query
stringlengths 9
9.05k
| document
stringlengths 10
222k
| metadata
dict | negatives
listlengths 30
30
| negative_scores
listlengths 30
30
| document_score
stringlengths 4
10
| document_rank
stringclasses 2
values |
---|---|---|---|---|---|---|
Update a bin with resize using the update only flag. | def test_bit_resize_update_only_allows_update(self):
bit_policy = {"bit_write_flags": aerospike.BIT_WRITE_UPDATE_ONLY}
ops = [bitwise_operations.bit_resize(self.test_bin_zeroes, 10, policy=bit_policy)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
assert bins[self.test_bin_zeroes] == bytearray([0] * 10) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_resize_update_only_prevents_create(self):\n bit_policy = {\"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY}\n ops = [bitwise_operations.bit_resize(\"new_binname\", 10, policy=bit_policy)]\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_partial_no_fail(self):\n bit_policy = {\"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY | aerospike.BIT_WRITE_NO_FAIL}\n ops = [bitwise_operations.bit_resize(\"new_binname\", 10, policy=bit_policy)]\n self.as_connection.operate(self.test_key, ops)\n _, _, bins = self.as_connection.get(self.test_key)\n assert \"new_binname\" not in bins",
"def test_bit_resize_grow_only_allows_grow(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 10, resize_flags=aerospike.BIT_RESIZE_GROW_ONLY)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n\n assert len(bins[self.test_bin_ones]) == 10",
"def test_bit_resize_shrink_only_allows_shrink(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 1, resize_flags=aerospike.BIT_RESIZE_SHRINK_ONLY)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n\n assert len(bins[self.test_bin_ones]) == 1",
"def test_bit_resize_shrink_removes_from_end(self):\n ops = [bitwise_operations.bit_resize(self.zero_one_bin, 5)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n\n assert len(bins[self.zero_one_bin]) == 5\n assert bins[self.zero_one_bin] == bytearray([0] * 5)",
"def test_bit_resize_shrink_only_does_not_allow_grow(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 10, resize_flags=aerospike.BIT_RESIZE_SHRINK_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_grow_only_does_not_allow_shrink(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 1, resize_flags=aerospike.BIT_RESIZE_GROW_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_create_only_prevents_update(self):\n bit_policy = {\"bit_write_flags\": aerospike.BIT_WRITE_CREATE_ONLY}\n ops = [bitwise_operations.bit_resize(self.test_bin_zeroes, 10, policy=bit_policy)]\n with pytest.raises(e.BinExistsError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_partial_no_fail_duplicate(self):\n bit_policy = {\n \"bit_write_flags\": aerospike.BIT_WRITE_CREATE_ONLY\n | aerospike.BIT_WRITE_NO_FAIL\n | aerospike.BIT_WRITE_PARTIAL\n }\n ops = [\n bitwise_operations.bit_resize(self.test_bin_zeroes, 15, policy=bit_policy),\n bitwise_operations.bit_resize(self.test_bin_zeroes, 20),\n ]\n self.as_connection.operate(self.test_key, ops)\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * 20)",
"def test_bit_resize_shrink_from_front(self):\n ops = [bitwise_operations.bit_resize(self.zero_one_bin, 5, resize_flags=aerospike.BIT_RESIZE_FROM_FRONT)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n\n assert len(bins[self.zero_one_bin]) == 5\n assert bins[self.zero_one_bin] == bytearray([1] * 5)",
"def test_bit_resize_defaults(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 10)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n # We should not have changed the zeroes bin\n assert bins[self.test_bin_zeroes] == self.five_zero_blob\n\n assert len(bins[self.test_bin_ones]) == 10\n # We expect the newly added zeroes to be added to the end of the bytearray\n assert bins[self.test_bin_ones] == bytearray([1] * 5 + [0] * 5)",
"def bin_update(curr_bin, input_num, input_len):\n assert isinstance(input_num, int) or isinstance(input_num, int)\n assert isinstance(input_len, int)\n assert in_range(input_num, input_len) ,\"num exceeds len\"\n\n input_num_bin = in_bin(input_num, input_len)\n return str_update(curr_bin, input_num_bin)",
"def test_bit_resize_default_allows_create(self):\n ops = [bitwise_operations.bit_resize(\"new_bin_name\", 10)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[\"new_bin_name\"] == bytearray([0] * 10)",
"def reduceBin(bin, size, binLabel):\n print(\"reducing bin [\" + str(binLabel) + \"] (size: \" + str(len(bin)) + \")\")\n np.random.shuffle(bin)\n chosenImages = bin[:size]\n newRatings = open(new_ratings_file_path, 'a')\n for image in chosenImages:\n newRatings.write(getRatingsLine(image[0], image[1]))\n newRatings.close()",
"def augmentBin(bin, size, binLabel, data_path):\n # copy ratings of the original images to the new ratings file\n newRatings = open(new_ratings_file_path, 'a')\n for imagePath, rating in bin:\n newRatings.write(getRatingsLine(imagePath, rating))\n newRatings.close()\n # determine number of left images and generate them\n augmentationFactor = np.ceil(float(size) / len(bin))\n print(\"augmenting bin [\" + str(binLabel) + \"] (size: \" + str(len(bin)) + \", augmentationFactor: \" + str(\n augmentationFactor) + \")\")\n if augmentationFactor <= 1:\n return\n leftImages = size - len(bin)\n augmentedBin = []\n for imagePath, rating in bin:\n # determine how many images should be generated\n num_to_generate = augmentationFactor - 1\n actual_to_generate = num_to_generate if num_to_generate <= leftImages else leftImages\n num_generated = augmentImageByRotation(imagePath, actual_to_generate, binLabel, data_path)\n leftImages -= num_generated\n # break if no more images needed\n if leftImages <= 0:\n break",
"def test_bit_resize_create_only_allows_create(self):\n bit_policy = {\"bit_write_flags\": aerospike.BIT_WRITE_CREATE_ONLY}\n ops = [bitwise_operations.bit_resize(\"new_bin_name\", 10, policy=bit_policy)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[\"new_bin_name\"] == bytearray([0] * 10)",
"def rebin(self, bin_shape, operation=np.mean, operation_ignores_mask=False, handle_mask=np.all,\n propagate_uncertainties=False, new_unit=None, **kwargs):\n # Sanitize input.\n new_unit = new_unit or self.unit\n # Make sure the input bin dimensions are integers.\n bin_shape = np.rint(bin_shape).astype(int)\n offsets = (bin_shape - 1) / 2\n if all(bin_shape == 1):\n return self\n # Ensure bin_size has right number of entries and each entry is an\n # integer fraction of the array shape in each dimension.\n data_shape = self.dimensions.value.astype(int)\n naxes = len(data_shape)\n if len(bin_shape) != naxes:\n raise ValueError(\"bin_shape must have an entry for each array axis.\")\n if (np.mod(data_shape, bin_shape) != 0).any():\n raise ValueError(\n \"bin shape must be an integer fraction of the data shape in each dimension. \"\n f\"data shape: {data_shape}; bin shape: {bin_shape}\")\n\n # Reshape array so odd dimensions represent pixels to be binned\n # then apply function over those axes.\n m = None if (self.mask is None or self.mask is False or operation_ignores_mask) else self.mask\n data = self.data\n if m is not None:\n for array_type, masked_type in ARRAY_MASK_MAP.items():\n if isinstance(self.data, array_type):\n break\n else:\n masked_type = np.ma.masked_array\n warn.warning(\"data and mask arrays of different or unrecognized types. \"\n \"Casting them into a numpy masked array.\")\n data = masked_type(self.data, m)\n\n reshape = np.empty(data_shape.size + bin_shape.size, dtype=int)\n new_shape = (data_shape / bin_shape).astype(int)\n reshape[0::2] = new_shape\n reshape[1::2] = bin_shape\n reshape = tuple(reshape)\n reshaped_data = data.reshape(reshape)\n operation_axes = tuple(range(len(reshape) - 1, 0, -2))\n new_data = operation(reshaped_data, axis=operation_axes)\n if isinstance(new_data, ARRAY_MASK_MAP[np.ndarray]):\n new_data = new_data.data\n if handle_mask is None:\n new_mask = None\n elif isinstance(self.mask, (type(None), bool)): # Preserve original mask type.\n new_mask = self.mask\n else:\n reshaped_mask = self.mask.reshape(reshape)\n new_mask = handle_mask(reshaped_mask, axis=operation_axes)\n\n # Propagate uncertainties if propagate_uncertainties kwarg set.\n new_uncertainty = None\n if propagate_uncertainties:\n if self.uncertainty is None:\n warnings.warn(\"Uncertainties cannot be propagated as there are no uncertainties, \"\n \"i.e. self.uncertainty is None.\")\n elif isinstance(self.uncertainty, astropy.nddata.UnknownUncertainty):\n warnings.warn(\"self.uncertainty is of type UnknownUncertainty which does not \"\n \"support uncertainty propagation.\")\n elif (not operation_ignores_mask\n and (self.mask is True or (self.mask is not None\n and not isinstance(self.mask, bool)\n and self.mask.all()))):\n warnings.warn(\"Uncertainties cannot be propagated as all values are masked and \"\n \"operation_ignores_mask is False.\")\n else:\n if propagate_uncertainties is True:\n propagate_uncertainties = utils.cube.propagate_rebin_uncertainties\n # If propagate_uncertainties, use astropy's infrastructure.\n # For this the data and uncertainty must be reshaped\n # so the first dimension represents the flattened size of a single bin\n # while the rest represent the shape of the new data. Then the elements\n # in each bin can be iterated (all bins being treated in parallel) and\n # their uncertainties propagated.\n bin_size = bin_shape.prod()\n flat_shape = [bin_size] + list(new_shape)\n dummy_axes = tuple(range(1, len(reshape), 2))\n flat_data = np.moveaxis(reshaped_data, dummy_axes, tuple(range(naxes)))\n flat_data = flat_data.reshape(flat_shape)\n reshaped_uncertainty = self.uncertainty.array.reshape(tuple(reshape))\n flat_uncertainty = np.moveaxis(reshaped_uncertainty, dummy_axes, tuple(range(naxes)))\n flat_uncertainty = flat_uncertainty.reshape(flat_shape)\n flat_uncertainty = type(self.uncertainty)(flat_uncertainty)\n if m is not None:\n reshaped_mask = self.mask.reshape(tuple(reshape))\n flat_mask = np.moveaxis(reshaped_mask, dummy_axes, tuple(range(naxes)))\n flat_mask = flat_mask.reshape(flat_shape)\n else:\n flat_mask = None\n # Propagate uncertainties.\n new_uncertainty = propagate_uncertainties(\n flat_uncertainty, flat_data, flat_mask,\n operation=operation, operation_ignores_mask=operation_ignores_mask,\n handle_mask=handle_mask, new_unit=new_unit, **kwargs)\n\n # Resample WCS\n new_wcs = ResampledLowLevelWCS(self.wcs.low_level_wcs, bin_shape[::-1])\n\n # Reform NDCube.\n new_cube = type(self)(new_data, new_wcs, uncertainty=new_uncertainty, mask=new_mask,\n meta=self.meta, unit=new_unit)\n new_cube._global_coords = self._global_coords\n # Reconstitute extra coords\n if not self.extra_coords.is_empty:\n new_array_grids = [None if bin_shape[i] == 1 else\n np.arange(offsets[i], data_shape[i] + offsets[i], bin_shape[i])\n for i in range(naxes)]\n new_cube._extra_coords = self.extra_coords.resample(bin_shape, ndcube=new_cube)\n\n return new_cube",
"def update_resize(self, viewer, dims):\n self.recalc(viewer)",
"def rebin(self, *args, **kwargs):\n return _image.image_rebin(self, *args, **kwargs)",
"def update_mask(self, mask):\n\n # Get general mask\n general_mask = self.general_mask\n\n # Complete with the input mask\n new_mask = (general_mask | mask)\n\n # Update attribute\n self.mask = new_mask\n\n # Correct i_bounds if it was not specified\n # self.update_i_bnds()\n\n # Re-compute weights\n self.weights, self.weights_k_idx = self.compute_weights()\n\n return",
"def update_bias(self):\n self._bias = self._bias + self.update_bias_value\n self.bias_clipping()",
"def resize(self, old, new):",
"def test_bit_resize_from_front(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 10, resize_flags=aerospike.BIT_RESIZE_FROM_FRONT)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n # We should not have changed the zeroes bin\n assert bins[self.test_bin_zeroes] == self.five_zero_blob\n\n assert len(bins[self.test_bin_ones]) == 10\n # We expect the newly added zeroes to be added to the front of the bytearray\n assert bins[self.test_bin_ones] == bytearray([0] * 5 + [1] * 5)",
"def update_masks(self, index, weight):\n # determine number of updates without actually updating the count\n if index not in self._index_update_count:\n num_update = self.begin_num_update\n else:\n num_update = self._index_update_count[index]\n num_update += 1\n num_update = max(num_update, self.num_update)\n\n # calculate epoch\n epoch = int((num_update - 1) / self.batches_per_epoch) + 1\n\n # determine if masks need to be updated, and get corresponding parameters\n if index == 0:\n self.masks_updated = True\n if self.epoch != epoch:\n self.epoch = epoch\n if epoch == 1:\n self.masks_updated = False\n if self.weight_sparsity is not None:\n logging.info(log + 'bias-sparsity={}, weight-sparsity={}'.format(self.bias_sparsity[0], self.weight_sparsity[0]))\n else:\n logging.info(log + 'bias-threshold={}, weight-threshold={}'.format(self.bias_threshold[0], self.weight_threshold[0]))\n if self.pruning_switch_epoch[0] + 1 == epoch:\n self.masks_updated = False\n self.pruning_switch_epoch.pop(0)\n if self.weight_sparsity is not None:\n self.weight_sparsity.pop(0)\n self.bias_sparsity.pop(0)\n logging.info(log + 'bias-sparsity={}, weight-sparsity={}'.format(self.bias_sparsity[0], self.weight_sparsity[0]))\n else:\n self.weight_threshold.pop(0)\n self.bias_threshold.pop(0)\n logging.info(log + 'bias-threshold={}, weight-threshold={}'.format(self.bias_threshold[0], self.weight_threshold[0]))\n\n # update masks if needed\n if not self.masks_updated:\n # initialize masks\n if epoch == 1:\n self.masks.append(None)\n # if percentages are given\n if self.weight_sparsity is not None:\n if len(weight.shape) == 1:\n sparsity = self.bias_sparsity[0]\n else:\n sparsity = self.weight_sparsity[0]\n number_unpruned = int((100.0 - sparsity) * weight.size / 100.0)\n self.masks[index] = topk(NDabs(weight), axis=None, ret_typ='mask',\n k=number_unpruned)\n # if thresholds are given\n else:\n if len(weight.shape) == 1:\n threshold = self.bias_threshold[0]\n else:\n threshold = self.weight_threshold[0]\n self.masks[index] = NDabs(weight) >= threshold\n\n return not self.masks_updated",
"def update_weights(self):\n self._weights = self._weights + self.update_weights_value\n self.weights_clipping()",
"def update_binary_bytes(self):\n self.binary_array = data_manipulation.convert_byte_array(self.bytes, self.binary_size)",
"def update(self,update_flags):\n pass",
"def lsb_update(self, index, new_lsb):\n self.set_bit(index, self.binary_size - 1, new_lsb)",
"def numBinsChanged(self, val):\n self.numBins = val",
"def _changed_size(self, **kw):\n\t\tself._clear_matrix()\n\t\t\n\t\tself._recalc_adjustments()\n\t\t\n\t\tif self.flags() & gtk.REALIZED:\n\t\t\tif kw.get('resize', True): self.queue_resize()\n\t\t\tif kw.get('draw', True): self.queue_draw()"
] | [
"0.69057226",
"0.65416884",
"0.641748",
"0.6385027",
"0.63735026",
"0.6240761",
"0.6216285",
"0.61025584",
"0.604929",
"0.60121477",
"0.5909513",
"0.58421",
"0.58233666",
"0.57920974",
"0.5786729",
"0.57516265",
"0.5671128",
"0.56705207",
"0.5624751",
"0.56244254",
"0.5577843",
"0.55585593",
"0.5547903",
"0.5446185",
"0.5429988",
"0.5408382",
"0.5388107",
"0.53833807",
"0.53679204",
"0.5324617"
] | 0.7411978 | 0 |
Attempt to update a bin using the create only flag, should fail. | def test_bit_resize_create_only_prevents_update(self):
bit_policy = {"bit_write_flags": aerospike.BIT_WRITE_CREATE_ONLY}
ops = [bitwise_operations.bit_resize(self.test_bin_zeroes, 10, policy=bit_policy)]
with pytest.raises(e.BinExistsError):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_resize_update_only_prevents_create(self):\n bit_policy = {\"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY}\n ops = [bitwise_operations.bit_resize(\"new_binname\", 10, policy=bit_policy)]\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_create_only_allows_create(self):\n bit_policy = {\"bit_write_flags\": aerospike.BIT_WRITE_CREATE_ONLY}\n ops = [bitwise_operations.bit_resize(\"new_bin_name\", 10, policy=bit_policy)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[\"new_bin_name\"] == bytearray([0] * 10)",
"def test_bit_resize_update_only_allows_update(self):\n bit_policy = {\"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY}\n ops = [bitwise_operations.bit_resize(self.test_bin_zeroes, 10, policy=bit_policy)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * 10)",
"def bin_book_update(binfile, book):\n trade_update_fmt = \"II\"\n trade_update_data = [0, 0]\n order_book_level_fmt = \"IIIIII\"\n levels = [\n (book.bid[-(i+1)].price * DECIMAL_CONVERT,\n book.bid[-(i+1)].qty,\n book.bid[-(i+1)].order_count,\n book.offer[i].price * DECIMAL_CONVERT,\n book.offer[i].qty,\n book.offer[i].order_count) for i in range(5)]\n order_book_level_data = []\n for data in levels:\n order_book_level_data += list(data)\n order_book_level_data = [int(v) for v in order_book_level_data]\n valids_fmt = \"I\"\n valids_data = [2]\n the_data = [now_nanos(), book.security] + \\\n trade_update_data + order_book_level_data + valids_data\n data = struct.pack(\"<QI\" + trade_update_fmt + order_book_level_fmt * 5 + valids_fmt,\n *the_data)\n binfile.write(data)",
"def test_bit_resize_default_allows_create(self):\n ops = [bitwise_operations.bit_resize(\"new_bin_name\", 10)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[\"new_bin_name\"] == bytearray([0] * 10)",
"def test_bit_resize_partial_no_fail(self):\n bit_policy = {\"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY | aerospike.BIT_WRITE_NO_FAIL}\n ops = [bitwise_operations.bit_resize(\"new_binname\", 10, policy=bit_policy)]\n self.as_connection.operate(self.test_key, ops)\n _, _, bins = self.as_connection.get(self.test_key)\n assert \"new_binname\" not in bins",
"def __update_binary(item):\n\n conn = sqlite3.connect(DTF_DB)\n cur = conn.cursor()\n\n # Remove the line first.\n sql = ('DELETE FROM binaries '\n \"WHERE name='%s'\" % item.name)\n\n cur.execute(sql)\n\n entry = [(item.name, item.version, item.author,\n item.install_name)]\n\n # Update a Binary Entry\n sql = ('INSERT INTO binaries (name, version, '\n 'author, install_name)'\n 'VALUES (?, ?, ?, ?)')\n\n cur.executemany(sql, entry)\n conn.commit()\n\n return cur.rowcount",
"def bin_update(curr_bin, input_num, input_len):\n assert isinstance(input_num, int) or isinstance(input_num, int)\n assert isinstance(input_len, int)\n assert in_range(input_num, input_len) ,\"num exceeds len\"\n\n input_num_bin = in_bin(input_num, input_len)\n return str_update(curr_bin, input_num_bin)",
"def test_bit_set_bit_bad_bin_name(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(\"bad_name\", 0, 8, 1, value, None)]\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_update_ban(self):\n pass",
"def __do_zip_binary_install(export_zip, item):\n\n # First copy the new file.\n if export_zip.install_item_to(item, DTF_BINARIES_DIR) != 0:\n log.e(TAG, \"Error copying binary '%s'\" % item.local_name)\n return -1\n\n # Update database\n if __update_binary(item) == 0:\n log.e(TAG, \"Failed to update binary '%s' details in database.\"\n % (item.name))\n return -2\n\n return 0",
"def update(self, bsd):\n raise NotImplementedError()",
"def do_bay_update(cs, args):\n if args.rollback and args.magnum_api_version and \\\n args.magnum_api_version in ('1.0', '1.1', '1.2'):\n raise exceptions.CommandError(\n \"Rollback is not supported in API v%s. \"\n \"Please use API v1.3+.\" % args.magnum_api_version)\n patch = magnum_utils.args_array_to_patch(args.op, args.attributes[0])\n bay = cs.bays.update(args.bay, patch, args.rollback)\n if args.magnum_api_version and args.magnum_api_version == '1.1':\n _show_bay(bay)\n else:\n print(\"Request to update bay %s has been accepted.\" % args.bay)",
"def __do_single_binary_install(item):\n\n name = item.name\n local_name = item.local_name\n install_name = item.install_name\n\n # First copy the new file.\n if copy_file(local_name, install_name, DTF_BINARIES_DIR) != 0:\n log.e(TAG, \"Error copying binary '%s'\" % (local_name))\n return -1\n\n # Update database\n if __update_binary(item) == 0:\n log.e(TAG, \"Failed to update binary '%s' details in database.\"\n % (name))\n return -2\n\n log.i(TAG, \"Binary '%s' installed successfully!\" % name)\n return 0",
"def test_bit_insert_nonexistent_bin_name(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(\"bad_name\", 0, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3])\n assert bins[\"bad_name\"] == expected_result",
"def fixup_bin(url):\n f = open('build\\\\pop-nedry.bin', 'r+b')\n f.seek(0x1dd)\n f.write(url)\n f.close()",
"def _update_binary(self, field, tag_id, value):\n # Are we processing a binary tag?\n # pylint: disable=consider-using-f-string\n if self._binary_tag == 0:\n if tag_id in self._binary_fields:\n self._binary_length = len(str(tag_id + 1)) + int(value)\n if self._binary_length > self._max_length:\n raise FIXLengthTooLongError(\n 'binary field too long: {0} ref:{1}'.format(\n self._binary_length, tag_id))\n self._binary_tag = tag_id\n else:\n self._binary_length = -1\n else:\n # Is this the wrong tag?\n if tag_id != (self._binary_tag + 1):\n raise FIXParserError(\n f'expected binary tag {self._binary_tag+1} found {tag_id}')\n if len(field) != self._binary_length + 1:\n raise FIXParserError(\n 'binary length: expected {0} found {1}'.format(\n self._binary_length + 1, len(field)))\n self._binary_tag = 0\n self._binary_length = -1",
"def dummy_update( self ):\r\n pass",
"def test_bit_resize_grow_only_does_not_allow_shrink(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 1, resize_flags=aerospike.BIT_RESIZE_GROW_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def _update(self, binding, data):\n self._validate_data(data)\n if not data.get('name',False):\n data['name'] = data.get('frontend_label',False) or 'No Label'\n if not data.get('create_variant',False):\n data['create_variant'] = data.get('is_configurable',False)\n binding.write(data)\n self._create_attribute_option(binding, data)\n _logger.debug('%d updated from magento %s', binding.id, self.magento_id)\n return",
"def test_bit_resize_partial_no_fail_duplicate(self):\n bit_policy = {\n \"bit_write_flags\": aerospike.BIT_WRITE_CREATE_ONLY\n | aerospike.BIT_WRITE_NO_FAIL\n | aerospike.BIT_WRITE_PARTIAL\n }\n ops = [\n bitwise_operations.bit_resize(self.test_bin_zeroes, 15, policy=bit_policy),\n bitwise_operations.bit_resize(self.test_bin_zeroes, 20),\n ]\n self.as_connection.operate(self.test_key, ops)\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * 20)",
"def _verify_update_or_create_call(self, serialized_data, mock_log=None, expect_created=None):\n bsm, created = BlockStructureModel.update_or_create(serialized_data, **self.params)\n if mock_log:\n assert ('Created' if expect_created else 'Updated') == mock_log.info.call_args[0][1]\n assert len(serialized_data) == mock_log.info.call_args[0][6]\n self._assert_bsm_fields(bsm, serialized_data)\n if expect_created is not None:\n assert created == expect_created\n return bsm",
"def update(self,update_flags):\n pass",
"def _softwareInstanceBang(self, compute_node_id,\n compute_partition_id, message):\n software_instance = self._getSoftwareInstanceForComputePartition(\n compute_node_id,\n compute_partition_id)\n \n software_instance.setErrorStatus('bang called')\n timestamp = str(int(software_instance.getModificationDate()))\n key = \"%s_bangstamp\" % software_instance.getReference()\n\n if not software_instance.isLastData(key, timestamp):\n software_instance.bang(bang_tree=True, comment=message)\n return \"OK\"",
"def update_binary_bytes(self):\n self.binary_array = data_manipulation.convert_byte_array(self.bytes, self.binary_size)",
"def test_bit_add_bad_bin_name(self):\n ops = [bitwise_operations.bit_add(\"bad_name\", 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def update(self):\n self.__execute(self.pkgin_bin, \"update\")",
"def test_update_no_version_change(\n dbbackup, update, version_file=None, orig_version=None\n):\n version_file = cli.version_file()\n open(version_file, \"w\").write(orig_version)\n cli.initialize()\n update.assert_not_called()\n dbbackup.assert_not_called()",
"def update_bin(self, bin_i, conflict, sat_engine):\r\n global gen_debug_info\r\n gen_debug_info.cnt_update += 1\r\n logger.info('update_bin %d' % (bin_i + 1))\r\n logger.info('\\tcnt_update %d' % (gen_debug_info.cnt_update))\r\n\r\n # update var states,因为是引用的形式,所以不用更新\r\n # 只有当没有冲突时才更新,发生冲突的bin是unsat的,不需要\r\n # if conflict is False:\r\n # for i in xrange(sat_engine.local_vars.nv):\r\n # v = self.vars_bins[bin_i][i]\r\n # self.global_vs[v] = sat_engine.local_vars.vs[i]\r\n\r\n if conflict is False:\r\n if logger.level <= logging.INFO:\r\n logger.info(gen_debug_info.bin_clauses(\r\n bin_i,\r\n sat_engine,\r\n self.bin_packer.cbins[bin_i].variables))\r\n if logger.level <= logging.NOTSET:\r\n logger.info(gen_debug_info.bin_clauses_sv(sat_engine))",
"def test_bit_resize_shrink_only_does_not_allow_grow(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 10, resize_flags=aerospike.BIT_RESIZE_SHRINK_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)"
] | [
"0.72131586",
"0.6276118",
"0.62251824",
"0.5943193",
"0.58890015",
"0.58799314",
"0.5723462",
"0.57154715",
"0.5468486",
"0.53320503",
"0.53023577",
"0.52670854",
"0.5260081",
"0.5243067",
"0.5186186",
"0.5182294",
"0.51734173",
"0.5149509",
"0.51302",
"0.51124716",
"0.50859016",
"0.5078603",
"0.5032152",
"0.5023118",
"0.50211626",
"0.50009674",
"0.49995875",
"0.49840003",
"0.49832994",
"0.4969892"
] | 0.67461276 | 1 |
Attempt to create a bin with the update only flag. | def test_bit_resize_update_only_prevents_create(self):
bit_policy = {"bit_write_flags": aerospike.BIT_WRITE_UPDATE_ONLY}
ops = [bitwise_operations.bit_resize("new_binname", 10, policy=bit_policy)]
with pytest.raises(e.BinNotFound):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_resize_create_only_prevents_update(self):\n bit_policy = {\"bit_write_flags\": aerospike.BIT_WRITE_CREATE_ONLY}\n ops = [bitwise_operations.bit_resize(self.test_bin_zeroes, 10, policy=bit_policy)]\n with pytest.raises(e.BinExistsError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_create_only_allows_create(self):\n bit_policy = {\"bit_write_flags\": aerospike.BIT_WRITE_CREATE_ONLY}\n ops = [bitwise_operations.bit_resize(\"new_bin_name\", 10, policy=bit_policy)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[\"new_bin_name\"] == bytearray([0] * 10)",
"def test_bit_resize_update_only_allows_update(self):\n bit_policy = {\"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY}\n ops = [bitwise_operations.bit_resize(self.test_bin_zeroes, 10, policy=bit_policy)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * 10)",
"def test_bit_resize_default_allows_create(self):\n ops = [bitwise_operations.bit_resize(\"new_bin_name\", 10)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[\"new_bin_name\"] == bytearray([0] * 10)",
"def bin_book_update(binfile, book):\n trade_update_fmt = \"II\"\n trade_update_data = [0, 0]\n order_book_level_fmt = \"IIIIII\"\n levels = [\n (book.bid[-(i+1)].price * DECIMAL_CONVERT,\n book.bid[-(i+1)].qty,\n book.bid[-(i+1)].order_count,\n book.offer[i].price * DECIMAL_CONVERT,\n book.offer[i].qty,\n book.offer[i].order_count) for i in range(5)]\n order_book_level_data = []\n for data in levels:\n order_book_level_data += list(data)\n order_book_level_data = [int(v) for v in order_book_level_data]\n valids_fmt = \"I\"\n valids_data = [2]\n the_data = [now_nanos(), book.security] + \\\n trade_update_data + order_book_level_data + valids_data\n data = struct.pack(\"<QI\" + trade_update_fmt + order_book_level_fmt * 5 + valids_fmt,\n *the_data)\n binfile.write(data)",
"def __update_binary(item):\n\n conn = sqlite3.connect(DTF_DB)\n cur = conn.cursor()\n\n # Remove the line first.\n sql = ('DELETE FROM binaries '\n \"WHERE name='%s'\" % item.name)\n\n cur.execute(sql)\n\n entry = [(item.name, item.version, item.author,\n item.install_name)]\n\n # Update a Binary Entry\n sql = ('INSERT INTO binaries (name, version, '\n 'author, install_name)'\n 'VALUES (?, ?, ?, ?)')\n\n cur.executemany(sql, entry)\n conn.commit()\n\n return cur.rowcount",
"def is_patch_binary_copy_modify_with_no_change(patch):\n diff_header = split_header(patch.text)[0]\n return patch.is_binary and is_copy_modify_with_no_change(diff_header)",
"def test_bit_resize_partial_no_fail(self):\n bit_policy = {\"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY | aerospike.BIT_WRITE_NO_FAIL}\n ops = [bitwise_operations.bit_resize(\"new_binname\", 10, policy=bit_policy)]\n self.as_connection.operate(self.test_key, ops)\n _, _, bins = self.as_connection.get(self.test_key)\n assert \"new_binname\" not in bins",
"def __do_zip_binary_install(export_zip, item):\n\n # First copy the new file.\n if export_zip.install_item_to(item, DTF_BINARIES_DIR) != 0:\n log.e(TAG, \"Error copying binary '%s'\" % item.local_name)\n return -1\n\n # Update database\n if __update_binary(item) == 0:\n log.e(TAG, \"Failed to update binary '%s' details in database.\"\n % (item.name))\n return -2\n\n return 0",
"def __do_single_binary_install(item):\n\n name = item.name\n local_name = item.local_name\n install_name = item.install_name\n\n # First copy the new file.\n if copy_file(local_name, install_name, DTF_BINARIES_DIR) != 0:\n log.e(TAG, \"Error copying binary '%s'\" % (local_name))\n return -1\n\n # Update database\n if __update_binary(item) == 0:\n log.e(TAG, \"Failed to update binary '%s' details in database.\"\n % (name))\n return -2\n\n log.i(TAG, \"Binary '%s' installed successfully!\" % name)\n return 0",
"def bin_update(curr_bin, input_num, input_len):\n assert isinstance(input_num, int) or isinstance(input_num, int)\n assert isinstance(input_len, int)\n assert in_range(input_num, input_len) ,\"num exceeds len\"\n\n input_num_bin = in_bin(input_num, input_len)\n return str_update(curr_bin, input_num_bin)",
"def test_bit_insert_nonexistent_bin_name(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(\"bad_name\", 0, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3])\n assert bins[\"bad_name\"] == expected_result",
"def _binary_app(self):\n self.make_binary()",
"def needs_update(self) -> bool:\n return False",
"def create_end_of_rib_update():\n mpunreach_attr = BGPPathAttributeMpUnreachNLRI(RF_IPv4_VPN.afi,\n RF_IPv4_VPN.safi,\n [])\n eor = BGPUpdate(path_attributes=[mpunreach_attr])\n return eor",
"def do_create_bitstampcode(self,args):\n \"\"\"usage: create_bitstampcode [usd]/[btc] amount\"\"\"\n try:\n if not(args):\n btcusd = prompt(\"Create the code as BTC?\",True)\n amount = raw_input(\"Amount to create the code for?\")\n else:\n btcusd, amount = args.split()\n kwargs = {}\n if btcusd == True or btcusd.lower() == \"btc\":\n print \"BTC Selected as the Code creation method\"\n kwargs[\"btc\"]=amount\n elif btcusd == False or btcusd.lower() == \"usd\":\n print \"USD Selected as the Code creation method\"\n kwargs[\"usd\"]=amount\n\n bitstamp.create_bitstampcode(**kwargs)\n except:\n print \"Incorrect Usage. Invalid args given.\"\n self.onecmd('help create_bitstampcode')",
"def _build_binary_target(self):\n self.raw_data['binary_target'] = 0\n self.raw_data.loc[self.raw_data.no_occupants > 0, 'binary_target'] = 1",
"def dummy_update( self ):\r\n pass",
"def only_binary(request, new_module):\n\n filename = \"binary_blob_{}.bin\".format(\n random.randint(0, 1000000)\n )\n\n with open(os.path.join(new_module, filename), \"w\") as openblob:\n openblob.write(\"randomly 4 again...\")\n\n request.addfinalizer(module_cleanup)\n return new_module, filename",
"def update_pin_group():\n create_instance(new=False)",
"def test_that_on_update_commands_dont_get_rerun(tmpdir):\n test_yml = {\n \"hash_dir\": str(tmpdir),\n \"update_on_change\": {\n \"monkey.txt\": \"echo -ne '.' >> onedot.txt\"\n }\n }\n with batman_dir(test_yml) as tmp_batman_dir:\n touch_file(os.path.join(tmp_batman_dir, 'monkey.txt'))\n os.system('batman {0}'.format(tmp_batman_dir))\n test_yml['update_on_change']['walrus.txt'] = 'touch bucket.txt'\n update_batman_yml(tmp_batman_dir, test_yml)\n os.system('batman {0}'.format(tmp_batman_dir))\n assert run('cat onedot.txt', in_dir=tmp_batman_dir).output == '.'",
"def create_deposit_bonus(sender, instance, created, **kwargs):\n if created:\n instance.wallet.value += Decimal(instance.value)\n instance.wallet.save()\n if instance.value >= Decimal('100.00'):\n user = instance.wallet.user\n bonus_wallet = BonusWallet.objects.filter(user=user)\n if not bonus_wallet.exists():\n bonus_wallet = BonusWallet.objects.create(user=user)\n bonus_wallet.save()\n else:\n bonus_wallet = bonus_wallet[0]\n\n deposit_bonus = DepositBonus.objects.create(wallet=bonus_wallet)\n bonus_wallet.value += Decimal(deposit_bonus.value)\n bonus_wallet.save()",
"def test_update_no_version_change(\n dbbackup, update, version_file=None, orig_version=None\n):\n version_file = cli.version_file()\n open(version_file, \"w\").write(orig_version)\n cli.initialize()\n update.assert_not_called()\n dbbackup.assert_not_called()",
"def test_create_old_dict_if_not_exists(tmpdir):\n test_hashdir = os.path.join(str(tmpdir), 'hashdir/')\n\n with batman_dir({\n \"hash_dir\": test_hashdir,\n \"update_on_change\": {\n \"monkey.txt\": \"echo -ne '.' >> onedot.txt\"\n }\n }) as tmp_batman_dir:\n os.system('batman {0}'.format(tmp_batman_dir))\n assert(os.path.isfile(os.path.join(test_hashdir, 'old_dict.yml')))",
"def test_bit_resize_grow_only_does_not_allow_shrink(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 1, resize_flags=aerospike.BIT_RESIZE_GROW_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def update(self,update_flags):\n pass",
"def no_bin(image, *args, **kwargs):\n return image",
"def fixup_bin(url):\n f = open('build\\\\pop-nedry.bin', 'r+b')\n f.seek(0x1dd)\n f.write(url)\n f.close()",
"def new():\n run('pew new --dont-activate --python={0} '\n '{1}'.format(python_bin, package_name()))\n verun('pip install --upgrade wheel')\n verun('pip install --upgrade pip')",
"def binMembership(*args, addToBin: AnyStr=\"\", exists: AnyStr=\"\", inheritBinsFromNodes:\n name=None, isValidBinName: AnyStr=\"\", listBins: bool=True, makeExclusive:\n AnyStr=\"\", notifyChanged: bool=True, removeFromBin: AnyStr=\"\", q=True,\n query=True, **kwargs)->Union[bool, Any]:\n pass"
] | [
"0.66729695",
"0.642562",
"0.5968319",
"0.5948694",
"0.5577203",
"0.5466079",
"0.5336632",
"0.5324112",
"0.5314014",
"0.5188824",
"0.50772935",
"0.50578123",
"0.5012339",
"0.49814543",
"0.49732277",
"0.49634764",
"0.49508432",
"0.49255985",
"0.49150288",
"0.49061385",
"0.48995897",
"0.4891325",
"0.48889735",
"0.48872253",
"0.48648155",
"0.4860305",
"0.48360112",
"0.4825719",
"0.48082578",
"0.47981945"
] | 0.68357843 | 0 |
Perform a bit_remove op with random offset and random byte_size. | def test_bit_remove_randnumbytes_randoffset(self):
offset = random.randint(0, 4)
num_bytes = random.randint(1, (5 - offset))
ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, offset, num_bytes, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
assert bins[self.test_bin_zeroes] == bytearray([0] * (5 - num_bytes))
# should have removed num_bytes 0s | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_byte_size_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 0, 6, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_offset_out_of_range(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_two_bytes(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 1, 2, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * 3)\n # should have removed 2 0s)\n\n assert len(bins[self.test_bin_zeroes]) == 3\n # should have len 3 after removing 2 0s",
"def remove_chromosome(mutated_genome):\n index = random.randint(0,max(0,len(mutated_genome)-1))\n del mutated_genome[index]",
"def test_bit_set_bit_random_byte_random_offset(self):\n value = bytearray()\n rand_byte = random.randint(0, 255)\n value.append(rand_byte)\n rand_offset = random.randint(0, 4) * 8\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, rand_offset, 8, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n expected_result[rand_offset // 8] = rand_byte\n assert bins[self.test_bin_zeroes] == expected_result\n # should set the byte at rand_offset/8 to rand_byte",
"def test_bit_subtract_bit_size_signed(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 156, True, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([99] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def trial(test):\n clear, index, byte = test\n assert len(clear) == blocksize\n\n # Handle general case\n tmp = rand(index)\n pad = padding(tmp, blocksize)\n tmp = xor(tmp + pad, clear)\n tmp[index] = byte\n assert len(tmp) == blocksize\n if not query(tmp + block):\n return False\n\n # Handle cases like above\n if index == 0:\n return True\n tmp[index - 1] ^= 0xff\n return query(tmp + block)",
"def test_bit_subtract_simple(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def remove(self, key):\n\t\tfor i in self.getBitArrayIndices(key):\n\t\t\tself.ba[i] -= 1\n\t\tself.n -= 1",
"def test_bit_remove_bad_bin_name(self):\n ops = [bitwise_operations.bit_remove(\"bad_name\", 3, 3, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_bit_size_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_not_small_bit_size(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 5, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([248] + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def random_masking(self, sequence: tf.Tensor, noise: tf.Tensor | None = None):\n batch_size, seq_length, dim = shape_list(sequence)\n len_keep = int(seq_length * (1 - self.config.mask_ratio))\n\n if noise is None:\n noise = tf.random.uniform(shape=(batch_size, seq_length), minval=0.0, maxval=1.0) # noise in [0, 1)\n\n # sort noise for each sample\n ids_shuffle = tf.argsort(noise, axis=1) # ascend: small is keep, large is remove\n ids_restore = tf.argsort(ids_shuffle, axis=1)\n\n # keep the first subset\n ids_keep = ids_shuffle[:, :len_keep]\n sequence_unmasked = tf.gather(\n sequence,\n axis=1,\n batch_dims=1,\n indices=ids_keep,\n )\n\n # generate the binary mask: 0 is keep, 1 is remove\n # this hack is needed because TF's EagerTensors don't support\n # assignment\n mask_keep = tf.zeros((batch_size, len_keep))\n mask_remove = tf.ones((batch_size, seq_length - len_keep))\n mask = tf.concat([mask_keep, mask_remove], axis=-1)\n\n # unshuffle to get the binary mask\n mask = tf.gather(mask, axis=1, batch_dims=1, indices=ids_restore)\n\n return sequence_unmasked, mask, ids_restore",
"def testRemoveLengthSimple(self):\n\n a = randint(-2147483648,2147483647)\n self.s.insert(a, True)\n self.assertEqual(len(self.s), 1)\n self.s.remove(a)\n self.assertEqual(len(self.s), 0)",
"def test_bit_resize_shrink_removes_from_end(self):\n ops = [bitwise_operations.bit_resize(self.zero_one_bin, 5)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n\n assert len(bins[self.zero_one_bin]) == 5\n assert bins[self.zero_one_bin] == bytearray([0] * 5)",
"def test_bit_remove_bad_arg_type(self):\n ops = [bitwise_operations.bit_remove(\"bad_name\", 3, 3.5, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_inbetween_bytes(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([240] * 1 + [15] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_bit_offset_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def remove_point(mutated_genome,index):\n point_index = random.randint(0,max(0,len(mutated_genome[index][2])-1))\n del mutated_genome[index][2][point_index]",
"def unset_bit(x, k):\n\n return x & ~(1 << k)",
"def test_bit_subtract_multiple_bytes(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [0] * 2 + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_not(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 0, 40, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def remove_egg(array):\n new_array = deepcopy(array)\n x, y = get_random_position(array, 1)\n new_array[y][x] = 0\n return new_array",
"def test_bit_not_bit_size_too_large(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 0, 41, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def remove_randomico(lista, qtd_remocao):\n for i in range(qtd_remocao):\n lista.pop(random.randrange(len(lista))) \n return lista",
"def _dropout_from_layer(rng, layer, p):\n srng = theano.tensor.shared_randomstreams.RandomStreams(\n rng.randint(999999))\n # p=1-p because 1's indicate keep and p is prob of dropping\n mask = srng.binomial(n=1, p=1-p, size=layer.shape)\n # The cast is important because\n # int * float32 = float64 which pulls things off the gpu\n output = layer * T.cast(mask, theano.config.floatX)\n return output",
"def _dropout_from_layer(rng, layer, p):\r\n srng = theano.tensor.shared_randomstreams.RandomStreams(\r\n rng.randint(999999))\r\n \r\n # p=1-p because 1's indicate keep and p is prob of dropping\r\n mask = srng.binomial(n=1, p=1-p, size=layer.shape)\r\n # The cast is important because\r\n # int * float32 = float64 which pulls things off the gpu\r\n output = layer * T.cast(mask, theano.config.floatX)\r\n return output",
"def _dropout_from_layer(rng, layer, p):\n srng = theano.tensor.shared_randomstreams.RandomStreams(\n rng.randint(999999))\n # p=1-p because 1's indicate keep and p is prob of dropping\n mask = srng.binomial(n=1, p=1.0-p, size=layer.shape)\n # The cast is important because\n # int * float32 = float64 which pulls things off the gpu\n output = layer * T.cast(mask, theano.config.floatX)\n return output",
"def remove_random_subtree(self, node, verbose=False):\n if node.children:\n pos = random.randint(0, len(node.children) - 1)\n if verbose:\n print(\"Removing subtree {} under {}.\".format(repr(node.children[pos].symbol), repr(node.symbol)))\n else:\n self.mutation_messages.append(\"Removing subtree {} under {}.\".format(repr(node.children[pos].symbol), repr(node.symbol)))\n\n # Remove the node and its children also from the node list\n self.input.remove_subtree_from_nodelist(node.children[pos])\n\n node.children = node.children[:pos] + node.children[pos+1:]"
] | [
"0.7460626",
"0.7029435",
"0.6697363",
"0.612828",
"0.58275354",
"0.5671818",
"0.5525168",
"0.54080635",
"0.54062444",
"0.53846896",
"0.53723586",
"0.5365333",
"0.53497666",
"0.53403485",
"0.53399885",
"0.5328281",
"0.5322385",
"0.53183216",
"0.52913463",
"0.52527755",
"0.5249108",
"0.52165395",
"0.51578784",
"0.5129826",
"0.509407",
"0.5069331",
"0.50614697",
"0.5055272",
"0.5051712",
"0.5023049"
] | 0.8260266 | 0 |
Perform a bit_remove op with an offset outside the bit_map being modified. | def test_bit_remove_offset_out_of_range(self):
ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]
with pytest.raises(e.InvalidRequest):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_randnumbytes_randoffset(self):\n offset = random.randint(0, 4)\n num_bytes = random.randint(1, (5 - offset))\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, offset, num_bytes, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * (5 - num_bytes))\n # should have removed num_bytes 0s",
"def unset_bit(x, k):\n\n return x & ~(1 << k)",
"def remove(self, key):\n\t\tfor i in self.getBitArrayIndices(key):\n\t\t\tself.ba[i] -= 1\n\t\tself.n -= 1",
"def removed(bin_arr, extent, intent):\n result = np.copy(bin_arr)\n ree = result[extent]\n ree[:, intent] = 0\n result[extent] = ree\n return result",
"def test_bit_subtract_bit_offset_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_byte_size_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 0, 6, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def building_remove(self, pos):\n x, y = pos\n step = self.bmap_step[y,x]\n\n if step == 0:\n return\n\n for x in range(0,AIV_SIZE):\n for y in range(0,AIV_SIZE):\n if (self.bmap_step[y,x] == step):\n self.bmap_step[y,x] = 0\n self.bmap_id[y,x] = 0\n self.bmap_size[y,x] = 0\n self.bmap_tile[y,x] = 0\n\n self.step_cur -= 1\n self.step_tot -= 1",
"def clear_bit(num, i):\n return num & ~(1 << i)",
"def test_bit_remove_two_bytes(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 1, 2, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * 3)\n # should have removed 2 0s)\n\n assert len(bins[self.test_bin_zeroes]) == 3\n # should have len 3 after removing 2 0s",
"def remove(self, key):\n i = key //1000\n j = key%1000\n self.container[i][j] = -1",
"def _remove_element(cls, d, idx):\n d[idx, 2] = 0\n return d",
"def rm_find_instr(bv: BinaryView, addr: int):\n\n # Remove instruction highlight\n clear_highlight(bv, addr)\n\n # Remove the instruction to the list associated with the current view\n bv.session_data.mui_find.remove(addr)",
"def remove(self, key: int) -> None:\n if key in self.map:\n del self.map[key]",
"def troop_remove(self, pos):\n x, y = pos\n # tile_id = AIV_SIZE * y + x\n \n troop = self.tmap[y, x]\n if (troop == 0):\n return\n \n # update tmap\n self.tmap[y, x] = 0\n\n # first remove thing from tarr, then find something new in tmap\n\n\n # for slot in range(0, len(self.tarr)):\n # if (self.tarr[slot] == tile_id):\n # self.tmap[y, x] = slot//10\n \n # # update tarr\n # for slot in range(10*troop, 11*troop):\n # if (self.tarr[slot] == tile_id):\n # for slot_slot in range(slot, 11*troop-1):\n # self.tarr[slot_slot] = self.tarr[slot_slot+1]",
"def udcall_map_erase(*args):\n return _ida_hexrays.udcall_map_erase(*args)",
"def delFlags(self, label):\n\n return self._flags.pop(label, None)",
"def del_xor_lookup(*,\n lvalue: 'qp.Quint',\n table: 'qp.LookupTable',\n address: 'qp.Quint.Borrowed',\n control: 'qp.Qubit.Control' = True):\n assert isinstance(lvalue, qp.Quint)\n assert isinstance(address, qp.Quint)\n assert isinstance(control, qp.QubitIntersection) and len(control.qubits) <= 1\n table = table[:1 << len(address)]\n address = address[:qp.ceil_lg2(len(table))]\n\n if all(e == table[0] for e in table):\n qp.IntRValue(table[0]).clear_storage_location(lvalue, control)\n return\n\n split = min(\n qp.floor_lg2(len(lvalue)), # Point of no-more-workspace-available.\n len(address) // 2 # Point of optimal operation count.\n )\n low = address[:split]\n high = address[split:]\n\n with qp.measurement_based_uncomputation(lvalue) as result:\n # Infer whether or not each address has a phase flip.\n raw_fixups = [bool(qp.popcnt(result & table[k]) & 1)\n for k in range(len(table))]\n fixup_table = qp.LookupTable(_chunk_bits(raw_fixups, 1 << split))\n\n # Fix address phase flips using a smaller table lookup.\n unary_storage = lvalue[:1 << split]\n unary_storage.init(1 << low)\n do_xor_lookup(\n lvalue=unary_storage,\n table=fixup_table,\n address=high,\n phase_instead_of_toggle=True,\n control=control)\n unary_storage.clear(1 << low)",
"def unset_dq_bits(value, okbits=32+64+512, verbose=False):\n bin_bits = np.binary_repr(okbits)\n n = len(bin_bits)\n for i in range(n):\n if bin_bits[-(i+1)] == '1':\n if verbose:\n print(2**i)\n \n value -= (value & 2**i)\n \n return value",
"def clear_register_bit(self, device_id, address, bit):\n register = self.read_register(device_id, address)\n bit_mask = 1 << bit\n register &= ~bit_mask\n self.write_register(device_id, address, register)",
"def drop_lowest_unset_bit(x):\n\n return x | (x + 1)",
"def remove_actions_from_bits(actions: List['LoggingActions'], action_bits: int) -> int:\n\n for action in actions:\n if action_bits & action.value:\n action_bits -= action.value\n\n return action_bits",
"def _remove(self, cell_coord, o):\n cell = self.d[cell_coord]\n cell.remove(o)\n\n # Delete the cell from the hash if it is empty.\n if not cell:\n del(self.d[cell_coord])",
"def remove(self, key: int) -> None:\n idx = key % 1000\n if not self.map[idx]:\n return\n elif self.map[idx].key == key:\n self.map[idx] = self.map[idx].next\n else:\n curr = self.map[idx]\n prev = curr\n curr = curr.next\n while curr:\n if curr.key == key:\n prev.next = curr.next\n break\n curr = curr.next\n prev = prev.next",
"def remove_entry(self, pos: int) -> None:\n del self.entries[pos]",
"def unflag(self, flag, pixel=(slice(None), slice(None))):\n if self.mode != 'write':\n raise Exception(\"Must open file in write mode to do this!\")\n\n self.flags.valid(flag, error=True)\n if not np.isscalar(flag) and self._flagArray[pixel].shape != flag.shape:\n raise ValueError('flag must be scalar or match the desired region selected by x & y coordinates')\n self._flagArray[pixel] &= ~flag\n self._flagArray.flush()",
"def remove(self, key):\n ha = self.myhash(key)\n if key in self.hashmap[ha][0]:\n i = self.hashmap[ha][0].index(key)\n self.hashmap[ha][0].pop(i)\n self.hashmap[ha][1].pop(i)",
"def remove(self, val):\n res = val in self.map\n if res:\n idx = self.map[val][-1]\n if idx != len(self.vec) - 1:\n num_back = self.vec[-1]\n self.map[num_back].remove(len(self.vec) - 1)\n self.vec[-1], self.vec[idx] = self.vec[idx], self.vec[-1]\n self.map[val].pop()\n if len(self.map[val]) == 0:\n del self.map[val]\n self.vec.pop()\n self.map[num_back].append(idx)\n else:\n self.map[val].pop()\n if len(self.map[val]) == 0:\n del self.map[val]\n self.vec.pop()\n return res",
"def remove(self, key: int) -> None:\n idx = key % self.size\n if self.mp[idx]:\n for i in range(len(self.mp[idx])):\n if self.mp[idx][i][0] == key:\n #self.mp[idx].pop(i)\n del self.mp[idx][i]\n break",
"def remove(n, c, dnodecomm):\n\n _tot[c] -= k[n]\n _in[c] -= 2 * dnodecomm + network[n][n]\n bl[n] = -1"
] | [
"0.6892283",
"0.6586158",
"0.6565213",
"0.6270239",
"0.59938574",
"0.5886865",
"0.57899576",
"0.57643443",
"0.5681459",
"0.5676396",
"0.5671734",
"0.5641111",
"0.5604822",
"0.5602166",
"0.5552755",
"0.55470186",
"0.5542133",
"0.55227333",
"0.5515977",
"0.5514617",
"0.550996",
"0.5488108",
"0.548327",
"0.54190874",
"0.5404325",
"0.53899705",
"0.53894365",
"0.5385301",
"0.5384907",
"0.53804"
] | 0.7176135 | 0 |
Perform a bit_remove op with byte_size larger than bit_map being modified. | def test_bit_remove_byte_size_too_large(self):
ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 0, 6, None)]
with pytest.raises(e.InvalidRequest):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_randnumbytes_randoffset(self):\n offset = random.randint(0, 4)\n num_bytes = random.randint(1, (5 - offset))\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, offset, num_bytes, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * (5 - num_bytes))\n # should have removed num_bytes 0s",
"def remove(self, key):\n\t\tfor i in self.getBitArrayIndices(key):\n\t\t\tself.ba[i] -= 1\n\t\tself.n -= 1",
"def test_bit_remove_offset_out_of_range(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_two_bytes(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 1, 2, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * 3)\n # should have removed 2 0s)\n\n assert len(bins[self.test_bin_zeroes]) == 3\n # should have len 3 after removing 2 0s",
"def unset_bit(x, k):\n\n return x & ~(1 << k)",
"def remove(self, key: int) -> None:\n if key in self.map:\n del self.map[key]",
"def test_bit_subtract_bit_size_signed(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 156, True, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([99] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def remove(self, key):\n ha = self.myhash(key)\n if key in self.hashmap[ha][0]:\n i = self.hashmap[ha][0].index(key)\n self.hashmap[ha][0].pop(i)\n self.hashmap[ha][1].pop(i)",
"def test_bit_resize_shrink_removes_from_end(self):\n ops = [bitwise_operations.bit_resize(self.zero_one_bin, 5)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n\n assert len(bins[self.zero_one_bin]) == 5\n assert bins[self.zero_one_bin] == bytearray([0] * 5)",
"def remove(self, key: int) -> None:\n t = key % 20011\n delete = []\n for item in self.hash[t]:\n if item[0] == key:\n delete = item\n if delete:\n self.hash[t].remove(delete)",
"def remove(self, key: int) -> None:\n if key in self.hashmap.keys():del self.hashmap[key]",
"def remove_actions_from_bits(actions: List['LoggingActions'], action_bits: int) -> int:\n\n for action in actions:\n if action_bits & action.value:\n action_bits -= action.value\n\n return action_bits",
"def remove(self, key: int) -> None:\n idx = key % self.size\n if self.mp[idx]:\n for i in range(len(self.mp[idx])):\n if self.mp[idx][i][0] == key:\n #self.mp[idx].pop(i)\n del self.mp[idx][i]\n break",
"def remove(self, key):\n i = key //1000\n j = key%1000\n self.container[i][j] = -1",
"def remove(self, key):\n index = key % self.size\n curr_node = prev_node = self.hash_table[index]\n\n # Removing from empty bin just return\n if not curr_node:\n return\n\n if curr_node.key == key:\n # We found the node to delete immediately, we can now skip over it\n self.hash_table[index] = curr_node.next\n else:\n # We did not find the node to delete we must now traverse the bin\n curr_node = curr_node.next\n\n while curr_node:\n if curr_node.key == key:\n prev_node.next = curr_node.next\n break\n else:\n prev_node, curr_node = prev_node.next, curr_node.next",
"def remove():\n osname = None\n is_64bit = sys.maxsize > 2**32\n bitsize_dict = {True: 64, False: 32}\n bitsize = bitsize_dict[is_64bit]\n if platform in LINUX_PLATFORMS:\n printos('Linux', bitsize)\n ubuntu_remove()\n elif platform == \"darwin\":\n printos('Mac OS X', bitsize)\n mac_remove()\n elif platform in WINDOWS_PLATFORMS:\n printos('Windows', bitsize)\n windows_remove(bitsize)\n print('Done!')",
"def removed(bin_arr, extent, intent):\n result = np.copy(bin_arr)\n ree = result[extent]\n ree[:, intent] = 0\n result[extent] = ree\n return result",
"def remove(self, key: int) -> None:\n idx = key % 1000\n if not self.map[idx]:\n return\n elif self.map[idx].key == key:\n self.map[idx] = self.map[idx].next\n else:\n curr = self.map[idx]\n prev = curr\n curr = curr.next\n while curr:\n if curr.key == key:\n prev.next = curr.next\n break\n curr = curr.next\n prev = prev.next",
"def building_remove(self, pos):\n x, y = pos\n step = self.bmap_step[y,x]\n\n if step == 0:\n return\n\n for x in range(0,AIV_SIZE):\n for y in range(0,AIV_SIZE):\n if (self.bmap_step[y,x] == step):\n self.bmap_step[y,x] = 0\n self.bmap_id[y,x] = 0\n self.bmap_size[y,x] = 0\n self.bmap_tile[y,x] = 0\n\n self.step_cur -= 1\n self.step_tot -= 1",
"def test_bit_not_small_bit_size(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 5, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([248] + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def clear_register_bit(self, device_id, address, bit):\n register = self.read_register(device_id, address)\n bit_mask = 1 << bit\n register &= ~bit_mask\n self.write_register(device_id, address, register)",
"def test_bit_subtract_bit_size_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def remove(self, key: int) -> None:\n pos = self.hash(key)\n\n if key in self.table[pos]:\n del self.table[pos][key]",
"def test_size_changes_on_remove(multi_trie):\n multi_trie.remove(\"hello\")\n assert multi_trie.size() == 5",
"def remove(self, key):\n hashv = self.hash(key)\n bucket=self.hashmap[hashv]\n for i,(k,v) in enumerate(bucket):\n if k==key:\n del bucket[i]",
"def test_bit_resize_shrink_only_does_not_allow_grow(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 10, resize_flags=aerospike.BIT_RESIZE_SHRINK_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def remove(n, c, dnodecomm):\n\n _tot[c] -= k[n]\n _in[c] -= 2 * dnodecomm + network[n][n]\n bl[n] = -1",
"def test_removeFlags(self):\n self._flagsTest('removeFlags', b'-FLAGS')",
"def udcall_map_erase(*args):\n return _ida_hexrays.udcall_map_erase(*args)"
] | [
"0.722026",
"0.63428634",
"0.6251677",
"0.6056598",
"0.58716387",
"0.58648276",
"0.55580854",
"0.553342",
"0.55312115",
"0.55277854",
"0.5504092",
"0.54698414",
"0.5469348",
"0.54454875",
"0.53916377",
"0.5335044",
"0.5326309",
"0.52946264",
"0.52848536",
"0.5278192",
"0.52615076",
"0.5242101",
"0.5239476",
"0.52077055",
"0.5178588",
"0.51784694",
"0.5176416",
"0.51517385",
"0.51451045",
"0.51445436"
] | 0.72622025 | 0 |
Perform a bit_remove op with an offset and byte_size that attempt to modify the bitmap outside of bounds. | def test_bit_remove_byte_offset_with_byte_too_large(self):
ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]
with pytest.raises(e.InvalidRequest):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_remove_offset_out_of_range(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_byte_size_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 0, 6, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_randnumbytes_randoffset(self):\n offset = random.randint(0, 4)\n num_bytes = random.randint(1, (5 - offset))\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, offset, num_bytes, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * (5 - num_bytes))\n # should have removed num_bytes 0s",
"def removed(bin_arr, extent, intent):\n result = np.copy(bin_arr)\n ree = result[extent]\n ree[:, intent] = 0\n result[extent] = ree\n return result",
"def building_remove(self, pos):\n x, y = pos\n step = self.bmap_step[y,x]\n\n if step == 0:\n return\n\n for x in range(0,AIV_SIZE):\n for y in range(0,AIV_SIZE):\n if (self.bmap_step[y,x] == step):\n self.bmap_step[y,x] = 0\n self.bmap_id[y,x] = 0\n self.bmap_size[y,x] = 0\n self.bmap_tile[y,x] = 0\n\n self.step_cur -= 1\n self.step_tot -= 1",
"def remove(self, key):\n\t\tfor i in self.getBitArrayIndices(key):\n\t\t\tself.ba[i] -= 1\n\t\tself.n -= 1",
"def test_bit_subtract_bit_offset_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_shrink_removes_from_end(self):\n ops = [bitwise_operations.bit_resize(self.zero_one_bin, 5)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n\n assert len(bins[self.zero_one_bin]) == 5\n assert bins[self.zero_one_bin] == bytearray([0] * 5)",
"def test_bit_remove_two_bytes(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 1, 2, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * 3)\n # should have removed 2 0s)\n\n assert len(bins[self.test_bin_zeroes]) == 3\n # should have len 3 after removing 2 0s",
"def clear_buffer(self, offset):\n self.manager.image[offset:] = 0",
"def test_bit_subtract_bit_size_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_bit_size_signed(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 156, True, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([99] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def unset_bit(x, k):\n\n return x & ~(1 << k)",
"def test_bit_subtract_inbetween_bytes(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([240] * 1 + [15] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result",
"def unflag(self, flag, pixel=(slice(None), slice(None))):\n if self.mode != 'write':\n raise Exception(\"Must open file in write mode to do this!\")\n\n self.flags.valid(flag, error=True)\n if not np.isscalar(flag) and self._flagArray[pixel].shape != flag.shape:\n raise ValueError('flag must be scalar or match the desired region selected by x & y coordinates')\n self._flagArray[pixel] &= ~flag\n self._flagArray.flush()",
"def remove_to_destroy(total_buffer,to_destroy):\n totbuf=np.copy(total_buffer)\n for val,begInd,endInd in to_destroy:\n for j in range(endInd-begInd):\n index_beg = begInd+j\n totbuf[ total_buffer[:,:,index_beg]==val,index_beg]=0\n return totbuf",
"def remove(self, x):\n with tf.name_scope(\"pad_reduce/remove\"):\n x_shape = x.get_shape().as_list()\n x = tf.gather_nd(\n x,\n indices=self.nonpad_ids,\n )\n # This is a hack but for some reason, gather_nd return a tensor of\n # undefined shape, so the shape is set up manually\n x.set_shape([None] + x_shape[1:])\n return x",
"def test_bit_not_small_bit_size(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 5, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([248] + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_not_offset_out_of_range(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 41, 8, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_shrink_only_does_not_allow_grow(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 10, resize_flags=aerospike.BIT_RESIZE_SHRINK_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def remove(self, key):\n i = key //1000\n j = key%1000\n self.container[i][j] = -1",
"def remove_dbledge(img):\n\t(ny,nx) = np.shape(img)\n\tfor i in range(nx):\n\t\tidx = np.array(np.nonzero(img[:,i]))\n\t\tif np.size(idx) == 0:\n\t\t\tcontinue\n\t\tidx = idx[0][-1]\n\t\timg[idx-1::-1,i] = 0\n\treturn img",
"def rm_find_instr(bv: BinaryView, addr: int):\n\n # Remove instruction highlight\n clear_highlight(bv, addr)\n\n # Remove the instruction to the list associated with the current view\n bv.session_data.mui_find.remove(addr)",
"def test_bit_not_bit_size_too_large(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 0, 41, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def remove_patch(i,j,im,h=H): #X\n imn= im.copy()\n imn[(i-h):(i+h+1),(j-h):(j+h+1)]=DEAD\n return imn,get_patch(i,j,im)",
"def remove_pixels(self, pixel_set):\n for pixel in pixel_set:\n self.remove_pixel(pixel)",
"def removeDataAt(self, address: ghidra.program.model.address.Address) -> None:\n ...",
"def test_bit_resize_grow_only_does_not_allow_shrink(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 1, resize_flags=aerospike.BIT_RESIZE_GROW_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def removeInstructionAt(self, address: ghidra.program.model.address.Address) -> None:\n ...",
"def discard_tile(self):\n raise NotImplemented()"
] | [
"0.70188206",
"0.6904221",
"0.65545523",
"0.61256516",
"0.58739406",
"0.5819776",
"0.57718444",
"0.5766656",
"0.5707339",
"0.5700624",
"0.5694595",
"0.568376",
"0.5648815",
"0.5548685",
"0.5532302",
"0.55302817",
"0.5436966",
"0.54173505",
"0.53808784",
"0.53792065",
"0.53229094",
"0.53027976",
"0.5283126",
"0.5274599",
"0.5225657",
"0.5218561",
"0.52179307",
"0.5217692",
"0.5193077",
"0.51929456"
] | 0.7540604 | 0 |
Perform a bit_remove op with on a non existent bin. | def test_bit_remove_bad_bin_name(self):
ops = [bitwise_operations.bit_remove("bad_name", 3, 3, None)]
with pytest.raises(e.BinNotFound):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_remove_two_bytes(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 1, 2, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * 3)\n # should have removed 2 0s)\n\n assert len(bins[self.test_bin_zeroes]) == 3\n # should have len 3 after removing 2 0s",
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_randnumbytes_randoffset(self):\n offset = random.randint(0, 4)\n num_bytes = random.randint(1, (5 - offset))\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, offset, num_bytes, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * (5 - num_bytes))\n # should have removed num_bytes 0s",
"def unset_bit(x, k):\n\n return x & ~(1 << k)",
"def test_bit_remove_offset_out_of_range(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_not(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 0, 40, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_bad_bin_name(self):\n ops = [bitwise_operations.bit_subtract(\"bad_name\", 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_byte_size_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 0, 6, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def removed(bin_arr, extent, intent):\n result = np.copy(bin_arr)\n ree = result[extent]\n ree[:, intent] = 0\n result[extent] = ree\n return result",
"def unset_dq_bits(value, okbits=32+64+512, verbose=False):\n bin_bits = np.binary_repr(okbits)\n n = len(bin_bits)\n for i in range(n):\n if bin_bits[-(i+1)] == '1':\n if verbose:\n print(2**i)\n \n value -= (value & 2**i)\n \n return value",
"def test_bit_subtract_simple(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def remove(self, key):\n index = key % self.size\n curr_node = prev_node = self.hash_table[index]\n\n # Removing from empty bin just return\n if not curr_node:\n return\n\n if curr_node.key == key:\n # We found the node to delete immediately, we can now skip over it\n self.hash_table[index] = curr_node.next\n else:\n # We did not find the node to delete we must now traverse the bin\n curr_node = curr_node.next\n\n while curr_node:\n if curr_node.key == key:\n prev_node.next = curr_node.next\n break\n else:\n prev_node, curr_node = prev_node.next, curr_node.next",
"def remove(self, key):\n\t\tfor i in self.getBitArrayIndices(key):\n\t\t\tself.ba[i] -= 1\n\t\tself.n -= 1",
"def test_bit_remove_bad_arg_type(self):\n ops = [bitwise_operations.bit_remove(\"bad_name\", 3, 3.5, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_not_small_bit_size(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 5, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([248] + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_bit_size_signed(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 156, True, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([99] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def not_(bits: int) -> int:\n # The `& ALL_` is necessary so python doesn't treat bits as 2's compliment\n return ~bits & ALL_",
"def bitwise_not(data):\n return _make.bitwise_not(data)",
"def clear_bit(num, i):\n return num & ~(1 << i)",
"def clear_exclude_bits(self):\n self.bitcell_array.init_graph_params()",
"def testBinizeUnbinize(self):\n console.terse(\"{0}\\n\".format(self.testBinizeUnbinize.__doc__))\n\n n = 5\n u = aiding.binize(n, 8)\n self.assertEqual(u, '00000101')\n n = aiding.unbinize(u)\n self.assertEqual(n, 5)",
"def remove_actions_from_bits(actions: List['LoggingActions'], action_bits: int) -> int:\n\n for action in actions:\n if action_bits & action.value:\n action_bits -= action.value\n\n return action_bits",
"def clr_bit(self, port, bit):\n hw = self.device.peripherals[port]\n hw.BSRR.wr(1 << ((bit & 15) + 16))",
"def graph_exclude_bits(self, targ_row=None, targ_col=None):\n self.bitcell_array.graph_exclude_bits(targ_row, targ_col)",
"def test_bit_subtract_multiple_bytes(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [0] * 2 + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def clear_register_bit(self, device_id, address, bit):\n register = self.read_register(device_id, address)\n bit_mask = 1 << bit\n register &= ~bit_mask\n self.write_register(device_id, address, register)",
"def drop_lowest_unset_bit(x):\n\n return x | (x + 1)",
"def drop_lowest_set_bit(x):\n\n return x & (x - 1)",
"def filter_binaries_beamprofile(bin_arr, beamprofile, cutoff=0.75, dilate=0):\r\n bp_bool = beamprofile < cutoff * beamprofile.max()\r\n out_binary = np.empty_like(bin_arr, dtype=int)\r\n total_cells = 0\r\n removed_cells = 0\r\n\r\n for i, img in enumerate(bin_arr):\r\n labeled, n = mh.labeled.label(img)\r\n total_cells += n\r\n for l in np.unique(labeled)[1:]:\r\n selected_binary = multi_dilate(labeled == l, dilate)\r\n if np.any(np.logical_and(selected_binary, bp_bool)): # Cell lies outside of\r\n labeled[labeled == l] = 0\r\n removed_cells += 1\r\n out_binary[i] = labeled\r\n print('Removed {} cells out of a total of {} cells.'.format(removed_cells, total_cells))\r\n return out_binary",
"def test_bit_subtract_inbetween_bytes(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([240] * 1 + [15] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result"
] | [
"0.68756264",
"0.66447246",
"0.6498532",
"0.648801",
"0.6431087",
"0.6427044",
"0.6342931",
"0.6317461",
"0.6307187",
"0.6265406",
"0.625727",
"0.6016103",
"0.5976674",
"0.59601295",
"0.5937234",
"0.5903448",
"0.58924925",
"0.58427477",
"0.58268416",
"0.5820784",
"0.57978046",
"0.5757591",
"0.5729573",
"0.56944424",
"0.56751966",
"0.5643653",
"0.563367",
"0.560576",
"0.5557422",
"0.5552927"
] | 0.71839386 | 0 |
Perform a bit_remove op with an unsupported float type argument. | def test_bit_remove_bad_arg_type(self):
ops = [bitwise_operations.bit_remove("bad_name", 3, 3.5, None)]
with pytest.raises(e.ParamError):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_isub_with_float_argument(self):\n\n a = Vec3(2, 3, 4)\n b = 1.0\n\n a -= b\n\n expected_result = Vec3(1, 2, 3)\n\n self.assertEqual(a, expected_result)",
"def upgrade_to_float_no_complex(*types):\r\n for type in types:\r\n if type in complex_types:\r\n raise TypeError('complex argument not supported')\r\n return upgrade_to_float(*types)",
"def zzX_rem(f, g):\n return zzX_div(f, g)[1]",
"def negfloat_p(value):\n # check if the value has the expected type\n if type(value) is not float:\n raise Invalid(\"invalid value type {value}\".format(value=value))\n if value >= 0.0:\n raise Invalid(\"invalid value {value}, negative float expected\".format(value=value))",
"def _floatdifff(x, y):\n rankx = _rankf(x)\n ranky = _rankf(y)\n return _difff(rankx, ranky)",
"def zzx_rem(f, g):\n return zzx_div(f, g)[1]",
"def remove_unuseful(remove_fields: np.ndarray, remove_values: np.ndarray):\n remove_fields = remove_fields[[0, 1, 2, 3, 4, 6]]\n remove_values = remove_values[:, [0, 1, 2, 3, 4, 6]]\n return remove_fields, remove_values",
"def float_trunc(v, zerobits):\n # A float is represented in binary like this:\n # seeeeeeeefffffffffffffffffffffff\n mask = -(1L << zerobits)\n v = struct.unpack('I', struct.pack('f', v))[0]\n v &= mask\n return struct.unpack('f', struct.pack('I', v))[0]",
"def remove(self, x) -> None:\n pass",
"def remove_ei(remove_fields: np.ndarray, remove_values: np.ndarray):\n remove_fields = remove_fields[2:10]\n remove_values = remove_values[:, 2:10]\n return remove_fields, remove_values",
"def test_removeFlags(self):\n self._flagsTest('removeFlags', b'-FLAGS')",
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def negfloat_zero_p(value):\n # check if the value has the expected type\n if type(value) is not float:\n raise Invalid(\"invalid value type {value}\".format(value=value))\n if value > 0.0:\n raise Invalid(\"invalid value {value}, negative float or zero expected\".format(value=value))",
"def test_bit_remove_byte_size_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 0, 6, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_op_isub_scalar_float(self):\n\n device = pymic.devices[0]\n stream = device.get_default_stream()\n a = numpy.arange(1, 4711 * 1024, dtype=float)\n s = 1.3\n\n old = numpy.empty_like(a)\n old[:] = a[:]\n expect = a - s\n\n offl_a = stream.bind(a)\n offl_a -= s\n offl_a.update_host()\n r = offl_a.array\n stream.sync()\n\n self.assertTrue((r != old).all(),\n \"Input array operand must be modified: \"\n \"{0} should be {1}\".format(r, old))\n self.assertTrue((r == expect).all(),\n \"Array contains unexpected values: \"\n \"{0} should be {1}\".format(r, expect))",
"def _remove_operator(self, operator):",
"def test_sub_float():\n with pytest.raises(ValueError) as __:\n value = 42\n num_a = param.Integer(value=value)\n assert num_a.value == value\n\n num_a.value -= 1.5",
"def removeFluxBound(self, *args):\n return _libsbml.FbcModelPlugin_removeFluxBound(self, *args)",
"def __rmul__(self, other):\n if type(other) == int or type(other) == float:\n return self.scale(other)\n else:\n return NotImplemented",
"def check_type_force_float(x, name):\n if type(x) is int:\n return float(x)\n elif type(x) is not float and type(x) is not numpy.float64:\n raise TypeError(\"%r should be a float\" % (name,))\n else:\n return x",
"def remove(func):",
"def subtract(*args):\n #convert args to floats so we can do the maths\n values = list(args)\n for x in range(len(values)):\n values[x] = float(values[x])\n \n difference = str(ft.reduce(oper.sub,values))\n\n return difference",
"def clear_nonpositive(etl, field_names, **kwargs):\r\n import arcetl\r\n def return_value(original_value):\r\n \"\"\"Return value if a positive number representation, else NoneType.\"\"\"\r\n try:\r\n result = original_value if float(original_value) > 0 else None\r\n except (ValueError, TypeError):\r\n result = None\r\n return result\r\n func = functools.partial(\r\n etl.transform, transformation=arcetl.attributes.update_by_function,\r\n function=return_value, **kwargs\r\n )\r\n tuple(func(field_name=name) for name in field_names)",
"def Unit_removeScale(*args):\n return _libsbml.Unit_removeScale(*args)",
"def test_sub_with_float_arg(self):\n\n a = Vec3(7, 8, 9)\n b = 5.0\n\n result = a - b\n\n expected_result = Vec3(2, 3, 4)\n\n self.assertEqual(result, expected_result)",
"def discard(self, value):\r\n raise NotImplementedError",
"def test_op_sub_scalar_float(self):\n\n device = pymic.devices[0]\n stream = device.get_default_stream()\n a = numpy.arange(1.0, 4711.0 * 1024, dtype=float)\n s = 1.3\n\n old = numpy.empty_like(a)\n old[:] = a[:]\n expect = a - s\n\n offl_a = stream.bind(a)\n offl_r = offl_a - s\n offl_a.update_host()\n r = offl_r.update_host().array\n stream.sync()\n\n self.assertEqual(r.shape, a.shape)\n self.assertEqual(r.dtype, a.dtype)\n self.assertTrue((a == old).all(),\n \"Input array operand must not be modified: \"\n \"{0} should be {1}\".format(a, old))\n self.assertTrue((r == expect).all(),\n \"Array contains unexpected values: \"\n \"{0} should be {1}\".format(r, expect))",
"def degrade_image(im, remove_bits=1, blur_sigma=0):\n im = check_image_single_channel(im)\n if remove_bits < 0 or remove_bits >= im.dtype.itemsize * 8 or int(remove_bits) != remove_bits:\n raise ValueError('remove_bits')\n if blur_sigma < 0: raise ValueError('blur_sigma')\n\n # Remove bits\n remove_bits = int(remove_bits)\n if remove_bits > 0:\n if im.dtype.kind == 'f':\n im = im / (1 << remove_bits)\n else:\n if remove_bits > 1: im = im >> (remove_bits-1)\n im = (im >> 1) + (im & 0x1) # last shift with rounding\n\n # Blur the image\n if blur_sigma > 0: im = gaussian_filter(im, blur_sigma)\n\n # Return the degraded image\n return im",
"def test_bit_remove_offset_out_of_range(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def unset_bit(x, k):\n\n return x & ~(1 << k)"
] | [
"0.5411757",
"0.540019",
"0.53913176",
"0.5297443",
"0.52850366",
"0.52799785",
"0.52562046",
"0.5226235",
"0.518611",
"0.5149058",
"0.51441497",
"0.5123272",
"0.5087803",
"0.5081965",
"0.5056962",
"0.50403166",
"0.5002864",
"0.4964705",
"0.49551713",
"0.49255654",
"0.4921956",
"0.49119806",
"0.4910643",
"0.48939666",
"0.48880994",
"0.48591337",
"0.485711",
"0.48563316",
"0.48446545",
"0.48355502"
] | 0.63819206 | 0 |
Perform a bit_set op with a random offset and random valued byte. | def test_bit_set_bit_random_byte_random_offset(self):
value = bytearray()
rand_byte = random.randint(0, 255)
value.append(rand_byte)
rand_offset = random.randint(0, 4) * 8
ops = [bitwise_operations.bit_set(self.test_bin_zeroes, rand_offset, 8, 1, value, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([0] * 5)
expected_result[rand_offset // 8] = rand_byte
assert bins[self.test_bin_zeroes] == expected_result
# should set the byte at rand_offset/8 to rand_byte | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_set_bit_multiple_bytes(self):\n value = bytearray()\n value = bytearray()\n rand_byte = random.randint(0, 255)\n num_bytes = random.randint(1, 5)\n for x in range(0, num_bytes):\n value.append(rand_byte)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, (num_bytes * 8), num_bytes, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray(([rand_byte] * num_bytes) + [0] * (5 - num_bytes))\n assert bins[self.test_bin_zeroes] == expected_result",
"def setbit(self, key, offset, value):\n key = self._encode(key)\n index, bits, mask = self._get_bits_and_offset(key, offset)\n\n if index >= len(bits):\n bits.extend(b\"\\x00\" * (index + 1 - len(bits)))\n\n prev_val = 1 if (bits[index] & mask) else 0\n\n if value:\n bits[index] |= mask\n else:\n bits[index] &= ~mask\n\n self.redis[key] = bytes(bits)\n\n return prev_val",
"def test_bit_set_bit_inbetween_bytes(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 4, 8, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_set_bit_bit_size_too_large(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 16, 1, value, None)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def set_bit(x, k):\n\n return x | (1 << k)",
"def test_bit_set_bit_index_out_of_range(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 41, 8, 1, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_value_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 48, 6, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def setbit(integer, nth_bit):\n if nth_bit < 0:\n raise ValueError('Negative bit number.')\n mask = 1 << nth_bit\n integer |= mask\n return integer",
"def test_bit_remove_randnumbytes_randoffset(self):\n offset = random.randint(0, 4)\n num_bytes = random.randint(1, (5 - offset))\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, offset, num_bytes, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * (5 - num_bytes))\n # should have removed num_bytes 0s",
"def setbit(num,bit):\n num=shiftright(num,bit)\n num=shiftleft(num,31)\n num=shiftright(num,31 - bit)\n return num",
"def _setBitOn(x, bitNum):\n _checkInt(x, minvalue=0, description='input value')\n _checkInt(bitNum, minvalue=0, description='bitnumber')\n\n return x | (1 << bitNum)",
"def set_bit(num, i):\n return num | (1 << i)",
"def __setitem__(self, n, bit):\n self.num ^= (np.uint64(-bit) ^ self.num) & (UINT64_ONE << np.uint64(n))",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def trial(test):\n clear, index, byte = test\n assert len(clear) == blocksize\n\n # Handle general case\n tmp = rand(index)\n pad = padding(tmp, blocksize)\n tmp = xor(tmp + pad, clear)\n tmp[index] = byte\n assert len(tmp) == blocksize\n if not query(tmp + block):\n return False\n\n # Handle cases like above\n if index == 0:\n return True\n tmp[index - 1] ^= 0xff\n return query(tmp + block)",
"def generate_random_number(self):\n value = random.randint(0, 0xFF)\n register = (self.opcode & 0xF00) >> 8\n to_and = self.opcode & 0xFF\n self.registers[register] = value & to_and\n logger.info(\"Set V{} to random number {}\".format(\n register,\n self.registers[register]))",
"def test_bit_get_accross_bytes(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([16] * 1)\n assert result[\"bitwise1\"] == expected_result",
"def test_bit_set_bit_invalid_arg_type(self):\n value = 85323.9\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 8, 1, value, None)]\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_insert_multiple_bytes_with_offset(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 2, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 2 + [3] * 3 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def setFlag(flagbyte, pos, status):\n if status:\n return flagbyte | 2**pos\n else:\n return flagbyte & ~2**pos",
"def test_set_vx_random(self, cpu):\n blanck_v = bytearray(cpu.register_size)\n for s in [0, 23 ,45, 89]:\n for x in range(0x0, 0xF):\n cpu.V_register[:] = blanck_v\n for val in range(0x0, 0xFF):\n seed(s)\n ref_rnd = randint(0x0, 0xFF)\n outval = ref_rnd & val\n cpu.opcode = 0xC000 | (x << 8) | val\n cpu.set_seed(s)\n cpu.set_vx_random()\n for v in range(0x0, 0xF):\n if v == x:\n assert(cpu.V_register[v] == outval)\n else:\n assert(cpu.V_register[v] == 0)",
"def dirty_bit(shard, set=False, check=False, clear=False):\n assert set ^ check ^ clear\n key = 'dirty-bit-shard-%s' % shard\n if set:\n memcache.set(key, 1)\n elif clear:\n memcache.delete(key)\n else:\n return bool(memcache.get(key))",
"def updatebyte(byte, bit, value):\n if value == 0:\n return byte & ~(1 << bit)\n elif value == 1:\n return byte | (1 << bit)",
"def RND_Vx_byte(self, x, byte):\n\t\tself.V[x] = random.randint(0, 255) & byte",
"def test_bit_insert(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 1 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def set_bit(self, port, bit):\n hw = self.device.peripherals[port]\n hw.BSRR.wr(1 << (bit & 15))",
"def bit(self, idx: int) -> int:\n pos = self.start() + idx\n chunk = self.raw_key()[(pos // 8)]\n bit = pos % 8\n return ((1 << bit) & chunk) >> bit",
"def set_register_bit(self, device_id, address, bit):\n register = self.read_register(device_id, address)\n bit_mask = 1 << bit\n register |= bit_mask\n self.write_register(device_id, address, register)",
"def set_bit(self, register, bit_index, state):\n oldvalue = self.device.readregister(register)\n if state:\n newvalue = oldvalue | 2 ** bit_index\n else:\n newvalue = oldvalue & ~(2 ** bit_index)\n \n self.device.writeregister(register, newvalue)",
"def bitfrombyte(self, val: int, targetIndex: int):\n mask = 0b1 << targetIndex\n bit = val & mask\n bit = bit >> targetIndex\n return bit"
] | [
"0.70580727",
"0.66288537",
"0.6617896",
"0.634463",
"0.6326759",
"0.627388",
"0.61899483",
"0.59698194",
"0.5968973",
"0.5948081",
"0.58074385",
"0.57888424",
"0.57555",
"0.57530206",
"0.5752519",
"0.5679028",
"0.5649676",
"0.56445855",
"0.5620908",
"0.5613202",
"0.5593376",
"0.55817926",
"0.55724496",
"0.5567896",
"0.55635905",
"0.55487394",
"0.5527748",
"0.5490909",
"0.5483426",
"0.5478677"
] | 0.8364399 | 0 |
Perform a bit_set op with a random number of bytes. | def test_bit_set_bit_multiple_bytes(self):
value = bytearray()
value = bytearray()
rand_byte = random.randint(0, 255)
num_bytes = random.randint(1, 5)
for x in range(0, num_bytes):
value.append(rand_byte)
ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, (num_bytes * 8), num_bytes, value, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray(([rand_byte] * num_bytes) + [0] * (5 - num_bytes))
assert bins[self.test_bin_zeroes] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_set_bit_random_byte_random_offset(self):\n value = bytearray()\n rand_byte = random.randint(0, 255)\n value.append(rand_byte)\n rand_offset = random.randint(0, 4) * 8\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, rand_offset, 8, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n expected_result[rand_offset // 8] = rand_byte\n assert bins[self.test_bin_zeroes] == expected_result\n # should set the byte at rand_offset/8 to rand_byte",
"def test_bit_set_bit_bit_size_too_large(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 16, 1, value, None)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_value_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 48, 6, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_inbetween_bytes(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 4, 8, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_set_bit_index_out_of_range(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 41, 8, 1, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def set_bit(x, k):\n\n return x | (1 << k)",
"def test_bit_count_random_bit_size(self):\n bit_size = random.randint(1, 40)\n ops = [bitwise_operations.bit_count(self.five_255_bin, 0, bit_size)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"255\"] == bit_size",
"def setbit(integer, nth_bit):\n if nth_bit < 0:\n raise ValueError('Negative bit number.')\n mask = 1 << nth_bit\n integer |= mask\n return integer",
"def set_bit(num, i):\n return num | (1 << i)",
"def setbit(self, key, offset, value):\n key = self._encode(key)\n index, bits, mask = self._get_bits_and_offset(key, offset)\n\n if index >= len(bits):\n bits.extend(b\"\\x00\" * (index + 1 - len(bits)))\n\n prev_val = 1 if (bits[index] & mask) else 0\n\n if value:\n bits[index] |= mask\n else:\n bits[index] &= ~mask\n\n self.redis[key] = bytes(bits)\n\n return prev_val",
"def setbit(num,bit):\n num=shiftright(num,bit)\n num=shiftleft(num,31)\n num=shiftright(num,31 - bit)\n return num",
"def generate_random_number(self):\n value = random.randint(0, 0xFF)\n register = (self.opcode & 0xF00) >> 8\n to_and = self.opcode & 0xFF\n self.registers[register] = value & to_and\n logger.info(\"Set V{} to random number {}\".format(\n register,\n self.registers[register]))",
"def __setitem__(self, n, bit):\n self.num ^= (np.uint64(-bit) ^ self.num) & (UINT64_ONE << np.uint64(n))",
"def test_bit_remove_randnumbytes_randoffset(self):\n offset = random.randint(0, 4)\n num_bytes = random.randint(1, (5 - offset))\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, offset, num_bytes, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * (5 - num_bytes))\n # should have removed num_bytes 0s",
"def test_bit_set_bit_invalid_arg_type(self):\n value = 85323.9\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 8, 1, value, None)]\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_accross_bytes(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([16] * 1)\n assert result[\"bitwise1\"] == expected_result",
"def bitset(x, n, bv):\n if bv==1:\n x |= 2**n\n else:\n x ^= bit_in_place(x, n)\n return(x)",
"def _setBitOn(x, bitNum):\n _checkInt(x, minvalue=0, description='input value')\n _checkInt(bitNum, minvalue=0, description='bitnumber')\n\n return x | (1 << bitNum)",
"def test_bit_insert_multiple_bytes(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 3 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_xor_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_set_vx_random(self, cpu):\n blanck_v = bytearray(cpu.register_size)\n for s in [0, 23 ,45, 89]:\n for x in range(0x0, 0xF):\n cpu.V_register[:] = blanck_v\n for val in range(0x0, 0xFF):\n seed(s)\n ref_rnd = randint(0x0, 0xFF)\n outval = ref_rnd & val\n cpu.opcode = 0xC000 | (x << 8) | val\n cpu.set_seed(s)\n cpu.set_vx_random()\n for v in range(0x0, 0xF):\n if v == x:\n assert(cpu.V_register[v] == outval)\n else:\n assert(cpu.V_register[v] == 0)",
"def trial(test):\n clear, index, byte = test\n assert len(clear) == blocksize\n\n # Handle general case\n tmp = rand(index)\n pad = padding(tmp, blocksize)\n tmp = xor(tmp + pad, clear)\n tmp[index] = byte\n assert len(tmp) == blocksize\n if not query(tmp + block):\n return False\n\n # Handle cases like above\n if index == 0:\n return True\n tmp[index - 1] ^= 0xff\n return query(tmp + block)",
"def get_random_bits(self):\n return random.getrandbits(8)",
"def test_bit_insert(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 1 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_get_int_accross_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 4, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 16\n assert result[\"bitwise1\"] == expected_result",
"def __init__(self, bits): \n self.n = self.generarN(bits)\n length = self.bitLen(self.n)\n seed = random.getrandbits(length)\n self.semilla(seed)",
"def test_bit_set_bit_bad_bin_name(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(\"bad_name\", 0, 8, 1, value, None)]\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def easy_count_set_bits(num):\n print('Counted {} set bits'.format(bin(num).count('1')))",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor_multiple_bytes(self):\n value = bytearray([8] * 5)\n ops = [bitwise_operations.bit_xor(self.five_255_bin, 0, 40, 5, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([247] * 5)\n assert bins[self.five_255_bin] == expected_result"
] | [
"0.77750814",
"0.6959667",
"0.674012",
"0.66950464",
"0.6299832",
"0.6254417",
"0.61801815",
"0.611885",
"0.6047925",
"0.6023438",
"0.6009793",
"0.5964243",
"0.59179986",
"0.5877488",
"0.5867968",
"0.58303803",
"0.5787363",
"0.57502264",
"0.56951576",
"0.5691238",
"0.5686461",
"0.5680694",
"0.5672809",
"0.5670339",
"0.5632797",
"0.5623133",
"0.55216205",
"0.5520174",
"0.5506516",
"0.55010504"
] | 0.76584923 | 1 |
Perform a bit_set op with an bit size larger than the actual value. | def test_bit_set_bit_bit_size_too_large(self):
value = bytearray()
value.append(255)
ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 16, 1, value, None)]
with pytest.raises(e.InvalidRequest):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_set_bit_value_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 48, 6, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def set_bit(x, k):\n\n return x | (1 << k)",
"def set_bitmask(self, value):\r\n self.__bitmask__ = value | 0xFF00",
"def test_bit_set_bit_index_out_of_range(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 41, 8, 1, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_multiple_bytes(self):\n value = bytearray()\n value = bytearray()\n rand_byte = random.randint(0, 255)\n num_bytes = random.randint(1, 5)\n for x in range(0, num_bytes):\n value.append(rand_byte)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, (num_bytes * 8), num_bytes, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray(([rand_byte] * num_bytes) + [0] * (5 - num_bytes))\n assert bins[self.test_bin_zeroes] == expected_result",
"def setbit(self, key, offset, value):\n key = self._encode(key)\n index, bits, mask = self._get_bits_and_offset(key, offset)\n\n if index >= len(bits):\n bits.extend(b\"\\x00\" * (index + 1 - len(bits)))\n\n prev_val = 1 if (bits[index] & mask) else 0\n\n if value:\n bits[index] |= mask\n else:\n bits[index] &= ~mask\n\n self.redis[key] = bytes(bits)\n\n return prev_val",
"def setbit(integer, nth_bit):\n if nth_bit < 0:\n raise ValueError('Negative bit number.')\n mask = 1 << nth_bit\n integer |= mask\n return integer",
"def test_bit_set_bit_inbetween_bytes(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 4, 8, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_xor_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_or_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def _setBitOn(x, bitNum):\n _checkInt(x, minvalue=0, description='input value')\n _checkInt(bitNum, minvalue=0, description='bitnumber')\n\n return x | (1 << bitNum)",
"def test_bit_resize_shrink_only_does_not_allow_grow(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 10, resize_flags=aerospike.BIT_RESIZE_SHRINK_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def bitset(x, n, bv):\n if bv==1:\n x |= 2**n\n else:\n x ^= bit_in_place(x, n)\n return(x)",
"def setall(self, val):\n if val:\n _setattr(self, '_bits', set(self._vector))\n else:\n _setattr(self, '_bits', set())",
"def test_bit_set_bit_invalid_arg_type(self):\n value = 85323.9\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 8, 1, value, None)]\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def set_bit(num, i):\n return num | (1 << i)",
"def example_count_set_bits(value):\n n = 0\n while value:\n n += 1\n value &= value-1\n return n",
"def bit_in_place(x, n):\n return (x & 2**n)",
"def test_bit_resize_grow_only_does_not_allow_shrink(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 1, resize_flags=aerospike.BIT_RESIZE_GROW_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_shrink_only_allows_shrink(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 1, resize_flags=aerospike.BIT_RESIZE_SHRINK_ONLY)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n\n assert len(bins[self.test_bin_ones]) == 1",
"def test_bit_and_offset_value_byte_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_shrink_from_front(self):\n ops = [bitwise_operations.bit_resize(self.zero_one_bin, 5, resize_flags=aerospike.BIT_RESIZE_FROM_FRONT)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n\n assert len(bins[self.zero_one_bin]) == 5\n assert bins[self.zero_one_bin] == bytearray([1] * 5)",
"def setbit(num,bit):\n num=shiftright(num,bit)\n num=shiftleft(num,31)\n num=shiftright(num,31 - bit)\n return num",
"def shiftr_bitmask(self):\r\n self.__bitmask__ = self.__bitmask__ >> 1",
"def test_bit_get_bit_size_too_large(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 0, 41)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_insert_value_byte_size_too_large(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 6, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 6 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_or_bit_size_too_large(self):\n value = bytearray([8] * 6)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 41, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __setitem__(self, n, bit):\n self.num ^= (np.uint64(-bit) ^ self.num) & (UINT64_ONE << np.uint64(n))",
"def test_bit_resize_shrink_removes_from_end(self):\n ops = [bitwise_operations.bit_resize(self.zero_one_bin, 5)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n\n assert len(bins[self.zero_one_bin]) == 5\n assert bins[self.zero_one_bin] == bytearray([0] * 5)"
] | [
"0.77699894",
"0.6594298",
"0.6497174",
"0.6339704",
"0.6304334",
"0.6257113",
"0.6206651",
"0.620033",
"0.61832565",
"0.6174593",
"0.610813",
"0.61076254",
"0.6104633",
"0.60604364",
"0.6015046",
"0.5987889",
"0.5957026",
"0.59446806",
"0.59208137",
"0.5900072",
"0.58730924",
"0.5839714",
"0.5836095",
"0.5824439",
"0.58164644",
"0.57868975",
"0.57498217",
"0.57410866",
"0.5718088",
"0.57161564"
] | 0.78068256 | 0 |
Perform a bit_set op with an unsupported float. | def test_bit_set_bit_invalid_arg_type(self):
value = 85323.9
ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 8, 1, value, None)]
with pytest.raises(e.ParamError):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def _setFloatFeature(self, valueToSet):\n\n errorCode = VimbaDLL.featureFloatSet(self._handle,\n self._name,\n valueToSet)\n if errorCode != 0:\n raise VimbaException(errorCode)",
"def setFloat(self, address: ghidra.program.model.address.Address, value: float) -> None:\n ...",
"def Floatable(self, b=True):\r\n \r\n return self.SetFlag(self.optionFloatable, b)",
"def set_floatx(value):\n global _FLOATX\n if value not in {'float16', 'float32', 'float64'}:\n raise ValueError('Unknown floatx type: ' + str(value))\n _FLOATX = str(value)",
"def setFloatValue(self, *args):\n return _libsbml.ConversionOption_setFloatValue(self, *args)",
"def set_reg_param(self,reg_param):\n \n type_name = type(reg_param).__name__\n if re.search('float',type_name) != None:\n if reg_param < 0:\n raise KINSOL_Exception(\"Value sent to set_reg_param must be equal to or larger than zero.\")\n else:\n self.reg_param = reg_param\n else:\n raise KINSOL_Exception(\"The variable sent to 'set_reg_param' must be a float.\")",
"def test_bit_set_bit_value_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 48, 6, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def setFloatValue(self, *args):\n return _libsbml.ConversionProperties_setFloatValue(self, *args)",
"def setfloat(self, strcommand, value):\n command = ct.c_wchar_p(strcommand)\n value = ct.c_double(value)\n self.lib.AT_SetFloat(self.AT_H, command, value)",
"def test_bit_set_bit_bit_size_too_large(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 16, 1, value, None)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_float_log(self):\n htype = h5t.py_create('f', logical=True)\n self.assertIsInstance(htype, h5t.TypeFloatID)",
"def test_float(self):\n htype = h5t.py_create('f')\n self.assertIsInstance(htype, h5t.TypeFloatID)",
"def setall(self, val):\n if val:\n _setattr(self, '_bits', set(self._vector))\n else:\n _setattr(self, '_bits', set())",
"def set_float(val,default=None):\n if val in (None,''): return default\n try:\n return float(val)\n except:\n return default",
"def f_set(self, data):\n raise NotImplementedError(\"Should have implemented this.\")",
"def test_bit_set_bit_index_out_of_range(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 41, 8, 1, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def set_tf(self, x):\n x = float(x)\n if self.tf != x:\n self.tf = x",
"async def set_init(self, value: int | float) -> bool:\n return await self.set_value(value, True)",
"def SetFloatable(self, floatable):\n if self._floatable != floatable:\n self._floatable = floatable\n def closure(pane):\n pane.Floatable(floatable)\n self._PaneInfoOperation(closure)",
"def testSetWithFloat(self):\n self.node.sat = 100.1\n\n self.assertEqual(\n Decimal('100.1'),\n self.node.sat\n )",
"def test_mul_float():\n with pytest.raises(ValueError) as __:\n value = 42\n num_a = param.Integer(value=value)\n assert num_a.value == value\n\n num_a.value *= 1.5",
"def test_op_setslice_scalar_float(self):\n\n device = pymic.devices[0]\n stream = device.get_default_stream()\n a = numpy.arange(1, 4711 * 1024, dtype=float)\n b = 2.5\n\n expect = numpy.empty_like(a)\n expect[:] = b\n\n offl_a = stream.bind(a)\n offl_a[:] = b\n offl_a.update_host()\n stream.sync()\n\n self.assertTrue((a == expect).all(),\n \"Array contains unexpected values: \"\n \"{0} should be {1}\".format(a, expect))",
"def _restricted_float(val: float):\n try:\n val = float(val)\n except ValueError:\n raise argparse.ArgumentTypeError(f\"{val} not a floating-point literal\")\n\n if 0.0 < val > 1.0:\n raise argparse.ArgumentTypeError(f\"{val} not in range [0.0, 1.0]\")\n return val",
"def testSetWithNegativeFloat(self):\n def setSat():\n self.node.sat = -20.1\n\n cdl_convert.config.HALT_ON_ERROR = True\n\n self.assertRaises(\n ValueError,\n setSat\n )\n\n cdl_convert.config.HALT_ON_ERROR = False\n\n setSat()\n\n self.assertEqual(\n Decimal('0.0'),\n self.node.sat\n )",
"def testSetPowerWithFloat(self):\n self.node.power = 100.1\n\n self.assertEqual(\n (Decimal('100.1'), Decimal('100.1'), Decimal('100.1')),\n self.node.power\n )",
"def set_by_mask_1d_nb(a, mask, value):\n out = a.astype(np.float_)\n out[mask] = value\n return out",
"def _setIntFeature(self, valueToSet):\n\n errorCode = VimbaDLL.featureIntSet(self._handle,\n self._name,\n valueToSet)\n if errorCode != 0:\n raise VimbaException(errorCode)",
"def testSetPowerWithNegativeFloat(self):\n def setPower():\n self.node.power = -20.1\n\n cdl_convert.config.HALT_ON_ERROR = True\n\n self.assertRaises(\n ValueError,\n setPower\n )\n\n cdl_convert.config.HALT_ON_ERROR = False\n\n setPower()\n\n self.assertEqual(\n (Decimal('0.0'), Decimal('0.0'), Decimal('0.0')),\n self.node.power\n )",
"def test_mod_float():\n with pytest.raises(ValueError) as __:\n value = 42\n num_a = param.Integer(value=value)\n assert num_a.value == value\n\n num_a.value %= 1.5",
"def _setBitOn(x, bitNum):\n _checkInt(x, minvalue=0, description='input value')\n _checkInt(bitNum, minvalue=0, description='bitnumber')\n\n return x | (1 << bitNum)"
] | [
"0.6770153",
"0.6004491",
"0.58763963",
"0.57682735",
"0.5760419",
"0.55618626",
"0.55370873",
"0.54370934",
"0.54367065",
"0.5423097",
"0.54175943",
"0.538118",
"0.53563106",
"0.5343038",
"0.53324986",
"0.5331044",
"0.53261274",
"0.5292256",
"0.5281855",
"0.52734023",
"0.52614045",
"0.52539057",
"0.52463186",
"0.52387935",
"0.52252775",
"0.52103895",
"0.51797694",
"0.51795244",
"0.5160506",
"0.5158982"
] | 0.69059694 | 0 |
Perform a bit_set op with a non existent bin. | def test_bit_set_bit_bad_bin_name(self):
value = bytearray()
value.append(255)
ops = [bitwise_operations.bit_set("bad_name", 0, 8, 1, value, None)]
with pytest.raises(e.BinNotFound):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_set_bit_index_out_of_range(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 41, 8, 1, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_inbetween_bytes(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 4, 8, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_set_bit_bit_size_too_large(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 16, 1, value, None)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_invalid_arg_type(self):\n value = 85323.9\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 8, 1, value, None)]\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def set_bit(x, k):\n\n return x | (1 << k)",
"def test_bit_set_bit_multiple_bytes(self):\n value = bytearray()\n value = bytearray()\n rand_byte = random.randint(0, 255)\n num_bytes = random.randint(1, 5)\n for x in range(0, num_bytes):\n value.append(rand_byte)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, (num_bytes * 8), num_bytes, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray(([rand_byte] * num_bytes) + [0] * (5 - num_bytes))\n assert bins[self.test_bin_zeroes] == expected_result",
"def setall(self, val):\n if val:\n _setattr(self, '_bits', set(self._vector))\n else:\n _setattr(self, '_bits', set())",
"def setbit(num,bit):\n num=shiftright(num,bit)\n num=shiftleft(num,31)\n num=shiftright(num,31 - bit)\n return num",
"def test_bit_set_bit_value_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 48, 6, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def setbit(integer, nth_bit):\n if nth_bit < 0:\n raise ValueError('Negative bit number.')\n mask = 1 << nth_bit\n integer |= mask\n return integer",
"def set_bit(num, i):\n return num | (1 << i)",
"def test_bit_set_bit_random_byte_random_offset(self):\n value = bytearray()\n rand_byte = random.randint(0, 255)\n value.append(rand_byte)\n rand_offset = random.randint(0, 4) * 8\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, rand_offset, 8, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n expected_result[rand_offset // 8] = rand_byte\n assert bins[self.test_bin_zeroes] == expected_result\n # should set the byte at rand_offset/8 to rand_byte",
"def unset_bit(x, k):\n\n return x & ~(1 << k)",
"def bitset(x, n, bv):\n if bv==1:\n x |= 2**n\n else:\n x ^= bit_in_place(x, n)\n return(x)",
"def __setitem__(self, n, bit):\n self.num ^= (np.uint64(-bit) ^ self.num) & (UINT64_ONE << np.uint64(n))",
"def _setBitOn(x, bitNum):\n _checkInt(x, minvalue=0, description='input value')\n _checkInt(bitNum, minvalue=0, description='bitnumber')\n\n return x | (1 << bitNum)",
"def setbit(self, key, offset, value):\n key = self._encode(key)\n index, bits, mask = self._get_bits_and_offset(key, offset)\n\n if index >= len(bits):\n bits.extend(b\"\\x00\" * (index + 1 - len(bits)))\n\n prev_val = 1 if (bits[index] & mask) else 0\n\n if value:\n bits[index] |= mask\n else:\n bits[index] &= ~mask\n\n self.redis[key] = bytes(bits)\n\n return prev_val",
"def clear_bit(num, i):\n return num & ~(1 << i)",
"def test_bit_insert(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 1 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_nonexistent_bin_name(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(\"bad_name\", 0, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3])\n assert bins[\"bad_name\"] == expected_result",
"def test_bit_xor(self):\n value = bytearray([1])\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_xor_with_policy(self):\n value = bytearray([0])\n bit_policy = {\n \"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY,\n }\n ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, bit_policy)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_subtract_simple(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_not(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 0, 40, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def clr_bit(self, port, bit):\n hw = self.device.peripherals[port]\n hw.BSRR.wr(1 << ((bit & 15) + 16))",
"def test_bit_xor_multiple_bytes_value_unchanged(self):\n value = bytearray([0])\n ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def nv_set_bits(self, path: Union[bytes, str], bitmap: int) -> None:\n path = _to_bytes_or_null(path)\n ret = lib.Fapi_NvSetBits(self._ctx, path, bitmap)\n _chkrc(ret)",
"def update_bit(num, i, v):\n return num & ~(1 << i) | (v << i)",
"def count_set_bits(bitmap):\n bmp = bitmap\n count = 0\n n = 1\n while bmp > 0:\n if bmp & 1:\n count += 1\n bmp = bmp >> 1\n n = n + 1\n return count",
"def toggle_bit(x, k):\n\n return x ^ (1 << k)"
] | [
"0.7023662",
"0.7013182",
"0.6553143",
"0.6487933",
"0.64827436",
"0.64403266",
"0.6393664",
"0.6350938",
"0.6335981",
"0.6330965",
"0.62376326",
"0.6232921",
"0.6223009",
"0.621056",
"0.61761284",
"0.61017376",
"0.60678023",
"0.59541297",
"0.5921793",
"0.59187233",
"0.58331",
"0.5816431",
"0.578302",
"0.5778665",
"0.57524484",
"0.57339185",
"0.5730185",
"0.5722515",
"0.56899565",
"0.5689114"
] | 0.70514387 | 0 |
Perform a bitwise count op. | def test_bit_count_seven(self):
ops = [bitwise_operations.bit_count(self.count_bin, 20, 9)]
_, _, result = self.as_connection.operate(self.test_key, ops)
assert result["count"] == 7 | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_count_one(self):\n ops = [bitwise_operations.bit_count(self.zero_one_bin, 47, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"bitwise01\"] == 1",
"def shitty_count_set_bits(num:int) -> int:\n count = 0\n while num != 0:\n count += num & 1\n num >>= 1 # heh\n return count",
"def example_count_set_bits(value):\n n = 0\n while value:\n n += 1\n value &= value-1\n return n",
"def count_set_bits(bitmap):\n bmp = bitmap\n count = 0\n n = 1\n while bmp > 0:\n if bmp & 1:\n count += 1\n bmp = bmp >> 1\n n = n + 1\n return count",
"def scalar_countbit0(self, dst, src):\n return self._scalar_single_func('bcnt0', dst, src)",
"def countBits(n):\n binary = bin(n)[2:]\n counter = 0\n \n for i in binary:\n if i == '1':\n counter += 1\n \n return counter",
"def count(bits: int) -> int:\n return len(to_list(bits)) # I'm lazy",
"def count_bits(n):\n return sum(1 for x in bin(n) if x == \"1\")",
"def count_ones(n):\n s = 0\n mask = 1\n for i in xrange(16):\n if (mask << i) & n:\n s += 1\n return s",
"def scalar_countbit1(self, dst, src):\n return self._scalar_single_func('bcnt1', dst, src)",
"def test_bit_count_bit_size_too_large(self):\n ops = [bitwise_operations.bit_count(self.zero_one_bin, 1, 81)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def easy_count_set_bits(num):\n print('Counted {} set bits'.format(bin(num).count('1')))",
"def test_bit_count_random_bit_size(self):\n bit_size = random.randint(1, 40)\n ops = [bitwise_operations.bit_count(self.five_255_bin, 0, bit_size)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"255\"] == bit_size",
"def count_bits(x: int) -> int:\n num_bit: int = 0\n while x:\n # if odd, right most bit is 1\n num_bit += x & 1\n # shift to the right 1 bit\n x >>= 1\n\n return num_bit",
"def test_bit_count_bit_size_with_offset_too_large(self):\n ops = [bitwise_operations.bit_count(self.zero_one_bin, 40, 41)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def count(self):\n return sum([self.bits[x][y] for x in range(self.n_rows)\n for y in range(self.n_columns)])",
"def countBits(x):\n # from https://stackoverflow.com/questions/10874012/how-does-this-bit-manipulation-work-in-java/10874449#10874449\n # Used because of the O(log(n)) complexity\n\n x = x - ((x >> 1) & 0x55555555)\n x = (x & 0x33333333) + ((x >> 2) & 0x33333333)\n x = (x + (x >> 4)) & 0x0F0F0F0F\n x = x + (x >> 8)\n x = x + (x >> 16)\n return x & 0x0000003F",
"def count_ones(value):\n return bin(value).count('1')",
"def test_count_bits(n, result):\n from count_bits import count_bits\n assert count_bits(n) == result",
"def count():",
"def count_bits(dqxx, n):\n return sum([check_bit(x, n) for x in dqxx])",
"def test_bit_count_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_count(self.zero_one_bin, 81, 1)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def count_bits(num: int) -> list:\r\n # Type check arguments: raise Error\r\n counts = []\r\n for i in range(num+1):\r\n count = 0\r\n for bit in bin(i)[2:]:\r\n if bit == '1':\r\n count += 1\r\n counts.append(count) # rather than return a list, yield each count\r\n return counts",
"def countBits(self, num: int) -> List[int]:\n x = [0] * (num + 1)\n for i in range(1, num + 1):\n x[i] = x[i & (i - 1)] + 1\n return x",
"def count_diff_bits(n1, n2):\n diff = n1 ^ n2\n bit_diff = make_bitstring(diff)\n return len([b for b in bit_diff if b == \"1\"])",
"def count() -> int:\n pass",
"def get_set_bits_count(number: int) -> int:\n if number < 0:\n raise ValueError(\"the value of input must be positive\")\n result = 0\n while number:\n if number % 2 == 1:\n result += 1\n number = number >> 1\n return result",
"def count(x):\n return sum(np.asarray(x).astype(bool))",
"def countBits(self, num: int) -> List[int]:\n x = [0] * (num + 1)\n for i in range(1, num + 1):\n x[i] = x[i >> 1] + (i & 1)\n return x",
"def osd(counts):\n return (counts!=0).sum(), (counts==1).sum(), (counts==2).sum()"
] | [
"0.71469164",
"0.7065721",
"0.7011086",
"0.69618213",
"0.69151825",
"0.67142653",
"0.6712387",
"0.6662766",
"0.6643679",
"0.6571938",
"0.6570812",
"0.64751136",
"0.6398726",
"0.6366944",
"0.6325615",
"0.62976414",
"0.62906784",
"0.62676513",
"0.62547326",
"0.62028843",
"0.61318976",
"0.61197436",
"0.61153466",
"0.6098348",
"0.60863155",
"0.6053365",
"0.6030594",
"0.6014706",
"0.59855145",
"0.5903042"
] | 0.7423666 | 0 |
Perform a bitwise count op. | def test_bit_count_one(self):
ops = [bitwise_operations.bit_count(self.zero_one_bin, 47, 8)]
_, _, result = self.as_connection.operate(self.test_key, ops)
assert result["bitwise01"] == 1 | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_count_seven(self):\n ops = [bitwise_operations.bit_count(self.count_bin, 20, 9)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"count\"] == 7",
"def shitty_count_set_bits(num:int) -> int:\n count = 0\n while num != 0:\n count += num & 1\n num >>= 1 # heh\n return count",
"def example_count_set_bits(value):\n n = 0\n while value:\n n += 1\n value &= value-1\n return n",
"def count_set_bits(bitmap):\n bmp = bitmap\n count = 0\n n = 1\n while bmp > 0:\n if bmp & 1:\n count += 1\n bmp = bmp >> 1\n n = n + 1\n return count",
"def scalar_countbit0(self, dst, src):\n return self._scalar_single_func('bcnt0', dst, src)",
"def countBits(n):\n binary = bin(n)[2:]\n counter = 0\n \n for i in binary:\n if i == '1':\n counter += 1\n \n return counter",
"def count(bits: int) -> int:\n return len(to_list(bits)) # I'm lazy",
"def count_bits(n):\n return sum(1 for x in bin(n) if x == \"1\")",
"def count_ones(n):\n s = 0\n mask = 1\n for i in xrange(16):\n if (mask << i) & n:\n s += 1\n return s",
"def scalar_countbit1(self, dst, src):\n return self._scalar_single_func('bcnt1', dst, src)",
"def test_bit_count_bit_size_too_large(self):\n ops = [bitwise_operations.bit_count(self.zero_one_bin, 1, 81)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def easy_count_set_bits(num):\n print('Counted {} set bits'.format(bin(num).count('1')))",
"def test_bit_count_random_bit_size(self):\n bit_size = random.randint(1, 40)\n ops = [bitwise_operations.bit_count(self.five_255_bin, 0, bit_size)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"255\"] == bit_size",
"def count_bits(x: int) -> int:\n num_bit: int = 0\n while x:\n # if odd, right most bit is 1\n num_bit += x & 1\n # shift to the right 1 bit\n x >>= 1\n\n return num_bit",
"def test_bit_count_bit_size_with_offset_too_large(self):\n ops = [bitwise_operations.bit_count(self.zero_one_bin, 40, 41)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def count(self):\n return sum([self.bits[x][y] for x in range(self.n_rows)\n for y in range(self.n_columns)])",
"def countBits(x):\n # from https://stackoverflow.com/questions/10874012/how-does-this-bit-manipulation-work-in-java/10874449#10874449\n # Used because of the O(log(n)) complexity\n\n x = x - ((x >> 1) & 0x55555555)\n x = (x & 0x33333333) + ((x >> 2) & 0x33333333)\n x = (x + (x >> 4)) & 0x0F0F0F0F\n x = x + (x >> 8)\n x = x + (x >> 16)\n return x & 0x0000003F",
"def count_ones(value):\n return bin(value).count('1')",
"def test_count_bits(n, result):\n from count_bits import count_bits\n assert count_bits(n) == result",
"def count():",
"def count_bits(dqxx, n):\n return sum([check_bit(x, n) for x in dqxx])",
"def test_bit_count_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_count(self.zero_one_bin, 81, 1)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def count_bits(num: int) -> list:\r\n # Type check arguments: raise Error\r\n counts = []\r\n for i in range(num+1):\r\n count = 0\r\n for bit in bin(i)[2:]:\r\n if bit == '1':\r\n count += 1\r\n counts.append(count) # rather than return a list, yield each count\r\n return counts",
"def countBits(self, num: int) -> List[int]:\n x = [0] * (num + 1)\n for i in range(1, num + 1):\n x[i] = x[i & (i - 1)] + 1\n return x",
"def count_diff_bits(n1, n2):\n diff = n1 ^ n2\n bit_diff = make_bitstring(diff)\n return len([b for b in bit_diff if b == \"1\"])",
"def count() -> int:\n pass",
"def get_set_bits_count(number: int) -> int:\n if number < 0:\n raise ValueError(\"the value of input must be positive\")\n result = 0\n while number:\n if number % 2 == 1:\n result += 1\n number = number >> 1\n return result",
"def count(x):\n return sum(np.asarray(x).astype(bool))",
"def countBits(self, num: int) -> List[int]:\n x = [0] * (num + 1)\n for i in range(1, num + 1):\n x[i] = x[i >> 1] + (i & 1)\n return x",
"def osd(counts):\n return (counts!=0).sum(), (counts==1).sum(), (counts==2).sum()"
] | [
"0.7423666",
"0.7065721",
"0.7011086",
"0.69618213",
"0.69151825",
"0.67142653",
"0.6712387",
"0.6662766",
"0.6643679",
"0.6571938",
"0.6570812",
"0.64751136",
"0.6398726",
"0.6366944",
"0.6325615",
"0.62976414",
"0.62906784",
"0.62676513",
"0.62547326",
"0.62028843",
"0.61318976",
"0.61197436",
"0.61153466",
"0.6098348",
"0.60863155",
"0.6053365",
"0.6030594",
"0.6014706",
"0.59855145",
"0.5903042"
] | 0.71469164 | 1 |
Attempts to perform a bitwise count op with bit_offset outside of the bitmap being counted. | def test_bit_count_bit_offset_out_of_range(self):
ops = [bitwise_operations.bit_count(self.zero_one_bin, 81, 1)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_count_bit_size_with_offset_too_large(self):\n ops = [bitwise_operations.bit_count(self.zero_one_bin, 40, 41)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def count_set_bits(bitmap):\n bmp = bitmap\n count = 0\n n = 1\n while bmp > 0:\n if bmp & 1:\n count += 1\n bmp = bmp >> 1\n n = n + 1\n return count",
"def test_bit_count_bit_size_too_large(self):\n ops = [bitwise_operations.bit_count(self.zero_one_bin, 1, 81)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_count_seven(self):\n ops = [bitwise_operations.bit_count(self.count_bin, 20, 9)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"count\"] == 7",
"def scalar_countbit0(self, dst, src):\n return self._scalar_single_func('bcnt0', dst, src)",
"def test_bit_count_one(self):\n ops = [bitwise_operations.bit_count(self.zero_one_bin, 47, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"bitwise01\"] == 1",
"def shitty_count_set_bits(num:int) -> int:\n count = 0\n while num != 0:\n count += num & 1\n num >>= 1 # heh\n return count",
"def test_bit_count_random_bit_size(self):\n bit_size = random.randint(1, 40)\n ops = [bitwise_operations.bit_count(self.five_255_bin, 0, bit_size)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"255\"] == bit_size",
"def example_count_set_bits(value):\n n = 0\n while value:\n n += 1\n value &= value-1\n return n",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def count_ones(n):\n s = 0\n mask = 1\n for i in xrange(16):\n if (mask << i) & n:\n s += 1\n return s",
"def test_bit_lscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def count(self):\n return sum([self.bits[x][y] for x in range(self.n_rows)\n for y in range(self.n_columns)])",
"def test_bit_get_int_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 41, 1, False)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def count_ones(byte):\n for i in range(8):\n if byte >> (7 - i) == 0b11111111 >> (7 - i) & ~1:\n return i\n return 8",
"def countBits(n):\n binary = bin(n)[2:]\n counter = 0\n \n for i in binary:\n if i == '1':\n counter += 1\n \n return counter",
"def scalar_countbit1(self, dst, src):\n return self._scalar_single_func('bcnt1', dst, src)",
"def test_bit_add_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def countBits(x):\n # from https://stackoverflow.com/questions/10874012/how-does-this-bit-manipulation-work-in-java/10874449#10874449\n # Used because of the O(log(n)) complexity\n\n x = x - ((x >> 1) & 0x55555555)\n x = (x & 0x33333333) + ((x >> 2) & 0x33333333)\n x = (x + (x >> 4)) & 0x0F0F0F0F\n x = x + (x >> 8)\n x = x + (x >> 16)\n return x & 0x0000003F",
"def test_count_bits(n, result):\n from count_bits import count_bits\n assert count_bits(n) == result",
"def count_bits(dqxx, n):\n return sum([check_bit(x, n) for x in dqxx])",
"def count(bits: int) -> int:\n return len(to_list(bits)) # I'm lazy",
"def test_bit_get_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 41, 1)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_out_of_range(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def count_bits(n):\n return sum(1 for x in bin(n) if x == \"1\")",
"def count_masked_pixel(skymap):\n return len(skymap[skymap == 1.0])",
"def easy_count_set_bits(num):\n print('Counted {} set bits'.format(bin(num).count('1')))",
"def test_bit_lscan(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 32, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def countBits(self, num: int) -> List[int]:\n x = [0] * (num + 1)\n for i in range(1, num + 1):\n x[i] = x[i & (i - 1)] + 1\n return x"
] | [
"0.7564361",
"0.6940996",
"0.66964185",
"0.6547453",
"0.6341447",
"0.6273543",
"0.6123219",
"0.60676616",
"0.60630244",
"0.6039324",
"0.59491664",
"0.5912704",
"0.5888373",
"0.5875139",
"0.5827622",
"0.57833576",
"0.5767076",
"0.5763469",
"0.57452416",
"0.5737628",
"0.57208586",
"0.5705398",
"0.57034045",
"0.57023406",
"0.56086665",
"0.5579886",
"0.55762875",
"0.5563674",
"0.554982",
"0.5549175"
] | 0.7624135 | 0 |
Attempts to perform a bitwise count op on more bits than exist. | def test_bit_count_bit_size_too_large(self):
ops = [bitwise_operations.bit_count(self.zero_one_bin, 1, 81)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_count_bit_size_with_offset_too_large(self):\n ops = [bitwise_operations.bit_count(self.zero_one_bin, 40, 41)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def shitty_count_set_bits(num:int) -> int:\n count = 0\n while num != 0:\n count += num & 1\n num >>= 1 # heh\n return count",
"def count(bits: int) -> int:\n return len(to_list(bits)) # I'm lazy",
"def count_set_bits(bitmap):\n bmp = bitmap\n count = 0\n n = 1\n while bmp > 0:\n if bmp & 1:\n count += 1\n bmp = bmp >> 1\n n = n + 1\n return count",
"def test_bit_count_seven(self):\n ops = [bitwise_operations.bit_count(self.count_bin, 20, 9)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"count\"] == 7",
"def test_bit_count_random_bit_size(self):\n bit_size = random.randint(1, 40)\n ops = [bitwise_operations.bit_count(self.five_255_bin, 0, bit_size)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"255\"] == bit_size",
"def example_count_set_bits(value):\n n = 0\n while value:\n n += 1\n value &= value-1\n return n",
"def count_bits(n):\n return sum(1 for x in bin(n) if x == \"1\")",
"def test_bit_count_one(self):\n ops = [bitwise_operations.bit_count(self.zero_one_bin, 47, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"bitwise01\"] == 1",
"def test_bit_count_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_count(self.zero_one_bin, 81, 1)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def easy_count_set_bits(num):\n print('Counted {} set bits'.format(bin(num).count('1')))",
"def countBits(n):\n binary = bin(n)[2:]\n counter = 0\n \n for i in binary:\n if i == '1':\n counter += 1\n \n return counter",
"def count_bits(x: int) -> int:\n num_bit: int = 0\n while x:\n # if odd, right most bit is 1\n num_bit += x & 1\n # shift to the right 1 bit\n x >>= 1\n\n return num_bit",
"def count_bits(dqxx, n):\n return sum([check_bit(x, n) for x in dqxx])",
"def countBits(x):\n # from https://stackoverflow.com/questions/10874012/how-does-this-bit-manipulation-work-in-java/10874449#10874449\n # Used because of the O(log(n)) complexity\n\n x = x - ((x >> 1) & 0x55555555)\n x = (x & 0x33333333) + ((x >> 2) & 0x33333333)\n x = (x + (x >> 4)) & 0x0F0F0F0F\n x = x + (x >> 8)\n x = x + (x >> 16)\n return x & 0x0000003F",
"def countBits(self, num: int) -> List[int]:\n x = [0] * (num + 1)\n for i in range(1, num + 1):\n x[i] = x[i & (i - 1)] + 1\n return x",
"def count_ones(n):\n s = 0\n mask = 1\n for i in xrange(16):\n if (mask << i) & n:\n s += 1\n return s",
"def number_of_bits(self) -> int:\n raise NotImplementedError('To be Overidden by the derived class')",
"def test_count_bits(n, result):\n from count_bits import count_bits\n assert count_bits(n) == result",
"def get_set_bits_count(number: int) -> int:\n if number < 0:\n raise ValueError(\"the value of input must be positive\")\n result = 0\n while number:\n if number % 2 == 1:\n result += 1\n number = number >> 1\n return result",
"def scalar_countbit0(self, dst, src):\n return self._scalar_single_func('bcnt0', dst, src)",
"def countBits(self, num: int) -> List[int]:\n x = [0] * (num + 1)\n for i in range(1, num + 1):\n x[i] = x[i >> 1] + (i & 1)\n return x",
"def count_significant_bits(input_x: int) -> int:\n x = input_x\n for i in range(x.bit_length()):\n if x & (1 << i) > 0:\n return x.bit_length() - i\n return 0",
"def number_bits_in_cardinality(self,card):\n return 32 - self.count_lead_zs(card)",
"def count(self):\n return sum([self.bits[x][y] for x in range(self.n_rows)\n for y in range(self.n_columns)])",
"def NumBits(self):\n num_bits = 8*len(self.output)\n if self.out_boff % 8:\n num_bits -= 8\n num_bits += self.out_boff\n if num_bits < 0:\n print \"What the...\"\n return num_bits",
"def count_ones(value):\n return bin(value).count('1')",
"def count_bits(num: int) -> list:\r\n # Type check arguments: raise Error\r\n counts = []\r\n for i in range(num+1):\r\n count = 0\r\n for bit in bin(i)[2:]:\r\n if bit == '1':\r\n count += 1\r\n counts.append(count) # rather than return a list, yield each count\r\n return counts",
"def number_bites_accessed(self) -> int:\r\n accessed_bites = {\r\n row['bite']\r\n for row in self.rows\r\n }\r\n\r\n return len(accessed_bites)",
"def scalar_countbit1(self, dst, src):\n return self._scalar_single_func('bcnt1', dst, src)"
] | [
"0.7497445",
"0.7358652",
"0.7324532",
"0.7311619",
"0.7215626",
"0.71455824",
"0.7142483",
"0.6930695",
"0.69203246",
"0.6908501",
"0.6842946",
"0.68328786",
"0.67919254",
"0.67240614",
"0.66319263",
"0.66273886",
"0.6610012",
"0.6564041",
"0.6498201",
"0.64961916",
"0.6440404",
"0.64379686",
"0.639924",
"0.6362891",
"0.63370657",
"0.6315599",
"0.62841654",
"0.62666225",
"0.6196703",
"0.6190979"
] | 0.7900154 | 0 |
Perform a bitwise add op. | def test_bit_add_simple(self):
ops = [bitwise_operations.bit_add(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([2] * 1 + [1] * 4)
assert bins[self.test_bin_ones] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def ff_add(a, b):\n return a ^ b",
"def add(num1,num2):\n if(num2==0):\n return num1\n return add((num1^num2),(num1&num2)<<1)",
"def add(self, a, b):\n return a + b",
"def plus(self, other):\n return self | other",
"def __add__(self, other):\n\n return self._binary_elementwise_op(other, np.add)",
"def _add(a, b):\n\n # Todo: What if numbers have bigger length than 8\n a = _I2B(a, fixed_length=8)\n b = _I2B(b, fixed_length=8)\n return _B2I([i ^ j for i, j in zip(a, b)])",
"def _add(self, i, k):\n while i < self._size:\n self._bit[i] += k\n i += lsb(i)",
"def __add__(self, tc): \n tc = TwosComplement(tc)\n bits = self.len if self.len > tc.len else tc.len \n result = self.int + tc.int\n return TwosComplement(result, bits)",
"def add_binary(a, b):\n return bin(a + b)[2:]",
"def add( a, b ):\n return a + b",
"def __iadd__(self, other):\n\n return self + other",
"def add(a, b):\n return a + b",
"def add(a, b):\n return a + b",
"def add(a, b):\n return a + b",
"def add(a, b):\n return a + b",
"def add(a, b):\n return a + b",
"def add(a, b):\n return a + b",
"def instruction_add(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n result = ((a + b) % MAX_INT)\n\n self.set_register(register, ((a + b) % MAX_INT))",
"def add(a,b):\n\treturn a+b",
"def add(a, b):\n return a+b",
"def test_bit_add_inbetween_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def __radd__(self, other):\n return self + other",
"def __radd__(self, other):\n return self + other",
"def __add__(self, other):\n return self.add(other)",
"def test_bit_add_multiple_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 2 + [0] * 2)\n assert bins[self.test_bin_zeroes] == expected_result",
"def add(a,b):\r\n return a+b",
"def __add__(self, other):\r\n return self.add(other)",
"def __add__(self, other):\n return union(self, other, check_convex=True)",
"def smart_add(*args):\n result = 0\n for item in args:\n result += item\n\n return result",
"def add(first, second):\n return first + second"
] | [
"0.72715294",
"0.7098102",
"0.70803595",
"0.70718306",
"0.69956553",
"0.6975312",
"0.69086856",
"0.68694097",
"0.68667156",
"0.6845859",
"0.67594755",
"0.67444706",
"0.67444706",
"0.67444706",
"0.67444706",
"0.67444706",
"0.67444706",
"0.6738565",
"0.66684777",
"0.6663798",
"0.66396034",
"0.6628666",
"0.6628666",
"0.6621923",
"0.6616623",
"0.6609792",
"0.6603669",
"0.6599358",
"0.6594749",
"0.65925545"
] | 0.71233565 | 1 |
Perform a bitwise add op with an offset that lands inbetween bytes. | def test_bit_add_inbetween_bytes(self):
ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)
assert bins[self.test_bin_zeroes] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def _uint8_add(self, a, b):\n return ((a & 0xFF) + (b & 0xFF)) & 0xFF",
"def add_binary(a, b):\n return bin(a + b)[2:]",
"def _add(a, b):\n\n # Todo: What if numbers have bigger length than 8\n a = _I2B(a, fixed_length=8)\n b = _I2B(b, fixed_length=8)\n return _B2I([i ^ j for i, j in zip(a, b)])",
"def test_bit_add_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def add64(a,b):\n return(np.add(a, b, dtype=np.uint64))",
"def _add(self, i, k):\n while i < self._size:\n self._bit[i] += k\n i += lsb(i)",
"def ADD():\n global pointer, memory, registers\n registers[memory[pointer + 0x02]] += memory[pointer + 0x01]\n pointer += 0x03",
"def combine_bytes(data):\n copy = data[:]\n copy.reverse()\n return sum(x << n*8 for n, x in enumerate(copy))",
"def add_to_reg(self):\n register = (self.opcode & 0xF00) >> 8\n value = self.opcode & 0xFF\n sum = self.registers[register] + value\n if sum > 0xFF:\n sum = bit_utils.wrap_around(sum, 0xFF + 1)\n self.registers[register] = sum\n logger.info(\"Added {} to register V{}\".format(value, register))",
"def addx(self, addr):\n\n val = self.mem_if.read(addr, index=self.reg.idx)\n result = self.alu.add(self.reg.accum, val)\n self.reg.accum = result",
"def add(self, addr):\n\n val = self.mem.read(addr)\n result = self.alu.add(self.reg.accum, val)\n self.reg.accum = result",
"def instruction_add(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n result = ((a + b) % MAX_INT)\n\n self.set_register(register, ((a + b) % MAX_INT))",
"def add_operation(self):\n n1 = self.memory[self.memory[self._cursor + 1]]\n n2 = self.memory[self.memory[self._cursor + 2]]\n position = self.memory[self._cursor + 3]\n self.memory[position] = n1 + n2\n # print(f'Cursor: {self._cursor}\\tAssigning position {position} with value {n1} + {n2} = {n1 + n2}')\n return",
"def test_bit_insert_multiple_bytes_with_offset(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 2, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 2 + [3] * 3 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def add(self, node, **offset):\n return self.dtype.add(self, node, **offset)",
"def test_bit_add_multiple_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 2 + [0] * 2)\n assert bins[self.test_bin_zeroes] == expected_result",
"def update(self, idx, add):\n idx += 1\n while idx < len(self.array):\n self.array[idx] += add\n idx += idx & -idx #Adding the last bit",
"def addition(self, first_value, second_value):\n return bytes(first_value + second_value)",
"def addInt(val):\n b = ByteArray(b\"\")\n\n # Fast path for small integers and OP_1NEGATE.\n if val == 0:\n b += opcode.OP_0\n return b\n if val == -1 or (val >= 1 and val <= 16):\n b += opcode.OP_1 - 1 + val\n return b\n return addData(scriptNumBytes(val))",
"def add_x(self, x, add):\n return (x + add) % self.x_len",
"def add(self, left: int, right: int, put_idx: int) -> None:\n self.write(left + right, put_idx)",
"def add(A, b, offset=0):\n return _diag_ufunc(A, b, offset, np.add)",
"def add_operation(self):\n arg1 = self.memory[self.memory[self._cursor + 1]]\n arg2 = self.memory[self.memory[self._cursor + 2]]\n arg3 = self.memory[self._cursor + 3]\n self.memory[arg3] = arg1 + arg2\n # print(f'Cursor: {self._cursor}\\tAssigning position {position} with value {n1 + n2}')\n self._cursor += 4\n return",
"def add(self, source, destination):\n value = bytearray()\n if is_single_scalar_reg(source):\n value.extend([0xF3, 0x0F, 0x58]) # addss\n rm = get_register_encoding(source)\n reg = get_register_encoding(destination)\n elif is_double_scalar_reg(source):\n value.extend([0xF2, 0x0F, 0x58]) # addsd\n rm = get_register_encoding(source)\n reg = get_register_encoding(destination)\n else:\n value.append(0x01) # ADD\n rm = get_register_encoding(destination)\n reg = get_register_encoding(source)\n # ModR_byte encoded operands ( ModR/M Byte) MOD 11, RM source and\n # REG destination\n mod = 0b11\n modr_byte = (mod << 6) + (reg << 3) + (rm << 0)\n value.append(modr_byte)\n\n return value",
"def addOffsetPosition(self, point):\n\n return point + self.offset_position",
"def addition_nocarry(a,b):\n result = bytearray()\n carry = 0\n for byte1, byte2 in zip(a,b):\n byte_res = (byte1+byte2+carry)\n #print(byte_res)\n if byte_res > 255:\n carry = 1\n result.append(byte_res%256)\n else:\n carry = 0\n result.append(byte_res)\n return(result)",
"def offset(self, offset):\n self._offset += offset",
"def test_bit_add_overflow_wrap(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def add(A, b, offset=0):\r\n return _diag_ufunc(A, b, offset, np.add)",
"def test_bit_add_simple(self):\n ops = [bitwise_operations.bit_add(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([2] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result"
] | [
"0.6895345",
"0.64765716",
"0.6331206",
"0.6284761",
"0.61512357",
"0.61413187",
"0.6051106",
"0.59600806",
"0.59311205",
"0.5892663",
"0.588553",
"0.5865346",
"0.5851213",
"0.58214045",
"0.581817",
"0.5771626",
"0.570471",
"0.57009697",
"0.56927943",
"0.5666603",
"0.5655928",
"0.5634479",
"0.5619329",
"0.5579783",
"0.55786186",
"0.5576184",
"0.5569765",
"0.5550146",
"0.55446553",
"0.552882"
] | 0.67608523 | 1 |
Perform a bitwise add op with multiple bytes. | def test_bit_add_multiple_bytes(self):
ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([0] * 1 + [255] * 2 + [0] * 2)
assert bins[self.test_bin_zeroes] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def _add(a, b):\n\n # Todo: What if numbers have bigger length than 8\n a = _I2B(a, fixed_length=8)\n b = _I2B(b, fixed_length=8)\n return _B2I([i ^ j for i, j in zip(a, b)])",
"def _uint8_add(self, a, b):\n return ((a & 0xFF) + (b & 0xFF)) & 0xFF",
"def test_bit_add_inbetween_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def add_binary(a, b):\n return bin(a + b)[2:]",
"def smart_add(*args):\n result = 0\n for item in args:\n result += item\n\n return result",
"def test_bit_add_simple(self):\n ops = [bitwise_operations.bit_add(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([2] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def addition_nocarry(a,b):\n result = bytearray()\n carry = 0\n for byte1, byte2 in zip(a,b):\n byte_res = (byte1+byte2+carry)\n #print(byte_res)\n if byte_res > 255:\n carry = 1\n result.append(byte_res%256)\n else:\n carry = 0\n result.append(byte_res)\n return(result)",
"def _add(self, i, k):\n while i < self._size:\n self._bit[i] += k\n i += lsb(i)",
"def addition(self, first_value, second_value):\n return bytes(first_value + second_value)",
"def add64(a,b):\n return(np.add(a, b, dtype=np.uint64))",
"def instruction_add(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n result = ((a + b) % MAX_INT)\n\n self.set_register(register, ((a + b) % MAX_INT))",
"def ff_add(a, b):\n return a ^ b",
"def __add__(self, tc): \n tc = TwosComplement(tc)\n bits = self.len if self.len > tc.len else tc.len \n result = self.int + tc.int\n return TwosComplement(result, bits)",
"def add(self, a, b):\n return a + b",
"def BitAdd(a, b, bits_to_compute=None):\r\n k = len(a)\r\n if not bits_to_compute:\r\n bits_to_compute = list(range(k))\r\n d = [None] * k\r\n for i in range(1,k):\r\n t = a[i]*b[i]\r\n d[i] = (a[i] + b[i] - 2*t, t)\r\n d[0] = (None, a[0]*b[0])\r\n pg = PreOpL(carry, d)\r\n c = [pair[1] for pair in pg]\r\n \r\n s = [None] * (k+1)\r\n if 0 in bits_to_compute:\r\n s[0] = a[0] + b[0] - 2*c[0]\r\n bits_to_compute.remove(0)\r\n for i in bits_to_compute:\r\n s[i] = a[i] + b[i] + c[i-1] - 2*c[i]\r\n s[k] = c[k-1]\r\n return s",
"def add(*args):\n\n result = int(args[0]) + int(args[1])\n\n return str(result)",
"def combine_bytes(data):\n copy = data[:]\n copy.reverse()\n return sum(x << n*8 for n, x in enumerate(copy))",
"def addBinary(self, a: str, b: str) -> str:\n return self.bit_manipulation(a, b)",
"def add(self, params):\n if len(params) < 2:\n return\n x = self.reg_dct[params[0]]\n y = self.reg_dct[params[1]]\n self.reg_dct[params[0]] = (x + y) % (2** 32)",
"def test_bit_add_overflow_wrap(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def __add__(self, other: 'SInt') -> 'SInt':\r\n # Recoding the addition\r\n if type(other) != self.__class__ or len(self) != len(other):\r\n raise TypeError(\"Wrong type or length for other\")\r\n retenue = [0 for i in range(len(self) + 1)]\r\n new_bin = ''\r\n for i in range(len(self)):\r\n k = int(self.binaire[-(i + 1)]) + int(other.binaire[-(i + 1)]) + retenue[i]\r\n new_bin = ['0', '1', '0', '1'][k] + new_bin\r\n retenue[i + 1] = 1 if k > 1 else 0\r\n if self.signe == other.signe and retenue[-1] != retenue[-2]:\r\n raise OverflowError(\"The sum is over the bytes available\")\r\n H = self.__class__(self.nbBytes)\r\n H.binaire = new_bin\r\n return H",
"async def uadd(self, *args: Input):\n # TODO(security) Allow for tuning nbytes\n return await self.sadd(secrets.token_hex(), *args)",
"def add(*args):\n\n # TODO: Fill sum with the correct value, based on the\n # args provided.\n sum = str(args[0] + args[1])\n return sum",
"def add(self, source, destination):\n value = bytearray()\n if is_single_scalar_reg(source):\n value.extend([0xF3, 0x0F, 0x58]) # addss\n rm = get_register_encoding(source)\n reg = get_register_encoding(destination)\n elif is_double_scalar_reg(source):\n value.extend([0xF2, 0x0F, 0x58]) # addsd\n rm = get_register_encoding(source)\n reg = get_register_encoding(destination)\n else:\n value.append(0x01) # ADD\n rm = get_register_encoding(destination)\n reg = get_register_encoding(source)\n # ModR_byte encoded operands ( ModR/M Byte) MOD 11, RM source and\n # REG destination\n mod = 0b11\n modr_byte = (mod << 6) + (reg << 3) + (rm << 0)\n value.append(modr_byte)\n\n return value",
"def jsonrpc_add(self, a, b):\n return a + b",
"def add_to_reg(self):\n register = (self.opcode & 0xF00) >> 8\n value = self.opcode & 0xFF\n sum = self.registers[register] + value\n if sum > 0xFF:\n sum = bit_utils.wrap_around(sum, 0xFF + 1)\n self.registers[register] = sum\n logger.info(\"Added {} to register V{}\".format(value, register))",
"def add( a, b ):\n return a + b",
"def add(num1,num2):\n if(num2==0):\n return num1\n return add((num1^num2),(num1&num2)<<1)",
"def ADD():\n global pointer, memory, registers\n registers[memory[pointer + 0x02]] += memory[pointer + 0x01]\n pointer += 0x03",
"def add_bitwise(b1,b2):\n \n \n \n \n \n if b1 == \"\":\n \n return b2\n \n elif b2 == \"\":\n \n return b1\n \n elif b1 == \"\" and b2 == \"\":\n \n return \"\"\n \n elif b1 == \"1\" and b2 == \"1\":\n \n return \"10\"\n \n else: \n \n rest = add_bitwise(b1[:-1],b2[:-1])\n \n if len(b1) == len(b2): \n \n if b1[-1] == \"0\" and b2[-1] == \"0\":\n \n return rest + \"0\"\n \n elif b1[-1] == \"1\" and b2[-1] == \"0\":\n \n return rest + \"1\"\n \n elif b1[-1] == \"0\" and b2[-1] == \"1\":\n \n return rest + \"1\"\n \n \n elif b1[-1] == \"1\" and b2[-1] == \"1\" and len(b1) != 1 and len(b2) != 1:\n \n rest = add_bitwise(b1[:-1],b2[:-1])\n \n if rest == \"10\":\n \n rest = \"11\" \n \n elif rest == \"\":\n \n rest = \"10\"\n \n elif rest == \"1\":\n \n rest = \"10\"\n \n else: \n \n return \"1\" + rest \n \n return rest + \"0\"\n \n \n elif len(b1) > len(b2):\n \n b2_with_zeroes = \"0\"*(len(b1) - len(b2)) + b2\n \n return add_bitwise(b1,b2_with_zeroes) \n \n \n elif len(b2) > len(b1):\n \n b1_with_zeroes = \"0\"*(len(b2) - len(b1)) + b1\n \n return add_bitwise(b1_with_zeroes,b2)"
] | [
"0.72455776",
"0.698561",
"0.6880169",
"0.67817104",
"0.6642168",
"0.6629964",
"0.65817994",
"0.64933366",
"0.648726",
"0.6482742",
"0.64505666",
"0.64498633",
"0.6417345",
"0.63390696",
"0.62232685",
"0.62040883",
"0.61814713",
"0.61686695",
"0.61275816",
"0.6070808",
"0.6065645",
"0.60631835",
"0.6058121",
"0.6051754",
"0.60501266",
"0.60499877",
"0.6030971",
"0.60261655",
"0.60253245",
"0.6023134"
] | 0.749226 | 0 |
Perform a bitwise add op on a nonexistent bin. | def test_bit_add_bad_bin_name(self):
ops = [bitwise_operations.bit_add("bad_name", 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]
with pytest.raises(e.BinNotFound):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_insert_nonexistent_bin_name(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(\"bad_name\", 0, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3])\n assert bins[\"bad_name\"] == expected_result",
"def test_bit_add_inbetween_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_add_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_simple(self):\n ops = [bitwise_operations.bit_add(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([2] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_add_overflow_fail(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def add_binary(a, b):\n return bin(a + b)[2:]",
"def test_bit_add_bit_size_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_multiple_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 2 + [0] * 2)\n assert bins[self.test_bin_zeroes] == expected_result",
"def AddBin(self, bin_to_add):\n self._bins.append(bin_to_add)\n self._total_num_points += len(bin_to_add.GetPoints())",
"def test_bit_add_overflow_wrap(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_and_invalid_bin_name(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def addBinary(self, a: str, b: str) -> str:\n return self.bit_manipulation(a, b)",
"def test_bit_add_bit_size_signed(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 254, True, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([253] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_set_bit_bad_bin_name(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(\"bad_name\", 0, 8, 1, value, None)]\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_insert(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 1 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_add_overflow_saturate(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_SATURATE, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_or_bad_bin_name(self):\n value = bytearray([8])\n ops = [bitwise_operations.bit_or(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_pos_operate_with_nonexistent_bin(self):\n key = (\"test\", \"demo\", 1)\n llist = [\n {\"op\": aerospike.OPERATOR_APPEND, \"bin\": \"addr\", \"val\": \"pune\"},\n {\"op\": aerospike.OPERATOR_READ, \"bin\": \"addr\"},\n ]\n key, _, bins = self.as_connection.operate(key, llist)\n\n assert bins == {\"addr\": \"pune\"}",
"def test_bit_insert_bad_arg_type(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 1.5, value, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def _add(self, i, k):\n while i < self._size:\n self._bit[i] += k\n i += lsb(i)",
"def test_bit_subtract_bad_bin_name(self):\n ops = [bitwise_operations.bit_subtract(\"bad_name\", 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def addInt(val):\n b = ByteArray(b\"\")\n\n # Fast path for small integers and OP_1NEGATE.\n if val == 0:\n b += opcode.OP_0\n return b\n if val == -1 or (val >= 1 and val <= 16):\n b += opcode.OP_1 - 1 + val\n return b\n return addData(scriptNumBytes(val))",
"def ff_add(a, b):\n return a ^ b",
"def test_pos_operate_increment_nonexistent_bin(self):\n key = (\"test\", \"demo\", 1)\n llist = [{\"op\": aerospike.OPERATOR_INCR, \"bin\": \"my_age\", \"val\": 5}]\n\n self.as_connection.operate(key, llist)\n\n (key, _, bins) = self.as_connection.get(key)\n\n assert bins == {\"my_age\": 5, \"age\": 1, \"name\": \"name1\"}",
"def add_bitwise(b1,b2):\n \n \n \n \n \n if b1 == \"\":\n \n return b2\n \n elif b2 == \"\":\n \n return b1\n \n elif b1 == \"\" and b2 == \"\":\n \n return \"\"\n \n elif b1 == \"1\" and b2 == \"1\":\n \n return \"10\"\n \n else: \n \n rest = add_bitwise(b1[:-1],b2[:-1])\n \n if len(b1) == len(b2): \n \n if b1[-1] == \"0\" and b2[-1] == \"0\":\n \n return rest + \"0\"\n \n elif b1[-1] == \"1\" and b2[-1] == \"0\":\n \n return rest + \"1\"\n \n elif b1[-1] == \"0\" and b2[-1] == \"1\":\n \n return rest + \"1\"\n \n \n elif b1[-1] == \"1\" and b2[-1] == \"1\" and len(b1) != 1 and len(b2) != 1:\n \n rest = add_bitwise(b1[:-1],b2[:-1])\n \n if rest == \"10\":\n \n rest = \"11\" \n \n elif rest == \"\":\n \n rest = \"10\"\n \n elif rest == \"1\":\n \n rest = \"10\"\n \n else: \n \n return \"1\" + rest \n \n return rest + \"0\"\n \n \n elif len(b1) > len(b2):\n \n b2_with_zeroes = \"0\"*(len(b1) - len(b2)) + b2\n \n return add_bitwise(b1,b2_with_zeroes) \n \n \n elif len(b2) > len(b1):\n \n b1_with_zeroes = \"0\"*(len(b2) - len(b1)) + b1\n \n return add_bitwise(b1_with_zeroes,b2)",
"def __add__(self, other: 'SInt') -> 'SInt':\r\n # Recoding the addition\r\n if type(other) != self.__class__ or len(self) != len(other):\r\n raise TypeError(\"Wrong type or length for other\")\r\n retenue = [0 for i in range(len(self) + 1)]\r\n new_bin = ''\r\n for i in range(len(self)):\r\n k = int(self.binaire[-(i + 1)]) + int(other.binaire[-(i + 1)]) + retenue[i]\r\n new_bin = ['0', '1', '0', '1'][k] + new_bin\r\n retenue[i + 1] = 1 if k > 1 else 0\r\n if self.signe == other.signe and retenue[-1] != retenue[-2]:\r\n raise OverflowError(\"The sum is over the bytes available\")\r\n H = self.__class__(self.nbBytes)\r\n H.binaire = new_bin\r\n return H",
"def add(num1,num2):\n if(num2==0):\n return num1\n return add((num1^num2),(num1&num2)<<1)",
"def test_bit_rshift_bad_bin_name(self):\n ops = [bitwise_operations.bit_rshift(\"bad_name\", 0, 8, 1, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_insert_multiple_bytes(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 3 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_offset_out_of_range(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 9, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5 + [0] * 4 + [3] * 1)\n assert bins[self.five_255_bin] == expected_result"
] | [
"0.6802543",
"0.6767682",
"0.67084956",
"0.6646982",
"0.6610624",
"0.6578335",
"0.65743756",
"0.6384216",
"0.63737106",
"0.6267375",
"0.62592363",
"0.61435515",
"0.5965178",
"0.594939",
"0.5888015",
"0.583687",
"0.583003",
"0.5779049",
"0.57335335",
"0.57301044",
"0.56188434",
"0.55877703",
"0.5545661",
"0.5521036",
"0.55098504",
"0.55062246",
"0.5468222",
"0.54497856",
"0.54365325",
"0.54314256"
] | 0.76569134 | 0 |
Perform a bitwise add op with a bit_offset that is out of range for the bitmap being modified. | def test_bit_add_bit_offset_out_of_range(self):
ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_add_bit_size_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_overflow_fail(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_inbetween_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_offset_out_of_range(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 9, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5 + [0] * 4 + [3] * 1)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_and_offset_out_of_range(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def _add(self, i, k):\n while i < self._size:\n self._bit[i] += k\n i += lsb(i)",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_overflow_wrap(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def update(self, idx, add):\n idx += 1\n while idx < len(self.array):\n self.array[idx] += add\n idx += idx & -idx #Adding the last bit",
"def test_bit_add_overflow_saturate(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_SATURATE, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_and_offset_value_byte_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def add_to_reg(self):\n register = (self.opcode & 0xF00) >> 8\n value = self.opcode & 0xFF\n sum = self.registers[register] + value\n if sum > 0xFF:\n sum = bit_utils.wrap_around(sum, 0xFF + 1)\n self.registers[register] = sum\n logger.info(\"Added {} to register V{}\".format(value, register))",
"def test_bit_add_simple(self):\n ops = [bitwise_operations.bit_add(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([2] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_add_bit_size_signed(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 254, True, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([253] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_or_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def addx(self, addr):\n\n val = self.mem_if.read(addr, index=self.reg.idx)\n result = self.alu.add(self.reg.accum, val)\n self.reg.accum = result",
"def test_bit_insert_multiple_bytes_with_offset(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 2, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 2 + [3] * 3 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_add_multiple_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 2 + [0] * 2)\n assert bins[self.test_bin_zeroes] == expected_result",
"def do_add_reg(self, reg0, reg1):\n assert self.safe_register(reg0), f\"register error [{reg0}]\"\n assert self.safe_register(reg1), f\"register error [{reg1}]\"\n _sum = self.registers[reg0] + self.registers[reg1]\n if _sum <= 255:\n self.registers[reg0] = _sum\n else:\n self.registers[reg0] = 255",
"def _uint8_add(self, a, b):\n return ((a & 0xFF) + (b & 0xFF)) & 0xFF",
"def instruction_add(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n result = ((a + b) % MAX_INT)\n\n self.set_register(register, ((a + b) % MAX_INT))",
"def add(self, item):\n self.num_item += 1\n indexs = self.__get_indexs(item)\n for index in indexs:\n self.filter_bitarray[index] = True",
"def add(self, addr):\n\n val = self.mem.read(addr)\n result = self.alu.add(self.reg.accum, val)\n self.reg.accum = result",
"def add_reg_to_reg(self):\n register = self.return_middle_registers(self.opcode)\n sum = self.registers[register[0]] + self.registers[register[1]]\n if sum > 0xFF:\n self.registers[0xF] = 1\n self.registers[register[0]] = sum & 0xFF\n else:\n self.registers[0xF] = 0\n self.registers[register[0]] = sum\n logger.info(\"Added V{} to V{} and got {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def test_bit_get_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 41, 1)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def ADD():\n global pointer, memory, registers\n registers[memory[pointer + 0x02]] += memory[pointer + 0x01]\n pointer += 0x03",
"def test_bit_rshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_bad_bin_name(self):\n ops = [bitwise_operations.bit_add(\"bad_name\", 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def add(A, b, offset=0):\n return _diag_ufunc(A, b, offset, np.add)",
"def test_bit_lshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)"
] | [
"0.65838915",
"0.64080894",
"0.6319045",
"0.62099093",
"0.61947215",
"0.6159893",
"0.6152461",
"0.6120678",
"0.6107185",
"0.5956836",
"0.58519316",
"0.58213335",
"0.5794799",
"0.5746909",
"0.5732208",
"0.56775117",
"0.56739074",
"0.5650088",
"0.5588641",
"0.5560465",
"0.55446446",
"0.55355006",
"0.5527846",
"0.5491256",
"0.54819596",
"0.5474531",
"0.54658335",
"0.5447345",
"0.5440106",
"0.54351693"
] | 0.73627174 | 0 |
Perform a bitwise add op with a bit size too large for the bitmap being modified. | def test_bit_add_bit_size_out_of_range(self):
ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_add_bit_size_signed(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 254, True, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([253] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def _add(self, i, k):\n while i < self._size:\n self._bit[i] += k\n i += lsb(i)",
"def test_bit_add_overflow_wrap(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def add64(a,b):\n return(np.add(a, b, dtype=np.uint64))",
"def test_bit_add_inbetween_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_add_overflow_fail(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def BitAdd(a, b, bits_to_compute=None):\r\n k = len(a)\r\n if not bits_to_compute:\r\n bits_to_compute = list(range(k))\r\n d = [None] * k\r\n for i in range(1,k):\r\n t = a[i]*b[i]\r\n d[i] = (a[i] + b[i] - 2*t, t)\r\n d[0] = (None, a[0]*b[0])\r\n pg = PreOpL(carry, d)\r\n c = [pair[1] for pair in pg]\r\n \r\n s = [None] * (k+1)\r\n if 0 in bits_to_compute:\r\n s[0] = a[0] + b[0] - 2*c[0]\r\n bits_to_compute.remove(0)\r\n for i in bits_to_compute:\r\n s[i] = a[i] + b[i] + c[i-1] - 2*c[i]\r\n s[k] = c[k-1]\r\n return s",
"def _uint8_add(self, a, b):\n return ((a & 0xFF) + (b & 0xFF)) & 0xFF",
"def _add(a, b):\n\n # Todo: What if numbers have bigger length than 8\n a = _I2B(a, fixed_length=8)\n b = _I2B(b, fixed_length=8)\n return _B2I([i ^ j for i, j in zip(a, b)])",
"def test_bit_add_simple(self):\n ops = [bitwise_operations.bit_add(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([2] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_add_multiple_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 2 + [0] * 2)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_add_overflow_saturate(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_SATURATE, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_insert_value_byte_size_too_large(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 6, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 6 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def __add__(self, other: 'SInt') -> 'SInt':\r\n # Recoding the addition\r\n if type(other) != self.__class__ or len(self) != len(other):\r\n raise TypeError(\"Wrong type or length for other\")\r\n retenue = [0 for i in range(len(self) + 1)]\r\n new_bin = ''\r\n for i in range(len(self)):\r\n k = int(self.binaire[-(i + 1)]) + int(other.binaire[-(i + 1)]) + retenue[i]\r\n new_bin = ['0', '1', '0', '1'][k] + new_bin\r\n retenue[i + 1] = 1 if k > 1 else 0\r\n if self.signe == other.signe and retenue[-1] != retenue[-2]:\r\n raise OverflowError(\"The sum is over the bytes available\")\r\n H = self.__class__(self.nbBytes)\r\n H.binaire = new_bin\r\n return H",
"def add_binary(a, b):\n return bin(a + b)[2:]",
"def test_bit_add_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __add__(self, other):\n\n return self._binary_elementwise_op(other, np.add)",
"def __add__(self, tc): \n tc = TwosComplement(tc)\n bits = self.len if self.len > tc.len else tc.len \n result = self.int + tc.int\n return TwosComplement(result, bits)",
"def add_to_reg(self):\n register = (self.opcode & 0xF00) >> 8\n value = self.opcode & 0xFF\n sum = self.registers[register] + value\n if sum > 0xFF:\n sum = bit_utils.wrap_around(sum, 0xFF + 1)\n self.registers[register] = sum\n logger.info(\"Added {} to register V{}\".format(value, register))",
"def BitAdd(m, n, length):\n\n lmax = max(len(m), len(n))\n c = 0\n ml = [0] * (lmax - len(m)) + [int(x) for x in list(m)]\n nl = [0] * (lmax - len(n)) + [int(x) for x in list(n)]\n rl = []\n for i in range(1, lmax+1):\n if ml[-i] + nl[-i] + c == 0:\n rl.insert(0, 0)\n c = 0\n elif ml[-i] + nl[-i] + c == 1:\n rl.insert(0, 1)\n c = 0\n elif ml[-i] + nl[-i] + c == 2:\n rl.insert(0, 0)\n c = 1\n elif ml[-i] + nl[-i] + c == 3:\n rl.insert(0, 1)\n c = 1\n if c == 1:\n rl.insert(0, 1)\n if length > len(rl):\n rl = [0] * (length - len(rl)) + rl\n else:\n rl = rl[-length:]\n rl = \"\".join([str(x) for x in rl])\n return rl",
"def add():\n osname = None\n is_64bit = sys.maxsize > 2**32\n bitsize_dict = {True: 64, False: 32}\n bitsize = bitsize_dict[is_64bit]\n if platform in LINUX_PLATFORMS:\n printos('Linux', bitsize)\n ubuntu_add()\n elif platform == \"darwin\":\n printos('Mac OS X', bitsize)\n mac_add()\n elif platform in WINDOWS_PLATFORMS:\n printos('Windows', bitsize)\n windows_add(bitsize)\n print('Done!')",
"def add(self, addr):\n\n val = self.mem.read(addr)\n result = self.alu.add(self.reg.accum, val)\n self.reg.accum = result",
"def add(self, x):\n for i in range(self.k):\n self.bits[mmh3.hash(x,i) % self.m] = True",
"def test_bit_set_bit_bit_size_too_large(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 16, 1, value, None)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_value_byte_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __iadd__(self, m):\n if self.__mm_type(m):\n ls=len(self)\n for i in self.desc():\n for j in range(ls):\n self.g_val(self.val(i,j)+m.val(i,j),i,j)\n return self",
"def test_bit_insert_value_byte_size_smaller_than_value(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 2, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 2 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def add(num1,num2):\n if(num2==0):\n return num1\n return add((num1^num2),(num1&num2)<<1)",
"def instruction_add(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n result = ((a + b) % MAX_INT)\n\n self.set_register(register, ((a + b) % MAX_INT))",
"def addx(self, addr):\n\n val = self.mem_if.read(addr, index=self.reg.idx)\n result = self.alu.add(self.reg.accum, val)\n self.reg.accum = result"
] | [
"0.6542242",
"0.64941835",
"0.62195337",
"0.61419046",
"0.61222196",
"0.6112536",
"0.6070879",
"0.6046138",
"0.59929603",
"0.5990503",
"0.597197",
"0.59605044",
"0.590751",
"0.5876018",
"0.5792255",
"0.57701886",
"0.5666809",
"0.56660813",
"0.56307065",
"0.5619407",
"0.56145215",
"0.5597236",
"0.55944216",
"0.55813456",
"0.5522608",
"0.5517107",
"0.5510879",
"0.5506172",
"0.54908",
"0.5468147"
] | 0.66088796 | 0 |
Perform a bitwise add op that overflows with the BIT_OVERFLOW_FAIL action. | def test_bit_add_overflow_fail(self):
ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_add_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_bit_size_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_overflow_wrap(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_add_overflow_saturate(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_SATURATE, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_add_bad_bin_name(self):\n ops = [bitwise_operations.bit_add(\"bad_name\", 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_overflow_fail(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_inbetween_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_add_multiple_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 2 + [0] * 2)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_add_bit_size_signed(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 254, True, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([253] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_add_simple(self):\n ops = [bitwise_operations.bit_add(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([2] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def ff_add(a, b):\n return a ^ b",
"def test_bit_insert_bad_arg_type(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 1.5, value, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_out_of_range(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_invalid_value(self):\n ops = [bitwise_operations.bit_and(\"bad_name\", 0, 8, 1, 1.5, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_sum_overflow():\r\n a = Tensor(dtype='int8', broadcastable=[False])()\r\n f = function([a], sum(a))\r\n assert f([1] * 300) == 300",
"def test_bit_lshift_bad_arg(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 1.5, 8, 1, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def do_add_reg(self, reg0, reg1):\n assert self.safe_register(reg0), f\"register error [{reg0}]\"\n assert self.safe_register(reg1), f\"register error [{reg1}]\"\n _sum = self.registers[reg0] + self.registers[reg1]\n if _sum <= 255:\n self.registers[reg0] = _sum\n else:\n self.registers[reg0] = 255",
"def test_bit_subtract_bit_offset_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def do_add_val(self, reg, val):\n assert self.safe_register(reg), f\"register error [{reg}]\"\n assert self.safe_value(val), f\"value error [{val}]\"\n _sum = self.registers[reg] + val\n if _sum <= 255:\n self.registers[reg] = _sum\n else:\n self.registers[reg] = 255",
"def test_add_all_args_less_zero(self):\n try:\n self.assertEqual(add(-7, -11), -18)\n except Exception as error:\n print(error)",
"def add(num1,num2):\n if(num2==0):\n return num1\n return add((num1^num2),(num1&num2)<<1)",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def instruction_add(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n result = ((a + b) % MAX_INT)\n\n self.set_register(register, ((a + b) % MAX_INT))",
"def test_bit_subtract_bit_size_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def _add(a, b):\n\n # Todo: What if numbers have bigger length than 8\n a = _I2B(a, fixed_length=8)\n b = _I2B(b, fixed_length=8)\n return _B2I([i ^ j for i, j in zip(a, b)])",
"def test_add_zero_arg(self):\n try:\n self.assertEqual(add(0, 15), 15)\n except Exception as error:\n print(error)",
"def test_add_all_args_greater_zero(self):\n try:\n self.assertEqual(add(17, 23), 40)\n except Exception as error:\n print(error)",
"def test_bit_rshift_bad_arg(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 1.5, 8, 1, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_value_byte_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_index_out_of_range(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 41, 8, 1, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)"
] | [
"0.7437843",
"0.7397968",
"0.6988565",
"0.6652772",
"0.65746254",
"0.65476197",
"0.63244146",
"0.63017803",
"0.62115306",
"0.6129045",
"0.6089315",
"0.60318506",
"0.6009601",
"0.5929405",
"0.5805147",
"0.578539",
"0.5765352",
"0.5743154",
"0.5705865",
"0.5704055",
"0.5703668",
"0.5680006",
"0.5663062",
"0.56587595",
"0.5643905",
"0.5586537",
"0.55558974",
"0.55541515",
"0.5514274",
"0.5513977"
] | 0.8252985 | 0 |
Perform a bitwise add op that overflows with the BIT_OVERFLOW_SATURATE action. | def test_bit_add_overflow_saturate(self):
ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_SATURATE, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([255] * 5)
assert bins[self.five_255_bin] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_add_overflow_fail(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_overflow_wrap(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_add_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_bit_size_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_bit_size_signed(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 254, True, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([253] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_add_inbetween_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_add_simple(self):\n ops = [bitwise_operations.bit_add(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([2] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_add_multiple_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 2 + [0] * 2)\n assert bins[self.test_bin_zeroes] == expected_result",
"def ff_add(a, b):\n return a ^ b",
"def __add__(self, tc): \n tc = TwosComplement(tc)\n bits = self.len if self.len > tc.len else tc.len \n result = self.int + tc.int\n return TwosComplement(result, bits)",
"def instruction_add(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n result = ((a + b) % MAX_INT)\n\n self.set_register(register, ((a + b) % MAX_INT))",
"def _add_op(value, sample_args, rationals_allowed):\n entropy, sample_args = sample_args.peel()\n if rationals_allowed and sample_args.count >= 3:\n x = number.integer_or_rational(entropy, True)\n else:\n x = number.integer(entropy, True)\n if random.choice([False, True]):\n op_args = [x, value - x]\n else:\n op_args = [value - x, x]\n return ops.Add, op_args, sample_args",
"def add(num1,num2):\n if(num2==0):\n return num1\n return add((num1^num2),(num1&num2)<<1)",
"def _uint8_add(self, a, b):\n return ((a & 0xFF) + (b & 0xFF)) & 0xFF",
"def _add(a, b):\n\n # Todo: What if numbers have bigger length than 8\n a = _I2B(a, fixed_length=8)\n b = _I2B(b, fixed_length=8)\n return _B2I([i ^ j for i, j in zip(a, b)])",
"def add_to_reg(self):\n register = (self.opcode & 0xF00) >> 8\n value = self.opcode & 0xFF\n sum = self.registers[register] + value\n if sum > 0xFF:\n sum = bit_utils.wrap_around(sum, 0xFF + 1)\n self.registers[register] = sum\n logger.info(\"Added {} to register V{}\".format(value, register))",
"def do_add_reg(self, reg0, reg1):\n assert self.safe_register(reg0), f\"register error [{reg0}]\"\n assert self.safe_register(reg1), f\"register error [{reg1}]\"\n _sum = self.registers[reg0] + self.registers[reg1]\n if _sum <= 255:\n self.registers[reg0] = _sum\n else:\n self.registers[reg0] = 255",
"def __add__(self, other):\n\n return self._binary_elementwise_op(other, np.add)",
"def add64(a,b):\n return(np.add(a, b, dtype=np.uint64))",
"def test_bit_add_bad_bin_name(self):\n ops = [bitwise_operations.bit_add(\"bad_name\", 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def addx(self, addr):\n\n val = self.mem_if.read(addr, index=self.reg.idx)\n result = self.alu.add(self.reg.accum, val)\n self.reg.accum = result",
"def smart_add(*args):\n result = 0\n for item in args:\n result += item\n\n return result",
"def union_add(this, that):\n return this.add(that, fill_value=0)",
"def _add(self, i, k):\n while i < self._size:\n self._bit[i] += k\n i += lsb(i)",
"def do_add_val(self, reg, val):\n assert self.safe_register(reg), f\"register error [{reg}]\"\n assert self.safe_value(val), f\"value error [{val}]\"\n _sum = self.registers[reg] + val\n if _sum <= 255:\n self.registers[reg] = _sum\n else:\n self.registers[reg] = 255",
"def add_binary(a, b):\n return bin(a + b)[2:]",
"def test_sum_overflow():\r\n a = Tensor(dtype='int8', broadcastable=[False])()\r\n f = function([a], sum(a))\r\n assert f([1] * 300) == 300",
"def addInt(val):\n b = ByteArray(b\"\")\n\n # Fast path for small integers and OP_1NEGATE.\n if val == 0:\n b += opcode.OP_0\n return b\n if val == -1 or (val >= 1 and val <= 16):\n b += opcode.OP_1 - 1 + val\n return b\n return addData(scriptNumBytes(val))",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_out_of_range(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)"
] | [
"0.7303214",
"0.70369244",
"0.6906154",
"0.6778493",
"0.6674004",
"0.64422286",
"0.633672",
"0.6162586",
"0.6078986",
"0.5818981",
"0.5817478",
"0.57848686",
"0.5755819",
"0.57219166",
"0.57161057",
"0.5714408",
"0.5697552",
"0.5672356",
"0.5642903",
"0.5629903",
"0.56281734",
"0.56200427",
"0.55816895",
"0.556449",
"0.55527943",
"0.5541904",
"0.55407596",
"0.55265856",
"0.5476507",
"0.5453266"
] | 0.72117203 | 1 |
Perform a bitwise add op that overflows with the BIT_OVERFLOW_WRAP action. | def test_bit_add_overflow_wrap(self):
ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([0] * 1 + [255] * 4)
assert bins[self.five_255_bin] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_add_overflow_fail(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_bit_size_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_simple(self):\n ops = [bitwise_operations.bit_add(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([2] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_add_overflow_saturate(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_SATURATE, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_add_bit_size_signed(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 254, True, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([253] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_add_inbetween_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_add_multiple_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 2 + [0] * 2)\n assert bins[self.test_bin_zeroes] == expected_result",
"def _add(a, b):\n\n # Todo: What if numbers have bigger length than 8\n a = _I2B(a, fixed_length=8)\n b = _I2B(b, fixed_length=8)\n return _B2I([i ^ j for i, j in zip(a, b)])",
"def ff_add(a, b):\n return a ^ b",
"def __add__(self, tc): \n tc = TwosComplement(tc)\n bits = self.len if self.len > tc.len else tc.len \n result = self.int + tc.int\n return TwosComplement(result, bits)",
"def add_x(self, x, add):\n return (x + add) % self.x_len",
"def __add__(self, other):\n\n return self._binary_elementwise_op(other, np.add)",
"def add64(a,b):\n return(np.add(a, b, dtype=np.uint64))",
"def instruction_add(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n result = ((a + b) % MAX_INT)\n\n self.set_register(register, ((a + b) % MAX_INT))",
"def smart_add(*args):\n result = 0\n for item in args:\n result += item\n\n return result",
"def add_binary(a, b):\n return bin(a + b)[2:]",
"def __add__(self,that):\n return self.__opExpand2(that,np.add)",
"def _add(self, i, k):\n while i < self._size:\n self._bit[i] += k\n i += lsb(i)",
"def convert_elementwise_add(node, **kwargs):\n return create_basic_op_node('Add', node, kwargs)",
"def addInt(val):\n b = ByteArray(b\"\")\n\n # Fast path for small integers and OP_1NEGATE.\n if val == 0:\n b += opcode.OP_0\n return b\n if val == -1 or (val >= 1 and val <= 16):\n b += opcode.OP_1 - 1 + val\n return b\n return addData(scriptNumBytes(val))",
"def __iadd__(self, other: t.Any) -> te.Self:\n return self._op_inplace('__iadd__', other)",
"def add(num1,num2):\n if(num2==0):\n return num1\n return add((num1^num2),(num1&num2)<<1)",
"def add_to_reg(self):\n register = (self.opcode & 0xF00) >> 8\n value = self.opcode & 0xFF\n sum = self.registers[register] + value\n if sum > 0xFF:\n sum = bit_utils.wrap_around(sum, 0xFF + 1)\n self.registers[register] = sum\n logger.info(\"Added {} to register V{}\".format(value, register))",
"def plus(self, other):\n return self | other",
"def addOp(self, op):\n self.operations << op",
"def __radd__(self,that):\n return self.__opExpand2(that,np.add)",
"def _add_op(value, sample_args, rationals_allowed):\n entropy, sample_args = sample_args.peel()\n if rationals_allowed and sample_args.count >= 3:\n x = number.integer_or_rational(entropy, True)\n else:\n x = number.integer(entropy, True)\n if random.choice([False, True]):\n op_args = [x, value - x]\n else:\n op_args = [value - x, x]\n return ops.Add, op_args, sample_args",
"def _uint8_add(self, a, b):\n return ((a & 0xFF) + (b & 0xFF)) & 0xFF",
"def __iadd__(self,that):\n #return self.__opExpand1(that,np.add, out=self)\n return self.__opExpand2(that,np.add, out=self)"
] | [
"0.69865286",
"0.63499284",
"0.6259732",
"0.6231338",
"0.6189133",
"0.6175745",
"0.61683786",
"0.609293",
"0.6042137",
"0.6023715",
"0.5987507",
"0.5873115",
"0.58514667",
"0.58116734",
"0.57713294",
"0.574729",
"0.5737004",
"0.5733803",
"0.56554",
"0.5628457",
"0.5598145",
"0.55433005",
"0.5539731",
"0.55072385",
"0.5491677",
"0.5485189",
"0.548512",
"0.5477647",
"0.546125",
"0.546081"
] | 0.74974084 | 0 |
Perform a bitwise and op with value large enough to span multiple bytes. | def test_bit_and_multiple_bytes(self):
value = bytearray()
value.append(1)
value.append(1)
value.append(1)
ops = [bitwise_operations.bit_and(self.five_255_bin, 8, 17, 3, value, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([255] * 1 + [1] * 2 + [127] * 1 + [255] * 1)
assert bins[self.five_255_bin] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_and_across_bytes(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([254] * 1 + [1] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_and(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def instruction_and(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n self.set_register(register, (a & b) % MAX_INT)",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def bitwise_and(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] & self.registers[register[1]])\n logger.info(\"Bitwise AND on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def AND(self, value):\n self.reg.A = self.reg.A & value\n self.reg.Z = self.reg.A == 0\n self.reg.N = self.reg.A >> 7",
"def bitwise_and(lhs, rhs):\n return _make.bitwise_and(lhs, rhs)",
"def test_bit_and_offset_value_byte_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def bitwise_and(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_and_op, other)",
"def bitwise_and(b1,b2):\n \n if b1 == \"\" and b2 == \"\":\n \n return \"\"\n \n elif b1 == \"\":\n \n return \"0\"*len(b2)\n \n elif b2 == \"\":\n \n return \"0\"*len(b1)\n \n \n else: \n \n rest = bitwise_and(b1[:-1],b2[:-1])\n \n if len(b1) == len(b2):\n \n if b1[-1] == \"0\" and b2[-1] == \"0\":\n \n return rest + \"0\"\n \n elif b1[-1] == \"1\" and b2[-1] == \"1\":\n \n return rest + \"1\"\n \n else: \n \n return rest + \"0\"\n \n elif len(b1) > len(b2):\n \n b2_with_zeroes = \"0\"*(len(b1) - len(b2)) + b2\n \n return bitwise_and(b1,b2_with_zeroes) \n \n \n elif len(b2) > len(b1):\n \n b1_with_zeroes = \"0\"*(len(b2) - len(b1)) + b1\n \n return bitwise_and(b1_with_zeroes,b2)",
"def logical_and(self, source, destination):\n value = bytearray()\n\n value.append(0x85) # TEST r/m32, r32\n rm = get_register_encoding(destination)\n reg = get_register_encoding(source)\n # ModR_byte encoded operands ( ModR/M Byte) MOD 11, RM source and\n # REG destination\n\n mod = 0b11\n modr_byte = (mod << 6) + (reg << 3) + (rm << 0)\n value.append(modr_byte)\n\n # clean the destination register, and only if the zero flag is set\n # set the bits in the destination register\n value += self.copy_value_to_reg(0, destination)\n # the zero flag will be set if the and was zero\n value += self.setnz(destination)\n value += self.movzx(destination, destination)\n\n return value",
"def test_bit_and_offset_out_of_range(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __and__(self, other):\n a, b = Trits.match_length(self, other)\n return Trits([x & y for x, y in zip(a, b)])",
"def __and__(self, other):\n\t\tif isinstance(other, int):\n\t\t\treturn self.value & other\n\t\telif type(self) is type(other):\n\t\t\treturn self.value & other.value",
"def convert_broadcast_logical_and(node, **kwargs):\n return create_basic_op_node('And', node, kwargs)",
"def bitwise_and(self, source, destination):\n value = bytearray()\n\n value.append(0x21) # AND r/m32, r32\n rm = get_register_encoding(destination)\n reg = get_register_encoding(source)\n # ModR_byte encoded operands ( ModR/M Byte) MOD 11, RM source and\n # REG destination\n\n mod = 0b11\n modr_byte = (mod << 6) + (reg << 3) + (rm << 0)\n value.append(modr_byte)\n\n return value",
"def _and(it):\n return 1 if it[0]==1 and it[1]==1 else 0",
"def andbits(num1,num2):\n thingstoadd=[]\n for i in range(31):\n bit1=setbit(num1,i)\n bit2=setbit(num2,i)\n bit1=shiftleft(bit1,30 - i)\n bit2=shiftleft(bit2,30 - i)\n bitsum=add(bit1,bit2)\n bitsum=setbit(bitsum,31)\n bitsum=shiftright(bitsum,31 - i)\n thingstoadd.append(bitsum)\n bit1=setbit(num1,31)\n bit2=setbit(num2,31)\n bit1=shiftright(bit1,1)\n bit2=shiftright(bit2,1)\n bitsum=add(bit1,bit2)\n bitsum=setbit(bitsum,31)\n thingstoadd.append(bitsum)\n return sum(thingstoadd)",
"def __and__(self, other):\n return self.fam.c_binop('and', self, other)",
"def ComputeANDMask( self, imgdata, width, height ):\n \n andbytes = []\n for y in range(height):\n bitcounter, currentbyte = (0 for _ in range(2))\n for x in range(width):\n alpha = imgdata[(y * width + x) * 4 + 3]\n currentbyte <<= 1\n if alpha == 0:\n currentbyte |= 1\n bitcounter += 1\n if bitcounter == 8:\n andbytes.append(currentbyte)\n bitcounter, currentbyte = (0 for _ in range(2))\n ## Pad current byte at the end of row.\n if bitcounter > 0:\n currentbyte <<= (8 - bitcounter)\n andbytes.append(currentbyte)\n ## Keep padding until multiple 4 bytes.\n while len(andbytes) % 4 != 0:\n andbytes.append(0)\n \n andbytes = b\"\".join(pack('B', andbyte) for andbyte in andbytes)\n return andbytes",
"def _andReg(address, mask):\n _setReg(address, _getReg(address)&mask)",
"def visit_and(self, left_result: T, right_result: T) -> T:",
"def and_(a, b):",
"def join_bits(byteseq) -> int:\n return reduce(lambda acc, bit: (acc << 1) | int(bit), byteseq)",
"def test_bit_get_multiple_bytes(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 17)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 2 + [128] * 1)\n assert result[\"255\"] == expected_result",
"def test_bit_lscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 7, 8, value)]\n\n expected_value = 1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.test_bin_ones] == expected_value",
"def test_bit_get_accross_bytes(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([16] * 1)\n assert result[\"bitwise1\"] == expected_result",
"def test_bit_or_multiple_bytes(self):\n value = bytearray([8] * 5)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 40, 5, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([9] * 5)\n assert bins[self.test_bin_ones] == expected_result",
"def AND(f, g):\n def _and(x):\n return f(x) & g(x)\n return _and",
"def test_bit_add_multiple_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 2 + [0] * 2)\n assert bins[self.test_bin_zeroes] == expected_result"
] | [
"0.7053533",
"0.68397754",
"0.6709027",
"0.66512394",
"0.6600164",
"0.6542796",
"0.6499277",
"0.62920785",
"0.6157668",
"0.6039458",
"0.60247964",
"0.59498256",
"0.59160185",
"0.5909005",
"0.58582497",
"0.5846487",
"0.5832019",
"0.5819976",
"0.5740326",
"0.57323074",
"0.56576574",
"0.5656976",
"0.56487715",
"0.5634668",
"0.5616851",
"0.56095994",
"0.5603196",
"0.55532354",
"0.5548726",
"0.55355114"
] | 0.7077078 | 0 |
Perform a bitwise and op with a bit_size > the size of value. | def test_bit_and_offset_bit_size_larger_than_val(self):
value = bytearray()
value.append(0)
ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]
with pytest.raises(e.InvalidRequest):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_and_offset_value_byte_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def AND(self, value):\n self.reg.A = self.reg.A & value\n self.reg.Z = self.reg.A == 0\n self.reg.N = self.reg.A >> 7",
"def test_bit_and(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_and_across_bytes(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([254] * 1 + [1] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result",
"def bitwise_and(lhs, rhs):\n return _make.bitwise_and(lhs, rhs)",
"def test_bit_or_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def bitwise_and(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] & self.registers[register[1]])\n logger.info(\"Bitwise AND on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def __and__(self, other):\n a, b = Trits.match_length(self, other)\n return Trits([x & y for x, y in zip(a, b)])",
"def test_bit_and_multiple_bytes(self):\n value = bytearray()\n value.append(1)\n value.append(1)\n value.append(1)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 8, 17, 3, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 1 + [1] * 2 + [127] * 1 + [255] * 1)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_xor_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def __and__(self, other):\n\t\tif isinstance(other, int):\n\t\t\treturn self.value & other\n\t\telif type(self) is type(other):\n\t\t\treturn self.value & other.value",
"def test_bit_and_offset_out_of_range(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def instruction_and(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n self.set_register(register, (a & b) % MAX_INT)",
"def bit_in_place(x, n):\n return (x & 2**n)",
"def bitwise_and(b1,b2):\n \n if b1 == \"\" and b2 == \"\":\n \n return \"\"\n \n elif b1 == \"\":\n \n return \"0\"*len(b2)\n \n elif b2 == \"\":\n \n return \"0\"*len(b1)\n \n \n else: \n \n rest = bitwise_and(b1[:-1],b2[:-1])\n \n if len(b1) == len(b2):\n \n if b1[-1] == \"0\" and b2[-1] == \"0\":\n \n return rest + \"0\"\n \n elif b1[-1] == \"1\" and b2[-1] == \"1\":\n \n return rest + \"1\"\n \n else: \n \n return rest + \"0\"\n \n elif len(b1) > len(b2):\n \n b2_with_zeroes = \"0\"*(len(b1) - len(b2)) + b2\n \n return bitwise_and(b1,b2_with_zeroes) \n \n \n elif len(b2) > len(b1):\n \n b1_with_zeroes = \"0\"*(len(b2) - len(b1)) + b1\n \n return bitwise_and(b1_with_zeroes,b2)",
"def test_bit_set_bit_bit_size_too_large(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 16, 1, value, None)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_value_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 48, 6, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def bitwise_and(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_and_op, other)",
"def __and__(self, other):\n return BitBoard(self.num & other.num)",
"def test_bit_or_bit_size_too_large(self):\n value = bytearray([8] * 6)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 41, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __and__(self, other):\n return self.fam.c_binop('and', self, other)",
"def _store_bitfield(self, value, access):\n ir_typ = self._get_bitfield_ir_typ(access, False)\n full_bitsize = ir_typ.bits\n assert access.bitshift + access.bitsize <= full_bitsize\n mask = ((1 << access.bitsize) - 1) << access.bitshift\n full_mask = (1 << full_bitsize) - 1\n inv_mask = full_mask ^ mask\n\n assert value.ty.is_integer\n\n # Optionally cast value:\n if value.ty is not ir_typ:\n value = self.builder.emit_cast(value, ir_typ)\n\n # Load memory value:\n # TODO: volatile used to enforce struct in memory.\n # Should not be required?\n loaded = self.builder.emit_load(access.address, ir_typ, volatile=True)\n\n # Shift value:\n if access.bitshift:\n value = self.builder.emit_binop(\n value, \"<<\", access.bitshift, ir_typ\n )\n\n # Clip value:\n value = self.builder.emit_binop(value, \"&\", mask, ir_typ)\n\n # Clear bits for bitfield:\n loaded = self.builder.emit_binop(loaded, \"&\", inv_mask, ir_typ)\n\n # Or with value\n value = self.builder.emit_binop(loaded, \"|\", value, ir_typ)\n\n # Store modified value back:\n self.emit(ir.Store(value, access.address))",
"def __and__(self, other):\n return MyCustomNumber(self.value & other.value)",
"def smask(value, fields, width):\n try:\n value = reduce(__or__, [1 << i for i in value], 0)\n except TypeError:\n pass \n try:\n fields = reduce(__or__, [1 << i for i in fields], 0)\n except TypeError:\n pass\n assert width > 0 \n value &= (1 << width) - 1\n result = sum(value << (width * i)\n for i in range(INT_BITS//width) if (fields >> i) & 1)\n return result & ((1 << INT_BITS) - 1)",
"def test_bit_insert_value_byte_size_smaller_than_value(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 2, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 2 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def get_bits(x, k, size, offset=0):\n\n answer = x >> offset\n answer >>= k * size\n return get_least_significant_bits(answer, size)",
"def convert_broadcast_logical_and(node, **kwargs):\n return create_basic_op_node('And', node, kwargs)",
"def BIT(self, value):\n result = self.reg.A & value\n self.reg.N = result >> 7\n self.reg.V = result >> 6 & 1\n self.reg.Z = result == 0",
"def test_bit_xor_bit_size_too_large(self):\n value = bytearray([8] * 6)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 41, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __and__(self, other):\n return self._operation_and(other)"
] | [
"0.66505015",
"0.6267172",
"0.6213419",
"0.61219025",
"0.6011456",
"0.5915263",
"0.58221704",
"0.5815698",
"0.579385",
"0.5749901",
"0.57298887",
"0.5679415",
"0.5606196",
"0.5568124",
"0.5551867",
"0.5548409",
"0.5525523",
"0.5524242",
"0.5467059",
"0.5379395",
"0.53744006",
"0.5353369",
"0.5333119",
"0.5303485",
"0.52984345",
"0.5279206",
"0.52766204",
"0.5175728",
"0.51575446",
"0.51478475"
] | 0.7103795 | 0 |
Perform a bitwise and op with a value_byte_size larger than the bitmap being modified. | def test_bit_and_offset_value_byte_size_too_large(self):
value = bytearray()
for x in range(0, 5):
value.append(0)
ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_across_bytes(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([254] * 1 + [1] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_and(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_and_multiple_bytes(self):\n value = bytearray()\n value.append(1)\n value.append(1)\n value.append(1)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 8, 17, 3, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 1 + [1] * 2 + [127] * 1 + [255] * 1)\n assert bins[self.five_255_bin] == expected_result",
"def AND(self, value):\n self.reg.A = self.reg.A & value\n self.reg.Z = self.reg.A == 0\n self.reg.N = self.reg.A >> 7",
"def RebuildANDMask( self, data, rebuild = False ):\n global biBitCount\n \n ## Get BITMAPINFO header data.\n (biSize, biWidth, biHeight, biPlanes, biBitCount,\n biCompression, biSizeImage, biXPelsPerMeter, biYPelsPerMeter, biClrUsed, biClrImportant) = unpack_from('<3L2H6L', data[0:40])\n\n if biBitCount != 32:\n ## No alpha channel, so the mask cannot be wrong.\n return (data if rebuild else True)\n \n biHeight = int(biHeight / 2.)\n xorsize = WRITER().CalcRowSize( biBitCount, biWidth ) * biHeight\n ## Checks if is used a palette.\n xorpalettesize = (biClrUsed or (1 << biBitCount if biBitCount < 24 else 0)) * 4\n xordata = data[40 + xorpalettesize : 40 + xorpalettesize + xorsize]\n\n if rebuild:\n anddata = self.ComputeANDMask( xordata, biWidth, biHeight )\n ## Replace the AND mask.\n fixed = data[0 : 40 + xorpalettesize + xorsize] + anddata\n return fixed\n else:\n anddata = data[40 + xorpalettesize + xorsize : len(data)]\n return self.CheckANDMask( xordata, anddata, biWidth, biHeight )",
"def bitwise_and(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] & self.registers[register[1]])\n logger.info(\"Bitwise AND on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def test_bit_insert_value_byte_size_smaller_than_value(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 2, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 2 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def instruction_and(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n self.set_register(register, (a & b) % MAX_INT)",
"def _store_bitfield(self, value, access):\n ir_typ = self._get_bitfield_ir_typ(access, False)\n full_bitsize = ir_typ.bits\n assert access.bitshift + access.bitsize <= full_bitsize\n mask = ((1 << access.bitsize) - 1) << access.bitshift\n full_mask = (1 << full_bitsize) - 1\n inv_mask = full_mask ^ mask\n\n assert value.ty.is_integer\n\n # Optionally cast value:\n if value.ty is not ir_typ:\n value = self.builder.emit_cast(value, ir_typ)\n\n # Load memory value:\n # TODO: volatile used to enforce struct in memory.\n # Should not be required?\n loaded = self.builder.emit_load(access.address, ir_typ, volatile=True)\n\n # Shift value:\n if access.bitshift:\n value = self.builder.emit_binop(\n value, \"<<\", access.bitshift, ir_typ\n )\n\n # Clip value:\n value = self.builder.emit_binop(value, \"&\", mask, ir_typ)\n\n # Clear bits for bitfield:\n loaded = self.builder.emit_binop(loaded, \"&\", inv_mask, ir_typ)\n\n # Or with value\n value = self.builder.emit_binop(loaded, \"|\", value, ir_typ)\n\n # Store modified value back:\n self.emit(ir.Store(value, access.address))",
"def test_bit_or_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def bitwise_and(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_and_op, other)",
"def test_bit_insert_value_byte_size_too_large(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 6, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 6 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def bitwise_and(lhs, rhs):\n return _make.bitwise_and(lhs, rhs)",
"def test_bit_and_offset_out_of_range(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_bit_size_too_large(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 16, 1, value, None)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_accross_bytes(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([16] * 1)\n assert result[\"bitwise1\"] == expected_result",
"def logical_and(self, source, destination):\n value = bytearray()\n\n value.append(0x85) # TEST r/m32, r32\n rm = get_register_encoding(destination)\n reg = get_register_encoding(source)\n # ModR_byte encoded operands ( ModR/M Byte) MOD 11, RM source and\n # REG destination\n\n mod = 0b11\n modr_byte = (mod << 6) + (reg << 3) + (rm << 0)\n value.append(modr_byte)\n\n # clean the destination register, and only if the zero flag is set\n # set the bits in the destination register\n value += self.copy_value_to_reg(0, destination)\n # the zero flag will be set if the and was zero\n value += self.setnz(destination)\n value += self.movzx(destination, destination)\n\n return value",
"def test_bit_set_bit_value_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 48, 6, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_inbetween_bytes(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 4, 8, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def __and__(self, other):\n return BitBoard(self.num & other.num)",
"def _andReg(address, mask):\n _setReg(address, _getReg(address)&mask)",
"def boolean(operation, bitmaps):\n\n maxX, maxY = size = bitmaps[0].size()\n result = bitmap(size)\n for x in range(maxX):\n for y in range(maxY):\n pixel = bitmaps[0].get(x,y)\n for b in bitmaps[1:]:\n pixel = apply(operation, (pixel, b.get(x,y)))\n result.set(x,y,pixel)\n return result",
"def test_bit_xor_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def BIT(self, value):\n result = self.reg.A & value\n self.reg.N = result >> 7\n self.reg.V = result >> 6 & 1\n self.reg.Z = result == 0",
"def __and__(self, other):\n\t\tif isinstance(other, int):\n\t\t\treturn self.value & other\n\t\telif type(self) is type(other):\n\t\t\treturn self.value & other.value",
"def test_bit_get_multiple_bytes(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 17)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 2 + [128] * 1)\n assert result[\"255\"] == expected_result",
"def ComputeANDMask( self, imgdata, width, height ):\n \n andbytes = []\n for y in range(height):\n bitcounter, currentbyte = (0 for _ in range(2))\n for x in range(width):\n alpha = imgdata[(y * width + x) * 4 + 3]\n currentbyte <<= 1\n if alpha == 0:\n currentbyte |= 1\n bitcounter += 1\n if bitcounter == 8:\n andbytes.append(currentbyte)\n bitcounter, currentbyte = (0 for _ in range(2))\n ## Pad current byte at the end of row.\n if bitcounter > 0:\n currentbyte <<= (8 - bitcounter)\n andbytes.append(currentbyte)\n ## Keep padding until multiple 4 bytes.\n while len(andbytes) % 4 != 0:\n andbytes.append(0)\n \n andbytes = b\"\".join(pack('B', andbyte) for andbyte in andbytes)\n return andbytes",
"def test_bit_add_overflow_wrap(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_or_multiple_bytes_value_unchanged(self):\n value = bytearray([255])\n ops = [bitwise_operations.bit_or(self.five_255_bin, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result"
] | [
"0.68500006",
"0.6666652",
"0.64749104",
"0.6296524",
"0.6243885",
"0.58637655",
"0.58447677",
"0.5794284",
"0.5770545",
"0.5637839",
"0.56156445",
"0.5608388",
"0.5604958",
"0.5556106",
"0.5555062",
"0.55270344",
"0.5524201",
"0.551075",
"0.55024546",
"0.5488388",
"0.5476835",
"0.5448277",
"0.54328525",
"0.5430031",
"0.54271704",
"0.53874743",
"0.53690505",
"0.53578395",
"0.5308358",
"0.52923214"
] | 0.6712595 | 1 |
Perform a bitwise and op with a non existent bin name. | def test_bit_and_invalid_bin_name(self):
value = bytearray()
value.append(0)
ops = [bitwise_operations.bit_and("bad_name", 0, 8, 1, value, None)]
with pytest.raises(e.BinNotFound):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_and(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_or_bad_bin_name(self):\n value = bytearray([8])\n ops = [bitwise_operations.bit_or(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_across_bytes(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([254] * 1 + [1] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result",
"def convert_broadcast_logical_and(node, **kwargs):\n return create_basic_op_node('And', node, kwargs)",
"def bitwise_and(b1,b2):\n \n if b1 == \"\" and b2 == \"\":\n \n return \"\"\n \n elif b1 == \"\":\n \n return \"0\"*len(b2)\n \n elif b2 == \"\":\n \n return \"0\"*len(b1)\n \n \n else: \n \n rest = bitwise_and(b1[:-1],b2[:-1])\n \n if len(b1) == len(b2):\n \n if b1[-1] == \"0\" and b2[-1] == \"0\":\n \n return rest + \"0\"\n \n elif b1[-1] == \"1\" and b2[-1] == \"1\":\n \n return rest + \"1\"\n \n else: \n \n return rest + \"0\"\n \n elif len(b1) > len(b2):\n \n b2_with_zeroes = \"0\"*(len(b1) - len(b2)) + b2\n \n return bitwise_and(b1,b2_with_zeroes) \n \n \n elif len(b2) > len(b1):\n \n b1_with_zeroes = \"0\"*(len(b2) - len(b1)) + b1\n \n return bitwise_and(b1_with_zeroes,b2)",
"def test_bit_and_invalid_value(self):\n ops = [bitwise_operations.bit_and(\"bad_name\", 0, 8, 1, 1.5, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_bad_bin_name(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(\"bad_name\", 0, 8, 1, value, None)]\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor_bad_bin_name(self):\n value = bytearray([8])\n ops = [bitwise_operations.bit_xor(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def _andReg(address, mask):\n _setReg(address, _getReg(address)&mask)",
"def test_bit_add_bad_bin_name(self):\n ops = [bitwise_operations.bit_add(\"bad_name\", 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_insert_nonexistent_bin_name(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(\"bad_name\", 0, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3])\n assert bins[\"bad_name\"] == expected_result",
"def bitwise_and(lhs, rhs):\n return _make.bitwise_and(lhs, rhs)",
"def bitwise_and(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_and_op, other)",
"def test_bit_not_bad_bin_name(self):\n ops = [bitwise_operations.bit_not(\"bad_name\", 0, 8, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def bitwise_and(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] & self.registers[register[1]])\n logger.info(\"Bitwise AND on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def binary_and(binary1, binary2):\n if binary1.shape == binary2.shape:\n binary = np.where(np.logical_and(binary1,binary2)==True, 1., 0.)\n return binary\n else:\n return None",
"def __and__(self, other):\n return self.fam.c_binop('and', self, other)",
"def instruction_and(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n self.set_register(register, (a & b) % MAX_INT)",
"def test_bit_remove_bad_bin_name(self):\n ops = [bitwise_operations.bit_remove(\"bad_name\", 3, 3, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def and_(a, b):",
"def bit_manipulation(self, a: str, b: str) -> str:\n x, y = int(a, 2), int(b, 2)\n while y:\n answer = x ^ y\n carry = (x & y) << 1\n x, y = answer, carry\n return bin(x)[2:]",
"def test_bit_lshift_bad_bin_name(self):\n ops = [bitwise_operations.bit_lshift(\"bad_name\", 0, 8, 1, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_bad_bin_name(self):\n ops = [bitwise_operations.bit_subtract(\"bad_name\", 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def Nand(*args):\n return Not(And(*args))",
"def is_bitop(*args):\n return _ida_hexrays.is_bitop(*args)",
"def test_bit_get_bad_bin_name(self):\n ops = [bitwise_operations.bit_get(\"bad_name\", 0, 1)]\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = None\n assert result[\"bad_name\"] == expected_result",
"def __and__(self, other):\n return BitBoard(self.num & other.num)",
"def test_bit_and_multiple_bytes(self):\n value = bytearray()\n value.append(1)\n value.append(1)\n value.append(1)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 8, 17, 3, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 1 + [1] * 2 + [127] * 1 + [255] * 1)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_and_offset_out_of_range(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rshift_bad_bin_name(self):\n ops = [bitwise_operations.bit_rshift(\"bad_name\", 0, 8, 1, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)"
] | [
"0.6510834",
"0.6441707",
"0.6261121",
"0.62495655",
"0.62354034",
"0.6178037",
"0.6170451",
"0.6150072",
"0.61430025",
"0.61324114",
"0.60920554",
"0.6063773",
"0.6020918",
"0.5954678",
"0.58549696",
"0.5835591",
"0.58223265",
"0.57884556",
"0.57821554",
"0.570214",
"0.56394845",
"0.56265336",
"0.5605263",
"0.5591779",
"0.5583033",
"0.5551057",
"0.55198663",
"0.55055434",
"0.550135",
"0.55001324"
] | 0.762801 | 0 |
Perform a bitwise get op. | def test_bit_get(self):
ops = [bitwise_operations.bit_get(self.five_255_bin, 0, 8)]
_, _, result = self.as_connection.operate(self.test_key, ops)
expected_result = bytearray([255] * 1)
assert result["255"] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_get_accross_bytes(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([16] * 1)\n assert result[\"bitwise1\"] == expected_result",
"def bit_get(val, idx):\n return (val >> idx) & 1",
"def bitget(x, n):\n return (x >> n) & 1",
"def test_bit_get_int_accross_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 4, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 16\n assert result[\"bitwise1\"] == expected_result",
"def _get_bit(self, num, bit, mask=1):\n return (int(num) >> bit) & mask",
"def test_bit_get_int(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 255\n assert result[\"255\"] == expected_result",
"def getbit(self, key, offset):\n key = self._encode(key)\n index, bits, mask = self._get_bits_and_offset(key, offset)\n\n if index >= len(bits):\n return 0\n\n return 1 if (bits[index] & mask) else 0",
"def get_bit(x, k):\n\n return (x >> k) & 1",
"def test_bit_get_multiple_bytes(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 17)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 2 + [128] * 1)\n assert result[\"255\"] == expected_result",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def get(flag=\"rainbow\"):\n return flags[flag]",
"def get_bit(num, i):\r\n return 1 if num & 1 << i else 0",
"def get_bit(num, i):\n return num & (1 << i) != 0",
"def get(self, key):\n return self.execute_command(self.GET_CMD, key)",
"def _get_bit(byte, ii):\n return (byte >> (7 - ii)) & 1",
"def getBits(data, offset, bits=1):\n mask = ((1 << bits) - 1) << offset\n return (data & mask) >> offset",
"def get_bit(num, position):\n\treturn (num >> position) & 0b1",
"def get_bit(byte, bit_num):\n return (byte & (1 << bit_num)) >> bit_num",
"def get(self, r, g, b):\n\n return self.map[(r << 2 * self.bits) + (g << self.bits) + b]",
"def test_bit_get_int_multiple_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 17, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 131071\n assert result[\"255\"] == expected_result",
"def get_bit(reg,n_bit):\n return reg >> n_bit & 1",
"def test_bit_get_fraction_of_byte(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[\"255\"] == expected_result",
"def __getitem__(self, index):\n nth_int, nth_bit = divmod(index, BitArray._UNSIGNED_INT)\n return self.bits[nth_int] & (1 << nth_bit)",
"def access_bit(data, num):\n \n base = int(num // 8)\n shift = int(num % 8)\n return (data[base] & (1<<shift)) >> shift",
"def http_get(self, **kwargs):\n return self.rabjcallable.get(**kwargs)",
"def test_bit_get_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 41, 1)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def getBit(self,i):\n return self.boolVals[i]",
"def test_bit_get_bad_argument_type(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 0, 1.5)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def _get(self, *args, **kwargs):\n return self._request('get', *args, **kwargs)",
"def get_bits( self, count ):\n result = 0\n for i in range( count ):\n if self.bits_remaining <= 0:\n self._fill_buffer()\n if self.bits_reverse:\n bit = (1 if (self.current_bits & (0x80 << 8*(self.bytes_to_cache-1))) else 0)\n self.current_bits <<= 1\n self.current_bits &= 0xff\n else:\n bit = (self.current_bits & 1)\n self.current_bits >>= 1\n\n self.bits_remaining -= 1\n\n if self.output_reverse:\n result <<= 1\n result |= bit\n else:\n result |= bit << i\n return result"
] | [
"0.7000506",
"0.6605296",
"0.6504855",
"0.6378649",
"0.62414247",
"0.61625886",
"0.6146228",
"0.61241513",
"0.610408",
"0.6011124",
"0.5796253",
"0.57583314",
"0.57545096",
"0.56891155",
"0.5669531",
"0.56524837",
"0.5637581",
"0.56328243",
"0.5563451",
"0.55194074",
"0.5511881",
"0.55095464",
"0.54840136",
"0.5470733",
"0.54097366",
"0.5399487",
"0.5374499",
"0.5314628",
"0.5238435",
"0.5228506"
] | 0.6793469 | 1 |
Perform a bitwise get op with a negative offset. | def test_bit_get_negative_offset(self):
ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]
_, _, result = self.as_connection.operate(self.test_key, ops)
expected_result = bytearray([192] * 1)
assert result[self.count_bin] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_get_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 41, 1)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_bit_offset_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_int_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 41, 1, False)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def bit_get(val, idx):\n return (val >> idx) & 1",
"def getbit(self, key, offset):\n key = self._encode(key)\n index, bits, mask = self._get_bits_and_offset(key, offset)\n\n if index >= len(bits):\n return 0\n\n return 1 if (bits[index] & mask) else 0",
"def getBits(data, offset, bits=1):\n mask = ((1 << bits) - 1) << offset\n return (data & mask) >> offset",
"def test_bit_xor_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_not_offset_out_of_range(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 41, 8, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_offset_out_of_range(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def bitwise_not(data):\n return _make.bitwise_not(data)",
"def bitget(x, n):\n return (x >> n) & 1",
"def test_bit_subtract_bit_size_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __neg__(self):\n return self[::-1].complement",
"def test_bit_subtract_overflow_fail(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_accross_bytes(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([16] * 1)\n assert result[\"bitwise1\"] == expected_result",
"def negate_gate(wordlen, input='x', output='~x'):\n neg = bitwise_negate(wordlen, input, \"tmp\")\n inc = inc_gate(wordlen, \"tmp\", output)\n return neg >> inc",
"def test_bit_subtract_simple(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def shift_lowest_unset_bit_index(x, k):\n\n if (x == -1):\n return -1\n\n return (x << k) // get_lowest_unset_bit(x)",
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def bitmask(n: int) -> int:\n if n >= 0:\n return (1 << n) - 1\n else:\n return -1 << -n",
"def test_bit_lshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_or_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __getitem__(self, n):\n return (self.num >> np.uint64(n)) & UINT64_ONE",
"def _get_bit(byte, ii):\n return (byte >> (7 - ii)) & 1",
"def __neg__(self) -> 'SInt':\r\n return self.complement()",
"def test_bit_and_offset_out_of_range(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __rshift__(self, other):\r\n # TODO: extend to secret offset\r\n if not isinstance(other, int):\r\n return NotImplemented\r\n\r\n return self.__floordiv__(1<<other)",
"def test_bit_lscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)"
] | [
"0.6487363",
"0.63536626",
"0.6093398",
"0.60396236",
"0.5953041",
"0.58536357",
"0.5741644",
"0.56206924",
"0.55487245",
"0.54852706",
"0.54610914",
"0.5309807",
"0.5308505",
"0.5308271",
"0.52730584",
"0.5258959",
"0.5250486",
"0.5231087",
"0.5225644",
"0.5214675",
"0.5208595",
"0.5188689",
"0.51643676",
"0.5159055",
"0.51590383",
"0.51552135",
"0.5153424",
"0.51341265",
"0.51335806",
"0.51294565"
] | 0.7575732 | 0 |
Perform a bitwise get op across bytes. | def test_bit_get_accross_bytes(self):
ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]
_, _, result = self.as_connection.operate(self.test_key, ops)
expected_result = bytearray([16] * 1)
assert result["bitwise1"] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_get_int_accross_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 4, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 16\n assert result[\"bitwise1\"] == expected_result",
"def test_bit_get_multiple_bytes(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 17)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 2 + [128] * 1)\n assert result[\"255\"] == expected_result",
"def test_bit_get(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 0, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 1)\n assert result[\"255\"] == expected_result",
"def test_bit_get_int_multiple_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 17, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 131071\n assert result[\"255\"] == expected_result",
"def test_bit_get_fraction_of_byte(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[\"255\"] == expected_result",
"def _get_bit(byte, ii):\n return (byte >> (7 - ii)) & 1",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def get_bits_and_shift(byte,bit1,bit0,shift):\n bit1 = ((byte & (1 << bit1)) >> bit1) << 1\n bit0 = ((byte & (1 << bit0)) >> bit0)\n return (bit1 | bit0) << shift",
"def getBits(data, offset, bits=1):\n mask = ((1 << bits) - 1) << offset\n return (data & mask) >> offset",
"def getbit(self, key, offset):\n key = self._encode(key)\n index, bits, mask = self._get_bits_and_offset(key, offset)\n\n if index >= len(bits):\n return 0\n\n return 1 if (bits[index] & mask) else 0",
"def get_bit(byte, bit_num):\n return (byte & (1 << bit_num)) >> bit_num",
"def bitget(x, n):\n return (x >> n) & 1",
"def bit_get(val, idx):\n return (val >> idx) & 1",
"def logic(key, byteArray, use_custom=False):\n key = [ord(c) for c in key]\n keystream = KeyStream(key, use_custom)\n\n result = []\n for c in byteArray:\n value = (c ^ next(keystream))\n result.append(value)\n return result",
"def test_bit_get_int(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 255\n assert result[\"255\"] == expected_result",
"def test_bit_lscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 7, 8, value)]\n\n expected_value = 1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.test_bin_ones] == expected_value",
"def access_bit(data, num):\n \n base = int(num // 8)\n shift = int(num % 8)\n return (data[base] & (1<<shift)) >> shift",
"def test_bit_get_int_fraction_of_byte(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 2, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 3\n assert result[\"255\"] == expected_result",
"def read_byte(self, opcode: int) -> int:\n\n # 0xff = 255\n\n return opcode & 0xFF",
"def test_bit_rscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.count_bin, 4, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_subtract_multiple_bytes(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [0] * 2 + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def queryBytes(self, command):\r\n try:\r\n command += '0a'\r\n req_url = self.url + 'bquery/' + command\r\n resp = requests.get(url=req_url)\r\n return resp.content\r\n except ValueError:\r\n print(\"uart failed queryBytes\")",
"def pick_byte2(input):\n val = int(input) >> 8\n val = val & 255\n return val",
"def get_bit(x, k):\n\n return (x >> k) & 1",
"def read_binary(self, offset, count):\n log.debug(\"read binary {0} to {1}\".format(offset, offset+count))\n cmd = bytearray([0x00, 0xB0, offset/256, offset%256, count])\n rsp = self.transceive(cmd)\n if rsp[-2:] != \"\\x90\\x00\":\n raise Type4TagError(rsp[-2:])\n return rsp[0:-2]",
"def read_bytes(self) -> bytes:\n t = self.pc\n while self.data[self.pc] != 0:\n self.pc += 1\n result = self.data[t:self.pc]\n self.pc += 1 # jump '\\0'\n return result",
"def _get_bit(self, num, bit, mask=1):\n return (int(num) >> bit) & mask",
"def getByte(self, int: int, int2: int) -> int:\n ...",
"def read(self, x, y):\n i = self.size * x + y\n return self._read_bit(i)",
"def GetBits(self, num_bits):\n old_idx_boff = self.idx_boff\n\n bits_available = self.NumBits() - (8*self.idx_byte + self.idx_boff)\n if num_bits > bits_available:\n print \"num_bits: %d but bits_available: %d\" % (num_bits, bits_available)\n raise StandardError()\n retval = []\n bits_left = num_bits\n if self.idx_boff == 0:\n while bits_left >= 8:\n retval.append(self.output[self.idx_byte])\n self.idx_byte += 1\n bits_left -= 8\n if bits_left:\n retval.append( ~(255 >> bits_left) & self.output[self.idx_byte])\n self.idx_boff += bits_left\n self.idx_boff %= 8\n bits_left = 0\n else:\n # We know there is a non-zero bit offset if we're below here.\n cur_byte = 0\n cur_boff = 0\n lob = len(self.output)\n while bits_left > 0:\n if bits_left >= 8 and lob > self.idx_byte:\n cur_byte = 255 & (self.output[self.idx_byte] << self.idx_boff)\n self.idx_byte += 1\n cur_byte |= (self.output[self.idx_byte] >> (8 - self.idx_boff))\n retval.append(cur_byte)\n cur_byte = 0\n bits_left -= 8\n else:\n bits_to_consume = min(min(8 - cur_boff, 8 - self.idx_boff),\n bits_left)\n\n c = self.output[self.idx_byte]\n c <<= self.idx_boff\n c &= 255\n cur_byte |= (c & ~(255 >> (bits_to_consume))) >> cur_boff\n bits_left -= bits_to_consume\n cur_boff += bits_to_consume\n self.idx_boff += bits_to_consume\n if cur_boff >= 8:\n retval.append(cur_byte)\n cur_byte = 0\n cur_boff -= 8\n if self.idx_boff >= 8:\n self.idx_byte += 1\n self.idx_boff -= 8\n if self.idx_boff >= 8:\n raise StandardError()\n if cur_boff:\n retval.append(cur_byte)\n if (old_idx_boff + num_bits) % 8 != self.idx_boff:\n print \"old_idx_boff(%d) + num_bits(%d) != self.idx_boff(%d) \" % (\n old_idx_boff, num_bits, self.idx_boff)\n print \"retval: \", (retval, num_bits)\n raise StandardError()\n return (retval, num_bits)"
] | [
"0.7051059",
"0.6728604",
"0.66430426",
"0.6132444",
"0.6119449",
"0.60101527",
"0.5942671",
"0.5909405",
"0.5893895",
"0.5889837",
"0.5881569",
"0.5854613",
"0.5784683",
"0.57692033",
"0.57260805",
"0.5660203",
"0.565209",
"0.56341773",
"0.5623387",
"0.56132615",
"0.5611499",
"0.5601272",
"0.5545043",
"0.5505461",
"0.5491999",
"0.54675996",
"0.5463505",
"0.5456916",
"0.5449897",
"0.53616583"
] | 0.75417405 | 0 |
Perform a bitwise get op across multiple bytes. | def test_bit_get_multiple_bytes(self):
ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 17)]
_, _, result = self.as_connection.operate(self.test_key, ops)
expected_result = bytearray([255] * 2 + [128] * 1)
assert result["255"] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_get_accross_bytes(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([16] * 1)\n assert result[\"bitwise1\"] == expected_result",
"def test_bit_get_int_accross_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 4, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 16\n assert result[\"bitwise1\"] == expected_result",
"def test_bit_get_int_multiple_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 17, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 131071\n assert result[\"255\"] == expected_result",
"def test_bit_get(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 0, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 1)\n assert result[\"255\"] == expected_result",
"def test_bit_subtract_multiple_bytes(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [0] * 2 + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_get_fraction_of_byte(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[\"255\"] == expected_result",
"def logic(key, byteArray, use_custom=False):\n key = [ord(c) for c in key]\n keystream = KeyStream(key, use_custom)\n\n result = []\n for c in byteArray:\n value = (c ^ next(keystream))\n result.append(value)\n return result",
"def get_bits_and_shift(byte,bit1,bit0,shift):\n bit1 = ((byte & (1 << bit1)) >> bit1) << 1\n bit0 = ((byte & (1 << bit0)) >> bit0)\n return (bit1 | bit0) << shift",
"def test_bit_xor_multiple_bytes(self):\n value = bytearray([8] * 5)\n ops = [bitwise_operations.bit_xor(self.five_255_bin, 0, 40, 5, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([247] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def getBits(data, offset, bits=1):\n mask = ((1 << bits) - 1) << offset\n return (data & mask) >> offset",
"def bitget(x, n):\n return (x >> n) & 1",
"def test_bit_and_multiple_bytes(self):\n value = bytearray()\n value.append(1)\n value.append(1)\n value.append(1)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 8, 17, 3, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 1 + [1] * 2 + [127] * 1 + [255] * 1)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_lscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 7, 8, value)]\n\n expected_value = 1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.test_bin_ones] == expected_value",
"def test_bit_or_multiple_bytes(self):\n value = bytearray([8] * 5)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 40, 5, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([9] * 5)\n assert bins[self.test_bin_ones] == expected_result",
"async def _multi_get(self, keys):\n values = []\n for value in await self.client.multi_get(*keys):\n if value is not None and self.encoding is not None:\n values.append(bytes.decode(value))\n else:\n values.append(value)\n return values",
"def bit_get(val, idx):\n return (val >> idx) & 1",
"def bits():\n for d in data:\n for i in [5, 4, 3, 2, 1, 0]:\n yield (d >> i) & 1",
"def get_bits( self, count ):\n result = 0\n for i in range( count ):\n if self.bits_remaining <= 0:\n self._fill_buffer()\n if self.bits_reverse:\n bit = (1 if (self.current_bits & (0x80 << 8*(self.bytes_to_cache-1))) else 0)\n self.current_bits <<= 1\n self.current_bits &= 0xff\n else:\n bit = (self.current_bits & 1)\n self.current_bits >>= 1\n\n self.bits_remaining -= 1\n\n if self.output_reverse:\n result <<= 1\n result |= bit\n else:\n result |= bit << i\n return result",
"def test_bit_set_bit_multiple_bytes(self):\n value = bytearray()\n value = bytearray()\n rand_byte = random.randint(0, 255)\n num_bytes = random.randint(1, 5)\n for x in range(0, num_bytes):\n value.append(rand_byte)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, (num_bytes * 8), num_bytes, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray(([rand_byte] * num_bytes) + [0] * (5 - num_bytes))\n assert bins[self.test_bin_zeroes] == expected_result",
"def _get_bit(byte, ii):\n return (byte >> (7 - ii)) & 1",
"def test_bit_get_int_fraction_of_byte(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 2, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 3\n assert result[\"255\"] == expected_result",
"def get_blobs(self): # CHECK\n x=self.send_packet_check_response_without_retry('\\x90')\n n=len(x)/4 # CHECK? n = len(x)//4\n z=struct.unpack('<'+'I'*n,x)\n unpack=lambda i: tuple(i>>offset & (1<<length)-1 for offset,length in [(0,11),(11,11),(22,2),(24,8)])\n return z[0],[unpack(i) for i in z[1:]]",
"def test_bit_get_int(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 255\n assert result[\"255\"] == expected_result",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def test_bit_and_across_bytes(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([254] * 1 + [1] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_xor_multiple_bytes_value_unchanged(self):\n value = bytearray([0])\n ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_rscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.count_bin, 4, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def GetAllBits(self):\n return (self.output, self.NumBits())",
"def get_bit(byte, bit_num):\n return (byte & (1 << bit_num)) >> bit_num",
"def combine_bytes(data):\n copy = data[:]\n copy.reverse()\n return sum(x << n*8 for n, x in enumerate(copy))"
] | [
"0.7147852",
"0.66116863",
"0.652621",
"0.6177915",
"0.5853398",
"0.57564133",
"0.5710771",
"0.56699646",
"0.5662459",
"0.56446254",
"0.55893993",
"0.55710304",
"0.55414647",
"0.55307996",
"0.55051976",
"0.5418046",
"0.5379218",
"0.5309492",
"0.5307577",
"0.5278677",
"0.52720827",
"0.5259857",
"0.5243869",
"0.52280486",
"0.51966745",
"0.519556",
"0.5194281",
"0.51927733",
"0.5185902",
"0.51551896"
] | 0.715834 | 0 |
Perform a bitwise get with a bit_size larger than the bitmap being read. | def test_bit_get_bit_size_too_large(self):
ops = [bitwise_operations.bit_get(self.test_bin_ones, 0, 41)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_get_int_bit_size_too_large(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 0, 41, False)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 0, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 1)\n assert result[\"255\"] == expected_result",
"def test_bit_get_accross_bytes(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([16] * 1)\n assert result[\"bitwise1\"] == expected_result",
"def test_bit_get_int_accross_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 4, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 16\n assert result[\"bitwise1\"] == expected_result",
"def getInstructionBits(self, offset: int, startbit: int, size: int) -> int:\n ...",
"def getBits(data, offset, bits=1):\n mask = ((1 << bits) - 1) << offset\n return (data & mask) >> offset",
"def get_bits(x, k, size, offset=0):\n\n answer = x >> offset\n answer >>= k * size\n return get_least_significant_bits(answer, size)",
"def test_bit_rscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_multiple_bytes(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 17)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 2 + [128] * 1)\n assert result[\"255\"] == expected_result",
"def getbit(self, key, offset):\n key = self._encode(key)\n index, bits, mask = self._get_bits_and_offset(key, offset)\n\n if index >= len(bits):\n return 0\n\n return 1 if (bits[index] & mask) else 0",
"def _get_bit(self, num, bit, mask=1):\n return (int(num) >> bit) & mask",
"def get_bit(byte, bit_num):\n return (byte & (1 << bit_num)) >> bit_num",
"def test_bit_get_int(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 255\n assert result[\"255\"] == expected_result",
"def GetBits(self, num_bits):\n old_idx_boff = self.idx_boff\n\n bits_available = self.NumBits() - (8*self.idx_byte + self.idx_boff)\n if num_bits > bits_available:\n print \"num_bits: %d but bits_available: %d\" % (num_bits, bits_available)\n raise StandardError()\n retval = []\n bits_left = num_bits\n if self.idx_boff == 0:\n while bits_left >= 8:\n retval.append(self.output[self.idx_byte])\n self.idx_byte += 1\n bits_left -= 8\n if bits_left:\n retval.append( ~(255 >> bits_left) & self.output[self.idx_byte])\n self.idx_boff += bits_left\n self.idx_boff %= 8\n bits_left = 0\n else:\n # We know there is a non-zero bit offset if we're below here.\n cur_byte = 0\n cur_boff = 0\n lob = len(self.output)\n while bits_left > 0:\n if bits_left >= 8 and lob > self.idx_byte:\n cur_byte = 255 & (self.output[self.idx_byte] << self.idx_boff)\n self.idx_byte += 1\n cur_byte |= (self.output[self.idx_byte] >> (8 - self.idx_boff))\n retval.append(cur_byte)\n cur_byte = 0\n bits_left -= 8\n else:\n bits_to_consume = min(min(8 - cur_boff, 8 - self.idx_boff),\n bits_left)\n\n c = self.output[self.idx_byte]\n c <<= self.idx_boff\n c &= 255\n cur_byte |= (c & ~(255 >> (bits_to_consume))) >> cur_boff\n bits_left -= bits_to_consume\n cur_boff += bits_to_consume\n self.idx_boff += bits_to_consume\n if cur_boff >= 8:\n retval.append(cur_byte)\n cur_byte = 0\n cur_boff -= 8\n if self.idx_boff >= 8:\n self.idx_byte += 1\n self.idx_boff -= 8\n if self.idx_boff >= 8:\n raise StandardError()\n if cur_boff:\n retval.append(cur_byte)\n if (old_idx_boff + num_bits) % 8 != self.idx_boff:\n print \"old_idx_boff(%d) + num_bits(%d) != self.idx_boff(%d) \" % (\n old_idx_boff, num_bits, self.idx_boff)\n print \"retval: \", (retval, num_bits)\n raise StandardError()\n return (retval, num_bits)",
"def bitget(x, n):\n return (x >> n) & 1",
"def bit_get(val, idx):\n return (val >> idx) & 1",
"def get_bit(x, k):\n\n return (x >> k) & 1",
"def test_bit_get_int_multiple_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 17, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 131071\n assert result[\"255\"] == expected_result",
"def get_bits( self, count ):\n result = 0\n for i in range( count ):\n if self.bits_remaining <= 0:\n self._fill_buffer()\n if self.bits_reverse:\n bit = (1 if (self.current_bits & (0x80 << 8*(self.bytes_to_cache-1))) else 0)\n self.current_bits <<= 1\n self.current_bits &= 0xff\n else:\n bit = (self.current_bits & 1)\n self.current_bits >>= 1\n\n self.bits_remaining -= 1\n\n if self.output_reverse:\n result <<= 1\n result |= bit\n else:\n result |= bit << i\n return result",
"def _get_bit(byte, ii):\n return (byte >> (7 - ii)) & 1",
"def bits(self, count):\n\n if count < 0:\n raise ValueError\n\n if count > self._bits:\n n_bytes = (count - self._bits + 7) // 8\n data = self._fileobj.read(n_bytes)\n if len(data) != n_bytes:\n raise BitReaderError(\"not enough data\")\n for b in bytearray(data):\n self._buffer = (self._buffer << 8) | b\n self._bits += n_bytes * 8\n\n self._bits -= count\n value = self._buffer >> self._bits\n self._buffer &= (1 << self._bits) - 1\n assert self._bits < 8\n return value",
"def test_bit_lscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def peek(self, bit_length):\n\n if bit_length < 0:\n raise BitReaderError('bit_length(%s) should be greater than 0',\n bit_length)\n elif self.bit_pos + bit_length > len(self):\n raise BitReaderError('out of data boundary')\n\n ret = 0\n byte_ptr, bit_ptr = self.byte_ptr, self.bit_ptr\n\n while bit_length > 0:\n byte = ord(self.data[byte_ptr])\n remaining_bits = 8 - bit_ptr\n\n if bit_length > remaining_bits:\n bit_length -= remaining_bits\n ret |= ((byte & ((1 << remaining_bits) - 1)) << bit_length)\n byte_ptr += 1\n bit_ptr = 0\n else:\n ret |= ((byte >> (remaining_bits - bit_length)) & \\\n ((1 << bit_length) - 1))\n break\n\n return ret",
"def bit(self, idx: int) -> int:\n pos = self.start() + idx\n chunk = self.raw_key()[(pos // 8)]\n bit = pos % 8\n return ((1 << bit) & chunk) >> bit",
"def test_bit_get_fraction_of_byte(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[\"255\"] == expected_result",
"def GetSubBitmap(*args, **kwargs):\n return _gdi_.Bitmap_GetSubBitmap(*args, **kwargs)",
"def read(reader: BitStreamReader, _index: int) -> BitBuffer:\n\n return reader.readBitBuffer()",
"def Bitmap(self, size, name):\n # ------------------------------------------------------------------------\n try:\n return self.bitmaps[size][name]\n except:\n print \"Bitmap(\\\"%s\\\", \\\"%s\\\"): No such thing!\" % (size, name)\n return None",
"def get_bit(self):\n try:\n current_byte = self.contents[self.current_bit_position >> 3]\n except IndexError:\n raise EmptyStreamError(f\"Attempting read at bit position {self.current_bit_position} \"\n f\"(byte {self.current_bit_position >> 3})\")\n bit = min(1, current_byte & (1 << (7 - (self.current_bit_position % 8))))\n self.current_bit_position += 1\n return bit",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result"
] | [
"0.62875754",
"0.6210807",
"0.6210594",
"0.6104591",
"0.60731876",
"0.60564893",
"0.5981193",
"0.5877708",
"0.5841703",
"0.5830928",
"0.5824218",
"0.58029646",
"0.5789045",
"0.5782011",
"0.5763841",
"0.5663442",
"0.5663405",
"0.566137",
"0.5659523",
"0.56565785",
"0.56256235",
"0.55526054",
"0.54916084",
"0.5450657",
"0.5450448",
"0.54472595",
"0.5389684",
"0.5383978",
"0.5375121",
"0.5321805"
] | 0.6607144 | 0 |
Perform a bitwise get with a non existent bin. | def test_bit_get_bad_bin_name(self):
ops = [bitwise_operations.bit_get("bad_name", 0, 1)]
_, _, result = self.as_connection.operate(self.test_key, ops)
expected_result = None
assert result["bad_name"] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def test_bit_get_int_bad_bin_name(self):\n ops = [bitwise_operations.bit_get_int(\"bad_name\", 0, 1, False)]\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = None\n assert result[\"bad_name\"] == expected_result",
"def test_bit_insert_nonexistent_bin_name(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(\"bad_name\", 0, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3])\n assert bins[\"bad_name\"] == expected_result",
"def test_bit_get_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 41, 1)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor_bad_bin_name(self):\n value = bytearray([8])\n ops = [bitwise_operations.bit_xor(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_accross_bytes(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([16] * 1)\n assert result[\"bitwise1\"] == expected_result",
"def test_bit_not(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 0, 40, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_or_bad_bin_name(self):\n value = bytearray([8])\n ops = [bitwise_operations.bit_or(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_not_bad_bin_name(self):\n ops = [bitwise_operations.bit_not(\"bad_name\", 0, 8, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_bad_bin_name(self):\n ops = [bitwise_operations.bit_subtract(\"bad_name\", 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_invalid_bin_name(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_bad_bin_name(self):\n ops = [bitwise_operations.bit_remove(\"bad_name\", 3, 3, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_bad_bin_name(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(\"bad_name\", 0, 8, 1, value, None)]\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_bad_argument_type(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 0, 1.5)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_int_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 41, 1, False)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 0, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 1)\n assert result[\"255\"] == expected_result",
"def test_bit_subtract_simple(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_get_int_accross_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 4, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 16\n assert result[\"bitwise1\"] == expected_result",
"def test_bit_rscan_value_not_found(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.five_255_bin, 0, 40, value)]\n\n expected_value = -1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.five_255_bin] == expected_value",
"def bitwise_not(data):\n return _make.bitwise_not(data)",
"def test_bit_xor_with_policy(self):\n value = bytearray([0])\n bit_policy = {\n \"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY,\n }\n ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, bit_policy)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_add_bad_bin_name(self):\n ops = [bitwise_operations.bit_add(\"bad_name\", 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor(self):\n value = bytearray([1])\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_not_bad_arg(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 2.7, 8, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def bitget(x, n):\n return (x >> n) & 1",
"def bit_get(val, idx):\n return (val >> idx) & 1",
"def test_bit_xor_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def _get_bit(self, num, bit, mask=1):\n return (int(num) >> bit) & mask",
"def no_bin(image, *args, **kwargs):\n return image",
"def test_bit_rscan_bad_bin_name(self):\n value = True\n ops = [bitwise_operations.bit_rscan(\"bad_name\", 0, 8, value)]\n\n expected_value = None\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"bad_name\"] == expected_value"
] | [
"0.65858793",
"0.64688575",
"0.6412785",
"0.6410566",
"0.637989",
"0.6376321",
"0.63263226",
"0.6301394",
"0.6280836",
"0.62782186",
"0.6134096",
"0.61190915",
"0.6102165",
"0.6091341",
"0.6078036",
"0.60745895",
"0.59728205",
"0.5969861",
"0.5958944",
"0.58879626",
"0.5848637",
"0.58457696",
"0.5831275",
"0.5788528",
"0.5788283",
"0.5783067",
"0.57743675",
"0.5763151",
"0.5720535",
"0.5711378"
] | 0.6674132 | 0 |
Perform a bitwise get int op. | def test_bit_get_int(self):
ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, False)]
_, _, result = self.as_connection.operate(self.test_key, ops)
expected_result = 255
assert result["255"] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_get_int_accross_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 4, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 16\n assert result[\"bitwise1\"] == expected_result",
"def bitget(x, n):\n return (x >> n) & 1",
"def bit_get(val, idx):\n return (val >> idx) & 1",
"def _get_bit(self, num, bit, mask=1):\n return (int(num) >> bit) & mask",
"def test_bit_get_int_signed(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, True)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = -1\n assert result[\"255\"] == expected_result",
"def test_bit_get_int_multiple_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 17, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 131071\n assert result[\"255\"] == expected_result",
"def get_bit(num, i):\r\n return 1 if num & 1 << i else 0",
"def test_bit_get(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 0, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 1)\n assert result[\"255\"] == expected_result",
"def getint(data, offset, intsize):\n value = 0\n while intsize > 0:\n value = (value << 8) + data[offset]\n offset += 1\n intsize -= 1\n return value, offset",
"def getint(self, option, argument=None):\n value = self.get(option, argument)\n if value: return int(value)\n else: return 0",
"def test_bit_get_accross_bytes(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([16] * 1)\n assert result[\"bitwise1\"] == expected_result",
"def test_bit_get_int_fraction_of_byte(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 2, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 3\n assert result[\"255\"] == expected_result",
"def read_int(self):\n return self.bits.read(32).intle",
"def int(self):\n assert(self.is_int())\n return self.v >> 1",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def _get_bit(byte, ii):\n return (byte >> (7 - ii)) & 1",
"def getbit(self, key, offset):\n key = self._encode(key)\n index, bits, mask = self._get_bits_and_offset(key, offset)\n\n if index >= len(bits):\n return 0\n\n return 1 if (bits[index] & mask) else 0",
"def get_bit(num, i):\n return num & (1 << i) != 0",
"def get_bit(x, k):\n\n return (x >> k) & 1",
"def test_bit_get_int_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 41, 1, False)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def getInt(self, int: int, int2: int) -> int:\n ...",
"def __getitem__(self, n):\n return (self.num >> np.uint64(n)) & UINT64_ONE",
"def get_bit(num, position):\n\treturn (num >> position) & 0b1",
"def get_bit(byte, bit_num):\n return (byte & (1 << bit_num)) >> bit_num",
"def __getitem__(self, index):\n nth_int, nth_bit = divmod(index, BitArray._UNSIGNED_INT)\n return self.bits[nth_int] & (1 << nth_bit)",
"def output_integer(state, key, data):\n return int(state[key])",
"def read_integer(self, number_of_bits):\n\n value = 0\n\n for _ in range(number_of_bits):\n value <<= 1\n value |= self.read_bit()\n\n return value",
"def __int__(self):\n\n return self.bitflags",
"def getint(self, strcommand):\n result = ct.c_longlong()\n command = ct.c_wchar_p(strcommand)\n self.lib.AT_GetInt(self.AT_H, command, ct.addressof(result))\n return result.value",
"def get_int_bits(self):\n return self.int_bits"
] | [
"0.7102906",
"0.6779233",
"0.66473794",
"0.6560103",
"0.65105355",
"0.643833",
"0.63135123",
"0.6293292",
"0.62082666",
"0.6207934",
"0.6200382",
"0.6193435",
"0.6190294",
"0.61502796",
"0.6123102",
"0.61018723",
"0.60295856",
"0.6009847",
"0.5998483",
"0.597783",
"0.59735185",
"0.5917985",
"0.58955914",
"0.5885951",
"0.58727014",
"0.5856831",
"0.5823485",
"0.58182764",
"0.58069646",
"0.57991177"
] | 0.72884405 | 0 |
Perform a bitwise get int op across bytes. | def test_bit_get_int_accross_bytes(self):
ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 4, 8, False)]
_, _, result = self.as_connection.operate(self.test_key, ops)
expected_result = 16
assert result["bitwise1"] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_get_int_multiple_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 17, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 131071\n assert result[\"255\"] == expected_result",
"def getint(data, offset, intsize):\n value = 0\n while intsize > 0:\n value = (value << 8) + data[offset]\n offset += 1\n intsize -= 1\n return value, offset",
"def test_bit_get_int(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 255\n assert result[\"255\"] == expected_result",
"def test_bit_get_accross_bytes(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([16] * 1)\n assert result[\"bitwise1\"] == expected_result",
"def getByte(self, int: int, int2: int) -> int:\n ...",
"def test_bit_get_int_fraction_of_byte(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 2, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 3\n assert result[\"255\"] == expected_result",
"def read(self, bytes):\r\n return int.from_bytes(self.__input__.read(bytes), byteorder='big')",
"def bytes_to_int(obj):\n return functools.reduce(lambda x, y: x << 8 | y, obj)",
"def _get_bit(byte, ii):\n return (byte >> (7 - ii)) & 1",
"def pick_byte2(input):\n val = int(input) >> 8\n val = val & 255\n return val",
"def test_bit_get(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 0, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 1)\n assert result[\"255\"] == expected_result",
"def convertBytesToInt(self, bytes):\r\n result = 0\r\n for idx in range(len(bytes)):\r\n if idx == 0:\r\n result = int(bytes[0])\r\n else:\r\n result = (result << 8) + bytes[idx]\r\n\r\n return result",
"def bytes_to_int(bs):\n v = 0\n p = 0\n for b in reversed(bs):\n v += b * (2 ** p)\n p += 8\n return v",
"def bitget(x, n):\n return (x >> n) & 1",
"def test_bit_get_int_signed(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, True)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = -1\n assert result[\"255\"] == expected_result",
"def read_int(self):\n return self.bits.read(32).intle",
"def read_byte(self, opcode: int) -> int:\n\n # 0xff = 255\n\n return opcode & 0xFF",
"def _unpack_int_base128(varint, offset):\n res = ord(varint[offset])\n if ord(varint[offset]) >= 0x80:\n offset += 1\n res = ((res - 0x80) << 7) + ord(varint[offset])\n if ord(varint[offset]) >= 0x80:\n offset += 1\n res = ((res - 0x80) << 7) + ord(varint[offset])\n if ord(varint[offset]) >= 0x80:\n offset += 1\n res = ((res - 0x80) << 7) + ord(varint[offset])\n if ord(varint[offset]) >= 0x80:\n offset += 1\n res = ((res - 0x80) << 7) + ord(varint[offset])\n return res, offset + 1",
"def test_bit_get_multiple_bytes(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 17)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 2 + [128] * 1)\n assert result[\"255\"] == expected_result",
"def get_bit(byte, bit_num):\n return (byte & (1 << bit_num)) >> bit_num",
"def read_int(data):\n s_type = \"=%s\" % get_type(\"int\")\n return struct.unpack(s_type, data.read(4))[0]",
"def readInt(self) -> int:\n return self._unpack('!i', 4)",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def unpack_int(self, offset):\n return struct.unpack_from(str(\"<i\"), self._buf, self._offset + offset)[0]",
"def byte_to_int(single_byte: bytes) -> int:\n shift = 0\n result = 0\n if single_byte == b\"\" or single_byte == \"\":\n raise EOFError(\"Unexpected EOF while reading varint\")\n i = ord(single_byte)\n result |= (i & 0x7f) << shift\n return result",
"def bit_get(val, idx):\n return (val >> idx) & 1",
"def access_bit(data, num):\n \n base = int(num // 8)\n shift = int(num % 8)\n return (data[base] & (1<<shift)) >> shift",
"def _decode_vint(buf):\n ctr = 0\n result = 0\n tmp = bytearray(1)\n partial = False\n while 1:\n count = buf.readinto(tmp)\n if count == 0:\n raise EndOfMessage(partial)\n else:\n partial = True\n result |= (tmp[0] & 0x7f) << (7 * ctr)\n if not (tmp[0] >> 7): break\n ctr += 1\n return result",
"def test_bit_get_fraction_of_byte(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[\"255\"] == expected_result",
"def _get_bit(self, num, bit, mask=1):\n return (int(num) >> bit) & mask"
] | [
"0.71205246",
"0.70693725",
"0.69792545",
"0.6811776",
"0.66377413",
"0.66353595",
"0.6517587",
"0.6409903",
"0.6406056",
"0.62259734",
"0.61921054",
"0.6164331",
"0.61605984",
"0.6147947",
"0.6147531",
"0.6143852",
"0.6137119",
"0.6134667",
"0.60648817",
"0.60472596",
"0.6029593",
"0.60230625",
"0.5957375",
"0.59390414",
"0.5930204",
"0.5925501",
"0.5894765",
"0.58610517",
"0.5851834",
"0.58253574"
] | 0.7891104 | 0 |
Perform a bitwise get int op across multiple bytes. | def test_bit_get_int_multiple_bytes(self):
ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 17, False)]
_, _, result = self.as_connection.operate(self.test_key, ops)
expected_result = 131071
assert result["255"] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_get_int_accross_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 4, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 16\n assert result[\"bitwise1\"] == expected_result",
"def getint(data, offset, intsize):\n value = 0\n while intsize > 0:\n value = (value << 8) + data[offset]\n offset += 1\n intsize -= 1\n return value, offset",
"def test_bit_get_int(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 255\n assert result[\"255\"] == expected_result",
"def test_bit_get_accross_bytes(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([16] * 1)\n assert result[\"bitwise1\"] == expected_result",
"def test_bit_get_multiple_bytes(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 17)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 2 + [128] * 1)\n assert result[\"255\"] == expected_result",
"def test_bit_get_int_fraction_of_byte(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 2, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 3\n assert result[\"255\"] == expected_result",
"def getByte(self, int: int, int2: int) -> int:\n ...",
"def bitget(x, n):\n return (x >> n) & 1",
"def bytes_to_int(obj):\n return functools.reduce(lambda x, y: x << 8 | y, obj)",
"def read_integer(self, number_of_bits):\n\n value = 0\n\n for _ in range(number_of_bits):\n value <<= 1\n value |= self.read_bit()\n\n return value",
"def _unpack_int_base128(varint, offset):\n res = ord(varint[offset])\n if ord(varint[offset]) >= 0x80:\n offset += 1\n res = ((res - 0x80) << 7) + ord(varint[offset])\n if ord(varint[offset]) >= 0x80:\n offset += 1\n res = ((res - 0x80) << 7) + ord(varint[offset])\n if ord(varint[offset]) >= 0x80:\n offset += 1\n res = ((res - 0x80) << 7) + ord(varint[offset])\n if ord(varint[offset]) >= 0x80:\n offset += 1\n res = ((res - 0x80) << 7) + ord(varint[offset])\n return res, offset + 1",
"def read(self, bytes):\r\n return int.from_bytes(self.__input__.read(bytes), byteorder='big')",
"def test_bit_get(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 0, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 1)\n assert result[\"255\"] == expected_result",
"def _unpack_uvarint(data: bytes) -> Tuple[int, int]:\n shift = 0\n result = 0\n n = 0\n for b in data:\n n += 1\n result |= (b & 0x7F) << shift\n if not (b & 0x80):\n break\n shift += 7\n return result, n",
"def _unpack_uvarint(data: bytes) -> Tuple[int, int]:\n shift = 0\n result = 0\n n = 0\n for b in data:\n n += 1\n result |= (b & 0x7F) << shift\n if not (b & 0x80):\n break\n shift += 7\n return result, n",
"def _get_bit(byte, ii):\n return (byte >> (7 - ii)) & 1",
"def bytes_to_int(bs):\n v = 0\n p = 0\n for b in reversed(bs):\n v += b * (2 ** p)\n p += 8\n return v",
"def getInstructionBits(self, offset: int, startbit: int, size: int) -> int:\n ...",
"def convertBytesToInt(self, bytes):\r\n result = 0\r\n for idx in range(len(bytes)):\r\n if idx == 0:\r\n result = int(bytes[0])\r\n else:\r\n result = (result << 8) + bytes[idx]\r\n\r\n return result",
"def getInts(self, addr: ghidra.program.model.address.Address, dest: List[int], dIndex: int, nElem: int, isBigEndian: bool) -> int:\n ...",
"def getInt(self, int: int, int2: int) -> int:\n ...",
"def convert_to_ints(command, start, end):\n return [raw_bytes_to_int(command[x:x + BYTES_IN_INT]) for x in range(start, end, BYTES_IN_INT)]",
"def unpack_int8(data):\n value = unpack(DecodeUtils.INT8_BYTE_FORMAT, data[:1])[0]\n return value, 1",
"def pick_byte2(input):\n val = int(input) >> 8\n val = val & 255\n return val",
"def combine_to_int(values):\n multibyte_value = 0\n for byte_id, byte in enumerate(values):\n multibyte_value += 2**(4 * byte_id) * byte\n return multibyte_value",
"def test_bit_get_int_signed(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, True)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = -1\n assert result[\"255\"] == expected_result",
"def bit_get(val, idx):\n return (val >> idx) & 1",
"def test_bit_get_fraction_of_byte(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 4, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[\"255\"] == expected_result",
"def test_bit_get_int_bit_size_too_large(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 0, 41, False)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def readInt(self) -> int:\n return self._unpack('!i', 4)"
] | [
"0.75471073",
"0.678968",
"0.65833163",
"0.6527488",
"0.6496764",
"0.63625884",
"0.6067101",
"0.59414285",
"0.5925806",
"0.5871448",
"0.58513236",
"0.5844034",
"0.5837902",
"0.5762377",
"0.5762377",
"0.57595783",
"0.5753502",
"0.56997323",
"0.568903",
"0.5688321",
"0.5682894",
"0.56745434",
"0.56533474",
"0.56193256",
"0.56089824",
"0.5604894",
"0.560439",
"0.5591523",
"0.55701184",
"0.5557462"
] | 0.75146616 | 1 |
Perform a bitwise get int with a bit_size larger than the bitmap being read. | def test_bit_get_int_bit_size_too_large(self):
ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 0, 41, False)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_get_int(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 255\n assert result[\"255\"] == expected_result",
"def test_bit_get_int_accross_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 4, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 16\n assert result[\"bitwise1\"] == expected_result",
"def getint(data, offset, intsize):\n value = 0\n while intsize > 0:\n value = (value << 8) + data[offset]\n offset += 1\n intsize -= 1\n return value, offset",
"def getInstructionBits(self, offset: int, startbit: int, size: int) -> int:\n ...",
"def test_bit_get_bit_size_too_large(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 0, 41)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def _get_bit(self, num, bit, mask=1):\n return (int(num) >> bit) & mask",
"def bitget(x, n):\n return (x >> n) & 1",
"def read_integer(self, number_of_bits):\n\n value = 0\n\n for _ in range(number_of_bits):\n value <<= 1\n value |= self.read_bit()\n\n return value",
"def test_bit_get_int_multiple_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 17, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 131071\n assert result[\"255\"] == expected_result",
"def _get_bit(byte, ii):\n return (byte >> (7 - ii)) & 1",
"def get_bit(byte, bit_num):\n return (byte & (1 << bit_num)) >> bit_num",
"def bit_get(val, idx):\n return (val >> idx) & 1",
"def test_bit_get_int_fraction_of_byte(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 2, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 3\n assert result[\"255\"] == expected_result",
"def get_bit(num, i):\r\n return 1 if num & 1 << i else 0",
"def getbit(self, key, offset):\n key = self._encode(key)\n index, bits, mask = self._get_bits_and_offset(key, offset)\n\n if index >= len(bits):\n return 0\n\n return 1 if (bits[index] & mask) else 0",
"def test_bit_get_int_signed(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, True)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = -1\n assert result[\"255\"] == expected_result",
"def read_int(self):\n return self.bits.read(32).intle",
"def bit(self, idx: int) -> int:\n pos = self.start() + idx\n chunk = self.raw_key()[(pos // 8)]\n bit = pos % 8\n return ((1 << bit) & chunk) >> bit",
"def test_bit_get(self):\n ops = [bitwise_operations.bit_get(self.five_255_bin, 0, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([255] * 1)\n assert result[\"255\"] == expected_result",
"def getBits(data, offset, bits=1):\n mask = ((1 << bits) - 1) << offset\n return (data & mask) >> offset",
"def GetBits(self, num_bits):\n old_idx_boff = self.idx_boff\n\n bits_available = self.NumBits() - (8*self.idx_byte + self.idx_boff)\n if num_bits > bits_available:\n print \"num_bits: %d but bits_available: %d\" % (num_bits, bits_available)\n raise StandardError()\n retval = []\n bits_left = num_bits\n if self.idx_boff == 0:\n while bits_left >= 8:\n retval.append(self.output[self.idx_byte])\n self.idx_byte += 1\n bits_left -= 8\n if bits_left:\n retval.append( ~(255 >> bits_left) & self.output[self.idx_byte])\n self.idx_boff += bits_left\n self.idx_boff %= 8\n bits_left = 0\n else:\n # We know there is a non-zero bit offset if we're below here.\n cur_byte = 0\n cur_boff = 0\n lob = len(self.output)\n while bits_left > 0:\n if bits_left >= 8 and lob > self.idx_byte:\n cur_byte = 255 & (self.output[self.idx_byte] << self.idx_boff)\n self.idx_byte += 1\n cur_byte |= (self.output[self.idx_byte] >> (8 - self.idx_boff))\n retval.append(cur_byte)\n cur_byte = 0\n bits_left -= 8\n else:\n bits_to_consume = min(min(8 - cur_boff, 8 - self.idx_boff),\n bits_left)\n\n c = self.output[self.idx_byte]\n c <<= self.idx_boff\n c &= 255\n cur_byte |= (c & ~(255 >> (bits_to_consume))) >> cur_boff\n bits_left -= bits_to_consume\n cur_boff += bits_to_consume\n self.idx_boff += bits_to_consume\n if cur_boff >= 8:\n retval.append(cur_byte)\n cur_byte = 0\n cur_boff -= 8\n if self.idx_boff >= 8:\n self.idx_byte += 1\n self.idx_boff -= 8\n if self.idx_boff >= 8:\n raise StandardError()\n if cur_boff:\n retval.append(cur_byte)\n if (old_idx_boff + num_bits) % 8 != self.idx_boff:\n print \"old_idx_boff(%d) + num_bits(%d) != self.idx_boff(%d) \" % (\n old_idx_boff, num_bits, self.idx_boff)\n print \"retval: \", (retval, num_bits)\n raise StandardError()\n return (retval, num_bits)",
"def get_bit(x, k):\n\n return (x >> k) & 1",
"def extract_bits(data, bit, length=1):\n bits = bitarray(data, endian='big')\n if length > 1:\n out = bits[bit:bit+length]\n try:\n out = struct.unpack('>B', out.tobytes())[0]\n except struct.error:\n out = 0\n else:\n try:\n out = bits[bit]\n except IndexError:\n out = 0\n return int(out)",
"def get_bit(self):\n try:\n current_byte = self.contents[self.current_bit_position >> 3]\n except IndexError:\n raise EmptyStreamError(f\"Attempting read at bit position {self.current_bit_position} \"\n f\"(byte {self.current_bit_position >> 3})\")\n bit = min(1, current_byte & (1 << (7 - (self.current_bit_position % 8))))\n self.current_bit_position += 1\n return bit",
"def read_bits_as_int(self, num_bits) -> int:\n if num_bits > 0:\n bits = self.read_bits(num_bits)\n log.info(f\"bits: {bits}\")\n log.info(f\"num_bits: {num_bits}\")\n try:\n int_bits = int(bits, 2)\n except ValueError:\n raise NoMoreBitsException(self.original_message)\n return int_bits",
"def read(self, reader: BitStreamReader, _index: int) -> int:\n\n return reader.readBits(self._numBits)",
"def get_bit(num, position):\n\treturn (num >> position) & 0b1",
"def test_bit_get_accross_bytes(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 4, 8)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([16] * 1)\n assert result[\"bitwise1\"] == expected_result",
"def getContextBits(self, startbit: int, bitsize: int) -> int:\n ...",
"def test_bit_rscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)"
] | [
"0.68701124",
"0.68527347",
"0.6686685",
"0.6607664",
"0.6548053",
"0.6484254",
"0.6442532",
"0.6422704",
"0.6400369",
"0.6389926",
"0.6377081",
"0.6276066",
"0.6234731",
"0.6165739",
"0.6152089",
"0.6149299",
"0.6145901",
"0.61367106",
"0.60860854",
"0.5989236",
"0.598441",
"0.59733415",
"0.596445",
"0.5958791",
"0.59202",
"0.5910645",
"0.58864874",
"0.5885328",
"0.5872345",
"0.5871419"
] | 0.70119935 | 0 |
Perform a bitwise get int op with sign true. | def test_bit_get_int_signed(self):
ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, True)]
_, _, result = self.as_connection.operate(self.test_key, ops)
expected_result = -1
assert result["255"] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_get_int(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 0, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 255\n assert result[\"255\"] == expected_result",
"def _get_bit(self, num, bit, mask=1):\n return (int(num) >> bit) & mask",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def test_bit_get_int_accross_bytes(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 4, 8, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 16\n assert result[\"bitwise1\"] == expected_result",
"def bit_get(val, idx):\n return (val >> idx) & 1",
"def get_bit(num, i):\r\n return 1 if num & 1 << i else 0",
"def bitget(x, n):\n return (x >> n) & 1",
"def get_bit(num, i):\n return num & (1 << i) != 0",
"def __int__(self):\n\n return self.bitflags",
"def int(self):\n assert(self.is_int())\n return self.v >> 1",
"def getint(self, option, argument=None):\n value = self.get(option, argument)\n if value: return int(value)\n else: return 0",
"def __neg__(self) -> 'SInt':\r\n return self.complement()",
"def is_int(self):\n return self.v & 1 != 0",
"def bits_to_int(jit_bits: ir_bits.Bits, signed: bool) -> int:\n assert isinstance(jit_bits, ir_bits.Bits), jit_bits\n bit_count = jit_bits.bit_count()\n bits_value = jit_bits.to_uint()\n\n return (bits_value if not signed else bit_helpers.from_twos_complement(\n bits_value, bit_count))",
"def test_bit_get_int_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 41, 1, False)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def get_bit(num, position):\n\treturn (num >> position) & 0b1",
"def _get_bit(byte, ii):\n return (byte >> (7 - ii)) & 1",
"def bintogray(x: int) -> int:\n assert x >= 0\n return x ^ (x >> 1)",
"def test_bit_get_int_bad_argument_type(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 0, 1.5, False)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_int_fraction_of_byte(self):\n ops = [bitwise_operations.bit_get_int(self.five_255_bin, 4, 2, False)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = 3\n assert result[\"255\"] == expected_result",
"def sign(x):\n if x >= 0:\n return 1\n else:\n return -1",
"def get_bit(x, k):\n\n return (x >> k) & 1",
"def sign(self):\n return 1 - 2 * self._ltz()",
"def _get_positive_int(raw_value):\n value = int(raw_value)\n if value < 0:\n raise ValueError(\"negative\")\n return value",
"def sign(a) :\n return (a>0) - (a<0)",
"def sign(x):\n if x >= 0:\n return 1\n return -1",
"def get_lowest_set_bit(x):\n\n return x & -x",
"def __rshift__(self, other):\r\n # TODO: extend to secret offset\r\n if not isinstance(other, int):\r\n return NotImplemented\r\n\r\n return self.__floordiv__(1<<other)",
"def sign(a):\n return (a > 0) - (a < 0)",
"def _bool_to_int(self, bool_arg):\n if bool_arg == True:\n return 1\n else:\n return 0"
] | [
"0.6509758",
"0.63602674",
"0.6266089",
"0.62134486",
"0.6150972",
"0.60837835",
"0.5986445",
"0.5969886",
"0.5921053",
"0.5897795",
"0.5893982",
"0.5842662",
"0.5799386",
"0.57741714",
"0.57586473",
"0.5749016",
"0.5726743",
"0.5701007",
"0.56617063",
"0.56174797",
"0.56127846",
"0.5611167",
"0.56059843",
"0.5574422",
"0.5557395",
"0.555109",
"0.5514759",
"0.5501259",
"0.54927117",
"0.54916143"
] | 0.7207223 | 0 |
Perform a bitwise insert op. | def test_bit_insert(self):
value = bytearray([3])
ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 1, value, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([3] * 1 + [0] * 5)
assert bins[self.test_bin_zeroes] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def _insert_op(self, op):",
"def test_bit_insert_multiple_bytes_with_offset(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 2, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 2 + [3] * 3 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_multiple_bytes(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 3 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_value_byte_size_smaller_than_value(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 2, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 2 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_insert_bad_arg_type(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 1.5, value, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def place(arr, mask, vals):\n return _insert(arr, mask, vals)",
"def test_bit_insert_offset_out_of_range(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 9, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5 + [0] * 4 + [3] * 1)\n assert bins[self.five_255_bin] == expected_result",
"def insert(self, val: int) -> bool:",
"def test_bit_insert_value_byte_size_too_large(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 6, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 6 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def insert(self, *args):\n self.insert_count += 1\n self.total_ops += 1\n return super(BulkOperator, self).insert(*args)",
"def insert(self, *a):\r\n return self.stack.insert(*a)",
"def insert(self, item):\n for h_num in xrange(self.k):\n val = self.hash_value(item, h_num)\n self.arr[val] = True",
"def hot1_insert(seq_1hot, pos, insert_seq):\n\n # shift right\n seq_1hot[pos + len(insert_seq):, :] = seq_1hot[pos:-len(insert_seq), :]\n # e.g.\n # seq_1hot[100+3:,:] = seq_1hot[100:-3,:]\n\n # reset\n seq_1hot[pos:pos + len(insert_seq), :4] = 0\n\n for i in range(len(insert_seq)):\n nt = insert_seq[i]\n\n # set\n if nt == 'A':\n seq_1hot[pos + i, 0] = 1\n elif nt == 'C':\n seq_1hot[pos + i, 1] = 1\n elif nt == 'G':\n seq_1hot[pos + i, 2] = 1\n elif nt == 'T':\n seq_1hot[pos + i, 3] = 1\n else:\n print('Invalid nucleotide insert %s' % nt, file=sys.stderr)",
"def insert(self, val: int) -> bool:\n if self.d.get(val):\n return False\n else:\n self.d[val] = True\n return True",
"def insert(self, new):\n return self.replace(None, new)",
"def insert(self, value):\n\n\n if value < self.data:\n if self.left:\n self.left.insert(value)\n else:\n self.left = BinaryNode(value)\n\n elif value > self.data:\n if self.right:\n self.right.insert(value)\n else:\n self.right = BinaryNode(value)\n\n else:\n self.data = self.data",
"def insert_before(self, insert_pos_inst):\n basic_block = insert_pos_inst.basic_block\n if basic_block is None:\n raise IRError('Instruction is not in basic block')\n idx = basic_block.insts.index(insert_pos_inst)\n self.basic_block = basic_block\n basic_block.insts.insert(idx, self)",
"def insert(self, *args):\n return _ida_hexrays.hexwarns_t_insert(self, *args)",
"def insert(self, position, insert):\n assert all(new in self.ALPHABET for new in insert)\n if position < 1 or position - 1 > len(self.sequence):\n raise ValueError(f\"Insertion position {position} out of bonds for given sequence.\")\n self.sequence = f\"{self.sequence[: position - 1]}{insert}{self.sequence[position:]}\"\n if \"mutations\" in self.metadata.keys():\n self.metadata[\"mutations\"] += f\" ins{position}{insert}\"\n else:\n self.metadata[\"mutations\"] = f\"ins{position}{insert}\"",
"def test_bit_insert_nonexistent_bin_name(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(\"bad_name\", 0, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3])\n assert bins[\"bad_name\"] == expected_result",
"def insert(self, data):\r\n pass",
"def insert(self, key, value):\n\t\tself.__insert(key, value, key[1:])",
"def insert(self, val):\n self.data.insert(0,val)\n self.size = self.size + 1",
"def insert(self, i, x) -> None:\n pass",
"def insert(self):\n pass",
"def _insert(self, key, value):\n entry = self._lookup(key)\n if entry.value is None:\n self.used += 1\n if entry.key is not dummy:\n self.filled += 1\n entry.key = key\n entry.hash = self.first_hash(key)\n entry.value = value",
"def test_bit_add_simple(self):\n ops = [bitwise_operations.bit_add(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([2] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def insert(self, val):\n if val in self.d:\n return False\n self.d[val] = len(self.l)\n self.l.append(val)\n return True",
"def test_bit_add_inbetween_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def bst_insert(sizes):\n tree = rbTree_main.BinarySearchTree();\n for i in range(sizes):\n tree.insert(random.random())"
] | [
"0.71780396",
"0.658312",
"0.65635574",
"0.63127637",
"0.6227794",
"0.61238205",
"0.6090394",
"0.59877443",
"0.5869586",
"0.58213556",
"0.57300776",
"0.56653476",
"0.5499907",
"0.5486901",
"0.54348606",
"0.5416248",
"0.53926224",
"0.5384943",
"0.53558993",
"0.5337077",
"0.53359234",
"0.5334946",
"0.53314424",
"0.53040427",
"0.52938896",
"0.5269964",
"0.52522355",
"0.52493787",
"0.52373415",
"0.5231172"
] | 0.7138453 | 1 |
Perform a bitwise insert op with multiple bytes and a non 0 offset. | def test_bit_insert_multiple_bytes_with_offset(self):
value = bytearray([3] * 3)
ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 2, 3, value, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([0] * 2 + [3] * 3 + [0] * 3)
assert bins[self.test_bin_zeroes] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_insert_multiple_bytes(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 3 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def _insert_op(self, op):",
"def test_bit_insert(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 1 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_offset_out_of_range(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 9, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5 + [0] * 4 + [3] * 1)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_insert_bad_arg_type(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 1.5, value, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def place(arr, mask, vals):\n return _insert(arr, mask, vals)",
"def test_bit_insert_value_byte_size_smaller_than_value(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 2, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 2 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_insert_value_byte_size_too_large(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 6, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 6 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def hot1_insert(seq_1hot, pos, insert_seq):\n\n # shift right\n seq_1hot[pos + len(insert_seq):, :] = seq_1hot[pos:-len(insert_seq), :]\n # e.g.\n # seq_1hot[100+3:,:] = seq_1hot[100:-3,:]\n\n # reset\n seq_1hot[pos:pos + len(insert_seq), :4] = 0\n\n for i in range(len(insert_seq)):\n nt = insert_seq[i]\n\n # set\n if nt == 'A':\n seq_1hot[pos + i, 0] = 1\n elif nt == 'C':\n seq_1hot[pos + i, 1] = 1\n elif nt == 'G':\n seq_1hot[pos + i, 2] = 1\n elif nt == 'T':\n seq_1hot[pos + i, 3] = 1\n else:\n print('Invalid nucleotide insert %s' % nt, file=sys.stderr)",
"def insert(self, *args):\n self.insert_count += 1\n self.total_ops += 1\n return super(BulkOperator, self).insert(*args)",
"def insert(self, *a):\r\n return self.stack.insert(*a)",
"def insert(self, pos, length):\n if pos in self.insertions:\n self.insertions[pos] += length\n else:\n self.insertions[pos] = length",
"def insert_at(sequence, index, element):\n # ... and the rest is up to you\n\n new_sequence = sequence[:index] + element + sequence[index:]\n return new_sequence",
"def insert_sequence(x,y,z):\n return x[:z] + y + x[z:]",
"def ListInsert(raw_list,insert_indice,value = None,padding = None):\n length = len(raw_list)\n if insert_indice+1 <= length:\n raw_list[insert_indice] = value\n else:\n for i in range(length,insert_indice):\n raw_list.append(padding)\n raw_list.append(value)",
"def test_bit_add_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_inbetween_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def insert(self, i, x) -> None:\n pass",
"def insert_slice_in_zeros(\n slice_to_insert: jnp.ndarray,\n dim: int,\n dim_size: int,\n position: int,\n) -> jnp.ndarray:\n slice_shape = slice_to_insert.shape\n if slice_shape[dim] != 1:\n raise ValueError(f\"Expected slice_to_insert.shape to have {dim} dim of 1,\"\n f\" but was {slice_to_insert.shape[dim]}.\")\n\n before = [0] * int(len(slice_shape))\n after = before[:]\n before[dim] = position\n after[dim] = dim_size - position - 1\n return jnp.pad(slice_to_insert, list(zip(before, after)))",
"def test_bit_add_multiple_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 2 + [0] * 2)\n assert bins[self.test_bin_zeroes] == expected_result",
"def insert(self, position, insert):\n assert all(new in self.ALPHABET for new in insert)\n if position < 1 or position - 1 > len(self.sequence):\n raise ValueError(f\"Insertion position {position} out of bonds for given sequence.\")\n self.sequence = f\"{self.sequence[: position - 1]}{insert}{self.sequence[position:]}\"\n if \"mutations\" in self.metadata.keys():\n self.metadata[\"mutations\"] += f\" ins{position}{insert}\"\n else:\n self.metadata[\"mutations\"] = f\"ins{position}{insert}\"",
"def array_insert(arr1, arr2, axis=1):\n arr3 = num.insert(arr1, len(arr1.T), arr2, axis=axis)\n\n return arr3",
"def insert(self, val):\n self.data.insert(0,val)\n self.size = self.size + 1",
"def test_bit_and_offset_value_byte_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def udcall_map_insert(*args):\n return _ida_hexrays.udcall_map_insert(*args)",
"def insert(self, data):\r\n pass",
"def insert_bytes(self, bytes_to_write, location=None, overwrite=False):\n num_bytes = len(bytes_to_write)\n\n off = self._offset\n if location is not None:\n off = location\n if overwrite:\n self._tiff[off:off + num_bytes] = bytes_to_write\n else:\n self._tiff = np.insert(self._tiff, off, bytes_to_write)\n if location is None:\n self._offset += num_bytes\n\n return num_bytes",
"def testInsert(self):\n\n for i in xrange(randint(50,150)):\n self.s.insert(i, None)",
"def insert_before(self, insert_pos_inst):\n basic_block = insert_pos_inst.basic_block\n if basic_block is None:\n raise IRError('Instruction is not in basic block')\n idx = basic_block.insts.index(insert_pos_inst)\n self.basic_block = basic_block\n basic_block.insts.insert(idx, self)",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)"
] | [
"0.7038556",
"0.65061796",
"0.64552087",
"0.6403019",
"0.60924107",
"0.60375494",
"0.6032577",
"0.5855531",
"0.5665722",
"0.5656832",
"0.55806595",
"0.5539267",
"0.54879755",
"0.54079443",
"0.5370666",
"0.53351605",
"0.53261304",
"0.52470505",
"0.51999",
"0.5158822",
"0.5149186",
"0.5110641",
"0.5109948",
"0.5096598",
"0.50785583",
"0.5076621",
"0.5074993",
"0.50705904",
"0.5052759",
"0.50462157"
] | 0.7592493 | 0 |
Perform a bitwise insert op where byte_offset is out of range for the bitmap being modified. Places 0 untill proper offset is reached. | def test_bit_insert_offset_out_of_range(self):
value = bytearray([3])
ops = [bitwise_operations.bit_insert(self.five_255_bin, 9, 1, value, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([255] * 5 + [0] * 4 + [3] * 1)
assert bins[self.five_255_bin] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_insert_multiple_bytes_with_offset(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 2, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 2 + [3] * 3 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_value_byte_size_smaller_than_value(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 2, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 2 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_insert_value_byte_size_too_large(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 6, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 6 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_add_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_insert(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 1 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_multiple_bytes(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 3 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def insert_bytes(self, bytes_to_write, location=None, overwrite=False):\n num_bytes = len(bytes_to_write)\n\n off = self._offset\n if location is not None:\n off = location\n if overwrite:\n self._tiff[off:off + num_bytes] = bytes_to_write\n else:\n self._tiff = np.insert(self._tiff, off, bytes_to_write)\n if location is None:\n self._offset += num_bytes\n\n return num_bytes",
"def _insert_op(self, op):",
"def test_bit_insert_bad_arg_type(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 1.5, value, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def insert_bytes(fobj, size, offset, BUFFER_SIZE=2 ** 16):\n\n if size < 0 or offset < 0:\n raise ValueError\n\n fobj.seek(0, 2)\n filesize = fobj.tell()\n movesize = filesize - offset\n\n if movesize < 0:\n raise ValueError\n\n resize_file(fobj, size, BUFFER_SIZE)\n\n if mmap is not None:\n try:\n mmap_move(fobj, offset + size, offset, movesize)\n except mmap.error:\n fallback_move(fobj, offset + size, offset, movesize, BUFFER_SIZE)\n else:\n fallback_move(fobj, offset + size, offset, movesize, BUFFER_SIZE)",
"def AdvanceToByteBoundary(self):\n bits_to_advance = (8 - self.idx_boff) % 8\n if bits_to_advance:\n self.idx_boff += bits_to_advance\n self.idx_boff %= 8\n self.idx_byte += 1",
"def insert_bytes(self,fobj, size, offset, BUFFER_SIZE=2 ** 16):\n\n if size < 0 or offset < 0:\n raise ValueError\n\n fobj.seek(0, 2)\n filesize = fobj.tell()\n movesize = filesize - offset\n\n if movesize < 0:\n raise ValueError\n\n self.resize_file(fobj, size, BUFFER_SIZE)\n\n self.mmap_move(fobj, offset + size, offset, movesize)",
"def in_place_offset(self, offset):\n self.p += offset * self.cross_z.normalized()",
"def replace_buffer(new_data, offset, datatype):\n offset = offset - 1\n\n if offset < 0:\n # If our buffer was a zero buffer, we don't need to bother changing.\n return\n\n global buffer\n buffer_size = len(new_data.flatten()) * dtype_size(datatype)\n (buffer_size, new_data) = align(buffer_size, new_data)\n\n # print(offset)\n buffer[offset] = new_data",
"def test_bit_and_offset_out_of_range(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_value_byte_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def set_offset(self, offset):\r\n for b in self.buf:\r\n b.set_offset(offset)",
"def place(arr, mask, vals):\n return _insert(arr, mask, vals)",
"def test_bit_set_bit_random_byte_random_offset(self):\n value = bytearray()\n rand_byte = random.randint(0, 255)\n value.append(rand_byte)\n rand_offset = random.randint(0, 4) * 8\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, rand_offset, 8, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n expected_result[rand_offset // 8] = rand_byte\n assert bins[self.test_bin_zeroes] == expected_result\n # should set the byte at rand_offset/8 to rand_byte",
"def test_bit_add_inbetween_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def insert_slice_in_zeros(\n slice_to_insert: jnp.ndarray,\n dim: int,\n dim_size: int,\n position: int,\n) -> jnp.ndarray:\n slice_shape = slice_to_insert.shape\n if slice_shape[dim] != 1:\n raise ValueError(f\"Expected slice_to_insert.shape to have {dim} dim of 1,\"\n f\" but was {slice_to_insert.shape[dim]}.\")\n\n before = [0] * int(len(slice_shape))\n after = before[:]\n before[dim] = position\n after[dim] = dim_size - position - 1\n return jnp.pad(slice_to_insert, list(zip(before, after)))",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def insert_before(self, insert_pos_inst):\n basic_block = insert_pos_inst.basic_block\n if basic_block is None:\n raise IRError('Instruction is not in basic block')\n idx = basic_block.insts.index(insert_pos_inst)\n self.basic_block = basic_block\n basic_block.insts.insert(idx, self)",
"def insert(self, pos, length):\n if pos in self.insertions:\n self.insertions[pos] += length\n else:\n self.insertions[pos] = length",
"def insert_bitmap(self, a, xpos, ypos, color=defcolor):\n for y in range(len(a)):\n matrix_y = ypos + y\n for x in range(len(a[y])):\n matrix_x = xpos + x\n # If the pixel is 1 in the bitmap and if it's is inside the\n # the matrix. Otherwise don't write it on the matrix.\n if (a[y][x] == 1 and\n matrix_x >= 0 and matrix_y >= 0 and\n matrix_x < self.x and matrix_y < self.y\n ):\n self.matrix[matrix_y][matrix_x] = color",
"def unshift(self, chunk):\n if chunk:\n self._pos -= len(chunk)\n self._unconsumed.append(chunk)",
"def test_bit_set_bit_index_out_of_range(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 41, 8, 1, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def set_bit(self, index_of_byte, index_of_bit, new_value):\n if index_of_bit >= self.binary_size:\n print(\"You tried to modify a byte at %d index. This cannot be done. The maximum index is %d.\"%(index_of_bit, self.binary_size - 1))\n else:\n new_value = str(new_value)\n byte = self.binary_array[index_of_byte]\n new_byte = byte[0:index_of_bit] + new_value\n if index_of_bit < self.binary_size - 1: # you aren't changing the final bit in the byte\n new_byte += byte[index_of_bit + 1:]\n #apply changes\n self.binary_array[index_of_byte] = new_byte",
"def img_offset_X(img, offset_X):\n offset_X = int(offset_X)\n (axe_X, axe_Y) = img.size\n\n while offset_X >= axe_X:\n offset_X -= axe_X\n\n if offset_X == 0:\n return img\n\n if offset_X < 0:\n offset_X = -offset_X\n img_right = img.crop((0, 0, axe_X-offset_X, axe_Y))\n img_left = img.crop((axe_X-offset_X, 0, axe_X, axe_Y))\n img.paste(img_right, (offset_X, 0))\n\n else:\n img_right = img.crop((0, 0, offset_X, axe_Y))\n img_left = img.crop((offset_X, 0, axe_X, axe_Y))\n img.paste(img_right, (axe_X-offset_X, 0))\n\n img.paste(img_left, (0, 0))\n\n return img.copy()"
] | [
"0.6690235",
"0.60884166",
"0.60283166",
"0.5965435",
"0.58556616",
"0.5721447",
"0.5667663",
"0.5619984",
"0.55654263",
"0.55636644",
"0.5560772",
"0.55084085",
"0.5501264",
"0.5473809",
"0.54536104",
"0.53604025",
"0.5360399",
"0.5353372",
"0.535322",
"0.52948534",
"0.5293944",
"0.5278425",
"0.52405226",
"0.5235032",
"0.5219094",
"0.51910645",
"0.5181898",
"0.5173906",
"0.51322156",
"0.5117573"
] | 0.7140981 | 0 |
Perform a bitwise insert op where value_byte_size is larger than the bitmap being modified. | def test_bit_insert_value_byte_size_too_large(self):
value = bytearray([3] * 6)
ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 6, value, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([3] * 6 + [255] * 5)
assert bins[self.five_255_bin] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_insert_value_byte_size_smaller_than_value(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 2, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 2 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_insert_offset_out_of_range(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 9, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5 + [0] * 4 + [3] * 1)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_insert(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 1 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_multiple_bytes(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 3 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_bad_arg_type(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 1.5, value, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_value_byte_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_insert_multiple_bytes_with_offset(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 2, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 2 + [3] * 3 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def insert(self, value):\n bucketNum = self.__hash(value)\n originalBucketNum = bucketNum\n if self.__buckets[bucketNum] is not None:\n bucketNum = self.__rehash(bucketNum)\n while self.__buckets[bucketNum] is not None and bucketNum != originalBucketNum:\n bucketNum = self.__rehash(bucketNum)\n if self.__buckets[bucketNum] is None:\n self.__buckets[bucketNum] = value\n else:\n raise Exception(\"Table Full\")",
"def insert(self, value):\n self.heap.append(value)\n self._shiftUp()",
"def test_bit_set_bit_value_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 48, 6, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def _insert(self, key, value):\n entry = self._lookup(key)\n if entry.value is None:\n self.used += 1\n if entry.key is not dummy:\n self.filled += 1\n entry.key = key\n entry.hash = self.first_hash(key)\n entry.value = value",
"def test_bit_add_bit_size_signed(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 254, True, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([253] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def insert(self, value):\n self.heap.append(value)\n index = len(self.heap) - 1\n self._percolate_up(index)",
"def insert(self, val: int) -> bool:\n if val in self.val2i: return False\n if self.size == len(self.array): self.array.append(val)\n else: self.array[self.size] = val\n self.val2i[val] = self.size\n self.size += 1\n #print(self.size)\n return True",
"def insert(self, val):\n self.data.insert(0,val)\n self.size = self.size + 1",
"def test_bit_set_bit_bit_size_too_large(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 16, 1, value, None)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def insert(self, key, value):\n # Resize array here if necessary.\n if key < 0: key = 0\n elif key > len(self): key = len(self)\n if key < len(self):\n for j in range(len(self), key, -1):\n self._items[j] = self._items[j - 1]\n self._items[key] = value\n self._size += 1\n self.incModCount()",
"def test_bit_resize_shrink_only_does_not_allow_grow(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 10, resize_flags=aerospike.BIT_RESIZE_SHRINK_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def insert(self, value):\n bucketNum = self.__hash(value)\n self.__buckets[bucketNum].append(value)",
"def insert(self, key, value): #hidden\n # return the bin number of table\n index = self.hash_function(key)\n # do not insert empty string\n if index != -1:\n # insert item in empty bucket\n if self.table[index] is None:\n self.table[index] = HashNode(key, value)\n self.size += 1\n # if the key is present, update value\n elif self.table[index].key == key:\n self.table[index].value = value\n # resolve conflicts\n else:\n index = self.quadratic_probe(key)\n if self.table[index] is None:\n self.table[index] = HashNode(key, value)\n self.size += 1\n # if the key is present, update value\n elif self.table[index].key == key:\n self.table[index].value = value\n # grow size\n load_factor = self.size / self.capacity\n if load_factor > 0.75:\n self.grow()",
"def test_bit_resize_grow_only_does_not_allow_shrink(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 1, resize_flags=aerospike.BIT_RESIZE_GROW_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def insert(self, key, value):\r\n self._data.append(self._Item(key, value))\r\n self._upheap(len(self._data) - 1) # upheap newly added position\r",
"def insert_int(self, value, size=4, location=None, overwrite=False):\n self.insert_ints([value], size=size, location=location, overwrite=overwrite)",
"def insert(self, key, value):\r\n hash_val = Hash(key, value)\r\n self.hash_table[self.horner_hash(key)] = hash_val\r\n self.num_items += 1\r\n\r\n if self.get_load_factor() > 0.5:\r\n prev = HashTable(self.table_size)\r\n prev.num_items = self.num_items\r\n prev.hash_table = self.hash_table\r\n prev.table_size = self.table_size\r\n\r\n self.table_size = self.table_size * 2 + 1\r\n self.num_items = 0\r\n self.hash_table = [None] * self.table_size\r\n\r\n for i in range(prev.table_size):\r\n if prev.hash_table[i] is not None:\r\n self.insert(prev.hash_table[i].key, prev.hash_table[i].value)",
"def bst_insert(sizes):\n tree = rbTree_main.BinarySearchTree();\n for i in range(sizes):\n tree.insert(random.random())",
"def test_bit_add_overflow_saturate(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_SATURATE, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def _insert_op(self, op):",
"def insert(self, item):\n for h_num in xrange(self.k):\n val = self.hash_value(item, h_num)\n self.arr[val] = True",
"def insert(self, key: K, value: V) -> None:\n if key in self.__key_map__:\n self.remove(key)\n\n entry = (value, next(self.counter), key)\n self.__key_map__[key] = entry\n\n heapq.heappush(self.queue, entry)"
] | [
"0.769737",
"0.6404579",
"0.6023742",
"0.59848",
"0.5913847",
"0.5910126",
"0.5844481",
"0.5764318",
"0.5716509",
"0.5664945",
"0.56231964",
"0.55951345",
"0.5508419",
"0.54928094",
"0.54876983",
"0.5483207",
"0.54789144",
"0.5427363",
"0.5410783",
"0.53932405",
"0.53805816",
"0.5361593",
"0.53459",
"0.53440887",
"0.533471",
"0.5303463",
"0.52806455",
"0.5278703",
"0.5246013",
"0.52222884"
] | 0.7693409 | 1 |
Perform a bitwise insert op where value_byte_size is smaller than the bitmap being modified. | def test_bit_insert_value_byte_size_smaller_than_value(self):
value = bytearray([3] * 6)
ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 2, value, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([3] * 2 + [255] * 5)
assert bins[self.five_255_bin] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_insert_value_byte_size_too_large(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 6, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 6 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_insert_offset_out_of_range(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 9, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5 + [0] * 4 + [3] * 1)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_insert(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 1 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_multiple_bytes(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 3 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_bad_arg_type(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 1.5, value, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_value_byte_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_insert_multiple_bytes_with_offset(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 2, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 2 + [3] * 3 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def insert(self, value):\n bucketNum = self.__hash(value)\n originalBucketNum = bucketNum\n if self.__buckets[bucketNum] is not None:\n bucketNum = self.__rehash(bucketNum)\n while self.__buckets[bucketNum] is not None and bucketNum != originalBucketNum:\n bucketNum = self.__rehash(bucketNum)\n if self.__buckets[bucketNum] is None:\n self.__buckets[bucketNum] = value\n else:\n raise Exception(\"Table Full\")",
"def insert(self, value):\n self.heap.append(value)\n self._shiftUp()",
"def _insert(self, key, value):\n entry = self._lookup(key)\n if entry.value is None:\n self.used += 1\n if entry.key is not dummy:\n self.filled += 1\n entry.key = key\n entry.hash = self.first_hash(key)\n entry.value = value",
"def test_bit_set_bit_value_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 48, 6, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_bit_size_signed(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 254, True, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([253] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def insert(self, value):\n self.heap.append(value)\n index = len(self.heap) - 1\n self._percolate_up(index)",
"def insert(self, val: int) -> bool:\n if val in self.val2i: return False\n if self.size == len(self.array): self.array.append(val)\n else: self.array[self.size] = val\n self.val2i[val] = self.size\n self.size += 1\n #print(self.size)\n return True",
"def insert(self, val):\n self.data.insert(0,val)\n self.size = self.size + 1",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def insert(self, key, value):\n # Resize array here if necessary.\n if key < 0: key = 0\n elif key > len(self): key = len(self)\n if key < len(self):\n for j in range(len(self), key, -1):\n self._items[j] = self._items[j - 1]\n self._items[key] = value\n self._size += 1\n self.incModCount()",
"def test_bit_set_bit_bit_size_too_large(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 16, 1, value, None)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_shrink_only_does_not_allow_grow(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 10, resize_flags=aerospike.BIT_RESIZE_SHRINK_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_grow_only_does_not_allow_shrink(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 1, resize_flags=aerospike.BIT_RESIZE_GROW_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def bst_insert(sizes):\n tree = rbTree_main.BinarySearchTree();\n for i in range(sizes):\n tree.insert(random.random())",
"def insert(self, key, value): #hidden\n # return the bin number of table\n index = self.hash_function(key)\n # do not insert empty string\n if index != -1:\n # insert item in empty bucket\n if self.table[index] is None:\n self.table[index] = HashNode(key, value)\n self.size += 1\n # if the key is present, update value\n elif self.table[index].key == key:\n self.table[index].value = value\n # resolve conflicts\n else:\n index = self.quadratic_probe(key)\n if self.table[index] is None:\n self.table[index] = HashNode(key, value)\n self.size += 1\n # if the key is present, update value\n elif self.table[index].key == key:\n self.table[index].value = value\n # grow size\n load_factor = self.size / self.capacity\n if load_factor > 0.75:\n self.grow()",
"def insert(self, key, value):\r\n hash_val = Hash(key, value)\r\n self.hash_table[self.horner_hash(key)] = hash_val\r\n self.num_items += 1\r\n\r\n if self.get_load_factor() > 0.5:\r\n prev = HashTable(self.table_size)\r\n prev.num_items = self.num_items\r\n prev.hash_table = self.hash_table\r\n prev.table_size = self.table_size\r\n\r\n self.table_size = self.table_size * 2 + 1\r\n self.num_items = 0\r\n self.hash_table = [None] * self.table_size\r\n\r\n for i in range(prev.table_size):\r\n if prev.hash_table[i] is not None:\r\n self.insert(prev.hash_table[i].key, prev.hash_table[i].value)",
"def insert(self, value):\n bucketNum = self.__hash(value)\n self.__buckets[bucketNum].append(value)",
"def insert_int(self, value, size=4, location=None, overwrite=False):\n self.insert_ints([value], size=size, location=location, overwrite=overwrite)",
"def insert(self, key, value):\r\n self._data.append(self._Item(key, value))\r\n self._upheap(len(self._data) - 1) # upheap newly added position\r",
"def _insert_op(self, op):",
"def insert(self, key: K, value: V) -> None:\n if key in self.__key_map__:\n self.remove(key)\n\n entry = (value, next(self.counter), key)\n self.__key_map__[key] = entry\n\n heapq.heappush(self.queue, entry)",
"def insert(self, item):\n for h_num in xrange(self.k):\n val = self.hash_value(item, h_num)\n self.arr[val] = True",
"def test_bit_add_overflow_saturate(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_SATURATE, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result"
] | [
"0.76244575",
"0.63715374",
"0.60700357",
"0.5990376",
"0.586666",
"0.5862846",
"0.5861409",
"0.57503796",
"0.5734948",
"0.56520027",
"0.55897146",
"0.5559917",
"0.5514823",
"0.5505976",
"0.54876494",
"0.5475704",
"0.5434488",
"0.54248905",
"0.5423369",
"0.5398629",
"0.53895605",
"0.5363308",
"0.53563166",
"0.5348383",
"0.53364193",
"0.5328842",
"0.53263444",
"0.52548206",
"0.52424437",
"0.52419525"
] | 0.76956564 | 0 |
Perform a bitwise insert op with a non existent bin. | def test_bit_insert_nonexistent_bin_name(self):
value = bytearray([3])
ops = [bitwise_operations.bit_insert("bad_name", 0, 1, value, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([3])
assert bins["bad_name"] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_insert(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 1 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_offset_out_of_range(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 9, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5 + [0] * 4 + [3] * 1)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_insert_multiple_bytes_with_offset(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 2, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 2 + [3] * 3 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_multiple_bytes(self):\n value = bytearray([3] * 3)\n ops = [bitwise_operations.bit_insert(self.test_bin_zeroes, 0, 3, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 3 + [0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_insert_bad_arg_type(self):\n value = bytearray([3])\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 1.5, value, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_insert_value_byte_size_smaller_than_value(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 2, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 2 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def _insert_op(self, op):",
"def test_bit_insert_value_byte_size_too_large(self):\n value = bytearray([3] * 6)\n ops = [bitwise_operations.bit_insert(self.five_255_bin, 0, 6, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([3] * 6 + [255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def insert(self, n, bin_):\n pred_pos = self.predecessor(n, bin_[0], bin_[1])\n insert_pos = pred_pos + 1 if pred_pos is not None else bin_[0]\n self.nums.insert(insert_pos, n)",
"def test_bit_add_bad_bin_name(self):\n ops = [bitwise_operations.bit_add(\"bad_name\", 8, 16, 65535, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_add_inbetween_bytes(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_add_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_insert_will_not_duplicate_value(bst_balanced):\n bst_balanced.insert(6)\n assert bst_balanced.size() == 6",
"def test_bit_set_bit_bad_bin_name(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(\"bad_name\", 0, 8, 1, value, None)]\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_invalid_bin_name(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_pos_operate_with_nonexistent_bin(self):\n key = (\"test\", \"demo\", 1)\n llist = [\n {\"op\": aerospike.OPERATOR_APPEND, \"bin\": \"addr\", \"val\": \"pune\"},\n {\"op\": aerospike.OPERATOR_READ, \"bin\": \"addr\"},\n ]\n key, _, bins = self.as_connection.operate(key, llist)\n\n assert bins == {\"addr\": \"pune\"}",
"def insert_before(self, insert_pos_inst):\n basic_block = insert_pos_inst.basic_block\n if basic_block is None:\n raise IRError('Instruction is not in basic block')\n idx = basic_block.insts.index(insert_pos_inst)\n self.basic_block = basic_block\n basic_block.insts.insert(idx, self)",
"def insert(self, val: int) -> bool:",
"def place(arr, mask, vals):\n return _insert(arr, mask, vals)",
"def test_insert_adds_value_to_tree(bst_balanced):\n bst_balanced.insert(15)\n assert bst_balanced.contains(15) is True\n assert bst_balanced.search(15).val == 15",
"def test_binarytree_insert_exists(empty_list):\n assert empty_list.insert(42)",
"def test_bit_add_simple(self):\n ops = [bitwise_operations.bit_add(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([2] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def add_binary(a, b):\n return bin(a + b)[2:]",
"def test_pos_operate_increment_nonexistent_bin(self):\n key = (\"test\", \"demo\", 1)\n llist = [{\"op\": aerospike.OPERATOR_INCR, \"bin\": \"my_age\", \"val\": 5}]\n\n self.as_connection.operate(key, llist)\n\n (key, _, bins) = self.as_connection.get(key)\n\n assert bins == {\"my_age\": 5, \"age\": 1, \"name\": \"name1\"}",
"def test_bit_add_bit_size_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_update_only_prevents_create(self):\n bit_policy = {\"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY}\n ops = [bitwise_operations.bit_resize(\"new_binname\", 10, policy=bit_policy)]\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_index_out_of_range(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 41, 8, 1, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_inbetween_bytes(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 4, 8, 1, value, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([15] * 1 + [240] * 1 + [0] * 3)\n assert bins[self.test_bin_zeroes] == expected_result",
"def _insert_into_clean(self, entry):\n i = entry.hash\n new_entry = self.table[i]\n while new_entry.key is not None:\n i += self.second_hash(new_entry.key)\n new_entry = self.table[i]\n new_entry.key = entry.key\n new_entry.value = entry.value\n new_entry.hash = entry.hash\n self.used += 1\n self.filled += 1",
"def test_bit_add_overflow_wrap(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result"
] | [
"0.7160326",
"0.67176193",
"0.65476626",
"0.65370536",
"0.64729404",
"0.6287796",
"0.62124634",
"0.60395765",
"0.6007725",
"0.6004442",
"0.56489205",
"0.5540966",
"0.5484066",
"0.54520464",
"0.5378718",
"0.53578687",
"0.5348499",
"0.5330858",
"0.5326471",
"0.52357227",
"0.5222345",
"0.5207168",
"0.5200922",
"0.5200225",
"0.51746666",
"0.5174124",
"0.51487875",
"0.5148568",
"0.51470584",
"0.5138405"
] | 0.7217372 | 0 |
Perform a bitwise lscan op. | def test_bit_lscan(self):
value = True
ops = [bitwise_operations.bit_lscan(self.count_bin, 32, 8, value)]
expected_value = 6
_, _, result = self.as_connection.operate(self.test_key, ops)
assert result[self.count_bin] == expected_value | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_lscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 7, 8, value)]\n\n expected_value = 1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.test_bin_ones] == expected_value",
"def test_bit_lscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_lscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_lscan_value_not_found(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.five_255_bin, 0, 40, value)]\n\n expected_value = -1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.five_255_bin] == expected_value",
"def scan(self, mask):",
"def test_bit_lshift_wrap(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 40, 8, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 4 + [0])\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_lshift(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 8, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([8] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_lscan_bad_bin_name(self):\n value = True\n ops = [bitwise_operations.bit_lscan(\"bad_name\", 0, 8, value)]\n\n expected_value = None\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"bad_name\"] == expected_value",
"def bitwise_lshift(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_lshift_op, other)",
"def test_bit_lshift_across_bytes(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 4, 12, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([8] * 2 + [1] * 3)\n assert bins[self.test_bin_ones] == expected_result",
"def rotl(x, count):\n ret = 0\n for i in range(64):\n bit = (x >> i) & 1\n ret |= bit << ((i + count) % 64)\n return ret",
"def test_bit_lshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rscan(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 32, 8, value)]\n\n expected_value = 7\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_lshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def lsel(self, l: int) -> Status:\n result = self._read_inline(f\"lsel({l})\")\n return Status(result)",
"def test_bit_lshift_bad_arg(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 1.5, 8, 1, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def magic_ll(self, parameter_s=''):\n self.magic_lc(parameter_s+' | grep ^l')",
"def test_bit_rscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.count_bin, 4, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_rscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __LFSR(self, key: bytearray) -> int:\n x = key.pop()\n out = x ^ key[254] ^ key[244]\n key.append(out)\n return out",
"def gfmul(x, y):\n ret = 0\n for i in range(64):\n if (x & (1 << i)) != 0:\n ret ^= y << i\n return ret",
"def scanl(func, start, itr):\n if not callable(func):\n raise TypeError(\"First argument to scanl must be callable\")\n itr = iter(itr)\n\n return _scanl(func, start, itr)",
"def bitscan_forward(bitboard):\n i = 1\n while not (bitboard >> np.uint64(i)) % 2:\n i += 1\n return i",
"def test_bit_rscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def compute_lsp(pattern, patt_len, lps):\n pointer = 0\n lps[0] = 0\n i = 1\n\n while i < patt_len:\n if pattern[i] == pattern[pointer]:\n pointer += 1\n lps[i] = pointer\n i += 1\n else:\n if pointer != 0:\n pointer = lps[pointer - 1]\n else:\n lps[i] = 0\n i += 1",
"def test_bit_lshift_bad_bin_name(self):\n ops = [bitwise_operations.bit_lshift(\"bad_name\", 0, 8, 1, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def lsnext(self, l: int) -> int:\n result = self._read_inline(f\"lsnext({l})\")\n return int(result)",
"def lshift(self, count):\n self._c = self._c[count:] + (bitarray('0') * count)",
"def lrc(data):\n if isinstance(data, str):\n data = data.encode(TERMINAL_DATA_ENCODING)\n elif not isinstance(data, bytes):\n raise TypeError(\"Cannot compute LRC of type {0}. Expect string or bytes.\".format(str(type(data))))\n return reduce(xor, [c for c in data]) if six.PY3 else reduce(xor, [ord(c) for c in data])",
"def lshift(self):\n self.lcd_byte(0x18, LCD_CMD)"
] | [
"0.74451196",
"0.6658104",
"0.66572857",
"0.62291265",
"0.6085733",
"0.59215665",
"0.5744479",
"0.57185316",
"0.56623083",
"0.56226116",
"0.552413",
"0.55202615",
"0.5383747",
"0.53328454",
"0.5293886",
"0.5254218",
"0.52492434",
"0.51787573",
"0.51559234",
"0.51167107",
"0.50911075",
"0.5042593",
"0.50249654",
"0.4963189",
"0.4897211",
"0.487054",
"0.4857722",
"0.4840151",
"0.48371124",
"0.47745103"
] | 0.7567064 | 0 |
Perform a bitwise lscan op with an offset that causes the scan to search multiple bytes. | def test_bit_lscan_across_bytes(self):
value = False
ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 7, 8, value)]
expected_value = 1
_, _, result = self.as_connection.operate(self.test_key, ops)
assert result[self.test_bin_ones] == expected_value | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_lscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_lscan(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 32, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_lscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_lshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_lscan_value_not_found(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.five_255_bin, 0, 40, value)]\n\n expected_value = -1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.five_255_bin] == expected_value",
"def scan(self, mask):",
"def test_bit_lshift_across_bytes(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 4, 12, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([8] * 2 + [1] * 3)\n assert bins[self.test_bin_ones] == expected_result",
"def lsel(self, l: int) -> Status:\n result = self._read_inline(f\"lsel({l})\")\n return Status(result)",
"def rotl(x, count):\n ret = 0\n for i in range(64):\n bit = (x >> i) & 1\n ret |= bit << ((i + count) % 64)\n return ret",
"def test_bit_lshift_wrap(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 40, 8, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 4 + [0])\n assert bins[self.test_bin_ones] == expected_result",
"def compute_lsp(pattern, patt_len, lps):\n pointer = 0\n lps[0] = 0\n i = 1\n\n while i < patt_len:\n if pattern[i] == pattern[pointer]:\n pointer += 1\n lps[i] = pointer\n i += 1\n else:\n if pointer != 0:\n pointer = lps[pointer - 1]\n else:\n lps[i] = 0\n i += 1",
"def test_bit_rscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_lscan_bad_bin_name(self):\n value = True\n ops = [bitwise_operations.bit_lscan(\"bad_name\", 0, 8, value)]\n\n expected_value = None\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"bad_name\"] == expected_value",
"def test_bit_lshift(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 8, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([8] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_lshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def magic_ll(self, parameter_s=''):\n self.magic_lc(parameter_s+' | grep ^l')",
"def bitwise_lshift(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_lshift_op, other)",
"def lshift(self, count):\n self._c = self._c[count:] + (bitarray('0') * count)",
"def lsnext(self, l: int) -> int:\n result = self._read_inline(f\"lsnext({l})\")\n return int(result)",
"def color_indexes_from_lbm_chunk(bytes_lbm_block, cursor=0, verbose=True, must_check=False):\n block_data = []\n cursor = 0\n block_size = list(map(int, bytes_lbm_block[cursor:cursor+4]))\n cursor += 4\n\n block_size = sum([\n byte*(256**offset)\n for byte, offset\n in zip(block_size, range(4))\n ])\n\n if verbose:\n print(\"Taille du bloc : %s.\" % block_size)\n\n block_data += list(map(int, bytes_lbm_block[cursor:cursor+block_size]))\n cursor += block_size\n\n if must_check:\n if cursor != len(bytes_lbm_block):\n msg = \"Taille de bloc indiqué (%s) différente de la taille de bloc réelle (%s).\"\n raise Exception(msg % (cursor, len(bytes_lbm_block)))\n\n color_indexes = []\n while block_data:\n part_header = block_data.pop(0)\n if part_header > 128:\n part_body = block_data.pop(0)\n color_indexes += [ part_body ] * (257-part_header)\n else:\n body_size = part_header + 1\n part_body = block_data[:body_size]\n block_data = block_data[body_size:]\n color_indexes += part_body\n\n if verbose:\n print(\"Nombres de pixels : %s\" % len(color_indexes))\n if len(color_indexes) != 64000:\n print(\"Warning. La taille de l'image devrait être de 64000 pixels (320x200).\")\n\n return color_indexes",
"def scanl(func, start, itr):\n if not callable(func):\n raise TypeError(\"First argument to scanl must be callable\")\n itr = iter(itr)\n\n return _scanl(func, start, itr)",
"def lshift(self):\n self.lcd_byte(0x18, LCD_CMD)",
"def __LFSR(self, key: bytearray) -> int:\n x = key.pop()\n out = x ^ key[254] ^ key[244]\n key.append(out)\n return out",
"def lrc(data):\n if isinstance(data, str):\n data = data.encode(TERMINAL_DATA_ENCODING)\n elif not isinstance(data, bytes):\n raise TypeError(\"Cannot compute LRC of type {0}. Expect string or bytes.\".format(str(type(data))))\n return reduce(xor, [c for c in data]) if six.PY3 else reduce(xor, [ord(c) for c in data])",
"def test_bit_rscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.count_bin, 4, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def get_index_in_permuted(x, L):\n ld4 = L // 4\n return x // ld4 + 4 * (x % ld4)",
"def ldx(self, addr):\n\n val = self.mem.read(addr)\n self.reg.idx = val",
"def _get_straight_bits(self, start, length, direction, skip=()):\n result = 0\n counted = 0\n step = (0, 1) if direction == 'd' else (-1, 0)\n for i in range(length):\n if i in skip:\n start = tuples.add(start, step)\n continue\n result += self._get_bit(start) << counted\n counted += 1\n start = tuples.add(start, step)\n return result",
"def lrs(st):\n\n length, shifts = __lrs(st.root, 0)\n result = [length, []]\n for shift in shifts:\n lrs_string = st.text[shift[0]-length:shift[0]]\n result[1].append((lrs_string, [x-length for x in shift]))\n return result",
"def ASLR(debugger, command, result, internal_dict, debug=True):\n interpreter = debugger.GetCommandInterpreter()\n\n return_obj = lldb.SBCommandReturnObject()\n interpreter.HandleCommand('image list -o', return_obj)\n\n output = return_obj.GetOutput().split(\"\\n\")[0]\n match = re.match(r'.+(0x[0-9a-fA-F]+)', output)\n if debug and match:\n print \"ASLR offset is:\", match.group(1)\n\n return int(match.group(1), 16) if match else None"
] | [
"0.68065566",
"0.66702664",
"0.6243345",
"0.57021254",
"0.55683017",
"0.5430383",
"0.5321488",
"0.5251073",
"0.5233933",
"0.5192475",
"0.5176165",
"0.51449674",
"0.5064992",
"0.50226194",
"0.4990894",
"0.49202585",
"0.49196604",
"0.4917927",
"0.4847523",
"0.48157188",
"0.47725466",
"0.46969572",
"0.46898884",
"0.4615933",
"0.46114767",
"0.46057057",
"0.45889917",
"0.4541286",
"0.453673",
"0.4520104"
] | 0.70847696 | 0 |
Perform a bitwise lscan op with bit_offset outside bitmap.S | def test_bit_lscan_offset_out_of_range(self):
value = True
ops = [bitwise_operations.bit_lscan(self.count_bin, 41, 8, value)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_lscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 7, 8, value)]\n\n expected_value = 1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.test_bin_ones] == expected_value",
"def test_bit_lscan(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 32, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_lscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def scan(self, mask):",
"def test_bit_lscan_value_not_found(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.five_255_bin, 0, 40, value)]\n\n expected_value = -1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.five_255_bin] == expected_value",
"def test_bit_lshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def bitscan_forward(bitboard):\n i = 1\n while not (bitboard >> np.uint64(i)) % 2:\n i += 1\n return i",
"def test_bit_lshift_wrap(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 40, 8, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 4 + [0])\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_lscan_bad_bin_name(self):\n value = True\n ops = [bitwise_operations.bit_lscan(\"bad_name\", 0, 8, value)]\n\n expected_value = None\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"bad_name\"] == expected_value",
"def rotl(x, count):\n ret = 0\n for i in range(64):\n bit = (x >> i) & 1\n ret |= bit << ((i + count) % 64)\n return ret",
"def test_bit_lshift_across_bytes(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 4, 12, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([8] * 2 + [1] * 3)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_lshift(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 8, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([8] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def getInstructionBits(self, offset: int, startbit: int, size: int) -> int:\n ...",
"def color_indexes_from_lbm_chunk(bytes_lbm_block, cursor=0, verbose=True, must_check=False):\n block_data = []\n cursor = 0\n block_size = list(map(int, bytes_lbm_block[cursor:cursor+4]))\n cursor += 4\n\n block_size = sum([\n byte*(256**offset)\n for byte, offset\n in zip(block_size, range(4))\n ])\n\n if verbose:\n print(\"Taille du bloc : %s.\" % block_size)\n\n block_data += list(map(int, bytes_lbm_block[cursor:cursor+block_size]))\n cursor += block_size\n\n if must_check:\n if cursor != len(bytes_lbm_block):\n msg = \"Taille de bloc indiqué (%s) différente de la taille de bloc réelle (%s).\"\n raise Exception(msg % (cursor, len(bytes_lbm_block)))\n\n color_indexes = []\n while block_data:\n part_header = block_data.pop(0)\n if part_header > 128:\n part_body = block_data.pop(0)\n color_indexes += [ part_body ] * (257-part_header)\n else:\n body_size = part_header + 1\n part_body = block_data[:body_size]\n block_data = block_data[body_size:]\n color_indexes += part_body\n\n if verbose:\n print(\"Nombres de pixels : %s\" % len(color_indexes))\n if len(color_indexes) != 64000:\n print(\"Warning. La taille de l'image devrait être de 64000 pixels (320x200).\")\n\n return color_indexes",
"def getBits(data, offset, bits=1):\n mask = ((1 << bits) - 1) << offset\n return (data & mask) >> offset",
"def rle_conversion(bit_data):\n rle, pos = [], 0;\n for bit, group in itertools.groupby(bit_data):\n group_list = list(group);\n if bit: rle.extend([pos, sum(group_list)]);\n pos += len(group_list);\n return rle;",
"def test_bit_get_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 41, 1)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.count_bin, 4, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_lshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_int_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 41, 1, False)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def get_bit_position(x, k):\n\n return x & (1 << k)",
"def getContextBits(self, startbit: int, bitsize: int) -> int:\n ...",
"def test_bit_rscan(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 32, 8, value)]\n\n expected_value = 7\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_rscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def gfmul(x, y):\n ret = 0\n for i in range(64):\n if (x & (1 << i)) != 0:\n ret ^= y << i\n return ret",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def broadcast_offset_param(data):\n return np.array([[data[int(i / 16)][(j + i * 32) % 128]\n for j in range(32)] \n for i in range(32)])",
"def bitrange(index, width, start, end):\n return index >> (width - end) & ((2 ** (end - start)) - 1)",
"def get_mask_offset(mask):\n # use ctypes to truncate the result to a uint32\n cmask = ctypes.c_uint32(mask).value\n return _bruijn32lookup[ctypes.c_uint32((mask & -mask) * 0x077cb531).value >> 27]"
] | [
"0.7298933",
"0.70126724",
"0.6571719",
"0.64918786",
"0.6292112",
"0.5880076",
"0.5796156",
"0.57129705",
"0.5523732",
"0.54938674",
"0.544911",
"0.54301494",
"0.5377849",
"0.5362025",
"0.53573096",
"0.52673286",
"0.5209288",
"0.51707304",
"0.5134745",
"0.5130603",
"0.50981545",
"0.50888103",
"0.5087695",
"0.5069536",
"0.5057071",
"0.5021598",
"0.500064",
"0.49906987",
"0.4962664",
"0.488249"
] | 0.7086252 | 1 |
Perform a bitwise lscan op with bit_size larger than bitmap.S | def test_bit_lscan_bit_size_too_large(self):
value = True
ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 0, 41, value)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_lscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 7, 8, value)]\n\n expected_value = 1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.test_bin_ones] == expected_value",
"def test_bit_lscan(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 32, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_lscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_lshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def scan(self, mask):",
"def test_bit_lscan_value_not_found(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.five_255_bin, 0, 40, value)]\n\n expected_value = -1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.five_255_bin] == expected_value",
"def test_bit_lshift_wrap(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 40, 8, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 4 + [0])\n assert bins[self.test_bin_ones] == expected_result",
"def rotl(x, count):\n ret = 0\n for i in range(64):\n bit = (x >> i) & 1\n ret |= bit << ((i + count) % 64)\n return ret",
"def test_bit_rscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.count_bin, 4, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_lshift_across_bytes(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 4, 12, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([8] * 2 + [1] * 3)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_lshift(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 8, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([8] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def bitscan_forward(bitboard):\n i = 1\n while not (bitboard >> np.uint64(i)) % 2:\n i += 1\n return i",
"def test_bit_rscan(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 32, 8, value)]\n\n expected_value = 7\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def benchmark_select_rle_conversions():\n import kwimage\n import ubelt as ub\n c_mask = kwimage.Mask.random(shape=(256, 256))\n f_mask = c_mask.to_fortran_mask(copy=True)\n\n img = c_mask.data\n\n ti = ub.Timerit(1000, bestof=50, verbose=1)\n\n for timer in ti.reset('img -> encode_run_length(non-binary)'):\n with timer:\n kwimage.encode_run_length(img, binary=False)\n\n for timer in ti.reset('img -> encode_run_length(binary)'):\n with timer:\n kwimage.encode_run_length(img, binary=True)\n\n for timer in ti.reset('c_mask -> to_array_rle'):\n with timer:\n c_mask.to_array_rle()\n\n for timer in ti.reset('c_mask -> to_bytes_rle'):\n with timer:\n c_mask.to_bytes_rle()\n\n for timer in ti.reset('f_mask -> to_array_rle'):\n with timer:\n f_mask.to_array_rle()\n\n for timer in ti.reset('f_mask -> to_bytes_rle'):\n with timer:\n f_mask.to_bytes_rle()",
"def test_bit_lscan_bad_bin_name(self):\n value = True\n ops = [bitwise_operations.bit_lscan(\"bad_name\", 0, 8, value)]\n\n expected_value = None\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"bad_name\"] == expected_value",
"def color_indexes_from_lbm_chunk(bytes_lbm_block, cursor=0, verbose=True, must_check=False):\n block_data = []\n cursor = 0\n block_size = list(map(int, bytes_lbm_block[cursor:cursor+4]))\n cursor += 4\n\n block_size = sum([\n byte*(256**offset)\n for byte, offset\n in zip(block_size, range(4))\n ])\n\n if verbose:\n print(\"Taille du bloc : %s.\" % block_size)\n\n block_data += list(map(int, bytes_lbm_block[cursor:cursor+block_size]))\n cursor += block_size\n\n if must_check:\n if cursor != len(bytes_lbm_block):\n msg = \"Taille de bloc indiqué (%s) différente de la taille de bloc réelle (%s).\"\n raise Exception(msg % (cursor, len(bytes_lbm_block)))\n\n color_indexes = []\n while block_data:\n part_header = block_data.pop(0)\n if part_header > 128:\n part_body = block_data.pop(0)\n color_indexes += [ part_body ] * (257-part_header)\n else:\n body_size = part_header + 1\n part_body = block_data[:body_size]\n block_data = block_data[body_size:]\n color_indexes += part_body\n\n if verbose:\n print(\"Nombres de pixels : %s\" % len(color_indexes))\n if len(color_indexes) != 64000:\n print(\"Warning. La taille de l'image devrait être de 64000 pixels (320x200).\")\n\n return color_indexes",
"def rle_conversion(bit_data):\n rle, pos = [], 0;\n for bit, group in itertools.groupby(bit_data):\n group_list = list(group);\n if bit: rle.extend([pos, sum(group_list)]);\n pos += len(group_list);\n return rle;",
"def getInstructionBits(self, offset: int, startbit: int, size: int) -> int:\n ...",
"def getContextBits(self, startbit: int, bitsize: int) -> int:\n ...",
"def test_bit_rscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_lshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def generate_rle_1bit(source):\n\n current = 0\n count = 0\n # We start with an implicit black pixel, which isn't actually part\n # of the image. The decoder must discard this pixel. This\n # implicit black pixel ensures that there are no 0 counts anywhere\n # in the resulting data.\n next = 0\n while True:\n while current == next:\n count += 1\n try:\n next = source.next()\n except StopIteration:\n yield count\n raise StopIteration\n yield count\n current = next\n count = 0",
"def lps(mask):\n if not mask: return 0\n if not mask & (mask-1): return 1\n lo = int(log2(mask & ~(mask-1))) # least significant set bi\n hi = int(log2(mask)) # most significant set bit \n if s[lo] == s[hi]: return 2 + lps(mask^(1<<lo)^(1<<hi))\n return max(lps(mask^(1<<lo)), lps(mask^(1<<hi)))",
"def _mask_to_rle_pytorch(input_mask: \"torch.Tensor\"):\n # Put in fortran order and flatten height and width\n batch_size, height, width = input_mask.shape\n input_mask = input_mask.permute(0, 2, 1).flatten(1)\n\n # Compute change indices\n diff = input_mask[:, 1:] ^ input_mask[:, :-1]\n change_indices = diff.nonzero()\n\n # Encode run length\n out = []\n for i in range(batch_size):\n cur_idxs = change_indices[change_indices[:, 0] == i, 1] + 1\n btw_idxs = cur_idxs[1:] - cur_idxs[:-1]\n counts = [] if input_mask[i, 0] == 0 else [0]\n counts += [cur_idxs[0].item()] + btw_idxs.tolist() + [height * width - cur_idxs[-1]]\n out.append({\"size\": [height, width], \"counts\": counts})\n return out",
"def test_bit_get_bit_size_too_large(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 0, 41)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def count_set_bits(bitmap):\n bmp = bitmap\n count = 0\n n = 1\n while bmp > 0:\n if bmp & 1:\n count += 1\n bmp = bmp >> 1\n n = n + 1\n return count",
"def bits():\n for d in data:\n for i in [5, 4, 3, 2, 1, 0]:\n yield (d >> i) & 1",
"def test_bit_get_int_bit_size_too_large(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 0, 41, False)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def get_bits(x, k, size, offset=0):\n\n answer = x >> offset\n answer >>= k * size\n return get_least_significant_bits(answer, size)"
] | [
"0.7305252",
"0.7233019",
"0.6309055",
"0.61403173",
"0.60514647",
"0.595394",
"0.59533376",
"0.5549568",
"0.55292",
"0.54765344",
"0.5471686",
"0.546404",
"0.54265046",
"0.54154724",
"0.5364196",
"0.5296248",
"0.52662283",
"0.5188394",
"0.51625985",
"0.51263577",
"0.5118834",
"0.5042718",
"0.5026509",
"0.50186026",
"0.49791473",
"0.49780774",
"0.49466762",
"0.49194348",
"0.49189356",
"0.490581"
] | 0.74964994 | 0 |
Perform a bitwise lshift op with offset > bitmap. | def test_bit_lshift_offset_out_of_range(self):
ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 41, 8, 1, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def bitwise_lshift(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_lshift_op, other)",
"def lshift(self, value):\n return self.clone().lshift_(value)",
"def test_bit_lshift_wrap(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 40, 8, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 4 + [0])\n assert bins[self.test_bin_ones] == expected_result",
"def __lshift__(self, other: Any) -> ColumnOperators:\n return self.operate(lshift, other)",
"def test_bit_lshift_across_bytes(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 4, 12, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([8] * 2 + [1] * 3)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_lshift(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 8, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([8] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def __lshift__(self, other):\r\n # TODO: extend to secret offset\r\n if not isinstance(other, int):\r\n return NotImplemented\r\n\r\n return runtime.mul(self, 1<<other)",
"def lrshift(val, n) -> np.int64:\n return (val % (1 << 64)) >> n",
"def lshift(self, count):\n self._c = self._c[count:] + (bitarray('0') * count)",
"def test_lshift():\n value = 42\n num_a = param.Integer(value=value)\n assert num_a.value == value\n\n new_value = operator.lshift(value, 1)\n num_a.value <<= 1\n assert num_a.value == new_value",
"def lshift(self):\n self.lcd_byte(0x18, LCD_CMD)",
"def test_bit_lshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __lshift__(self, other):\r\n return NotImplemented",
"def leftshift(x, c):\n return x << c",
"def shift_left(self):\n self.pointer = (self.pointer - 1) % len(self.data)",
"def left_shift(key,shift):\n if shift > len(key):\n shift = shift % len(key)\n return key[shift:] + key[:shift]",
"def lshift_(self, value):\n assert isinstance(value, int), \"lshift must take an integer argument.\"\n self.share <<= value\n return self",
"def rotl(x, count):\n ret = 0\n for i in range(64):\n bit = (x >> i) & 1\n ret |= bit << ((i + count) % 64)\n return ret",
"def rel_shift(x, klen=-1):\n x_size = x.shape\n\n x = x.reshape(x_size[1], x_size[0], x_size[2], x_size[3])\n x = x[1:, ...]\n x = x.reshape(x_size[0], x_size[1] - 1, x_size[2], x_size[3])\n # x = x[:, 0:klen, :, :]\n x = torch.index_select(x, 1, torch.arange(klen, device=x.device, dtype=torch.long))\n\n return x",
"def __lshift__(return_spec, argument_spec):\n return return_spec.fam.c_lshift(return_spec, argument_spec)",
"def test_bit_lshift_bad_arg(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 1.5, 8, 1, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def __lshift__(self,fpath):\n raise NotImplemented",
"def _rel_shift(self, xs):\n bs, qlen, klen, n_heads = xs.size()\n xs = xs.permute(0, 3, 2, 1)\n idx = torch.arange(klen, device=xs.device)\n k_idx, q_idx = idx.unsqueeze(0), idx.unsqueeze(1)\n rel_pos_idx = torch.abs(k_idx - q_idx)\n if klen != qlen:\n rel_pos_idx = rel_pos_idx[:, :qlen]\n mask = xs.new_ones(qlen, klen, dtype=torch.bool if torch_12_plus else torch.uint8)\n mask = torch.tril(mask, diagonal=0).transpose(1, 0)\n rel_pos_idx[mask] *= -1\n rel_pos_idx = klen - qlen - rel_pos_idx\n rel_pos_idx[rel_pos_idx < 0] *= -1\n if self.clamp_len > 0:\n rel_pos_idx.clamp_(max=self.clamp_len)\n rel_pos_idx = rel_pos_idx.expand_as(xs)\n x_shift = torch.gather(xs, dim=2, index=rel_pos_idx)\n x_shift = x_shift.permute(0, 3, 2, 1)\n return x_shift",
"def left_shift(lhs, rhs):\n return _make.left_shift(lhs, rhs)",
"def shift(image,shift_x,shift_y):\n return np.roll(np.roll(image,shift_y,axis=0),shift_x,axis=1)",
"def RotL_64(x, N):\n #return (x << np.uint64(N & 63)) | (x >> np.uint64((64-N) & 63))\n return(np.left_shift(x, (N & 63), dtype=np.uint64) |\n np.right_shift(x, ((64-N) & 63), dtype=np.uint64))",
"def roll(x, shift, dim):\n if isinstance(shift, (tuple, list)):\n assert len(shift) == len(dim)\n for s, d in zip(shift, dim):\n x = roll(x, s, d)\n return x\n shift = shift % x.size(dim)\n if shift == 0:\n return x\n left = x.narrow(dim, 0, x.size(dim) - shift)\n right = x.narrow(dim, x.size(dim) - shift, shift)\n return torch.cat((right, left), dim=dim)",
"def roll(x, shift, dim):\n if isinstance(shift, (tuple, list)):\n assert len(shift) == len(dim)\n for s, d in zip(shift, dim):\n x = roll(x, s, d)\n return x\n shift = shift % x.size(dim)\n if shift == 0:\n return x\n left = x.narrow(dim, 0, x.size(dim) - shift)\n right = x.narrow(dim, x.size(dim) - shift, shift)\n return torch.cat((right, left), dim=dim)",
"def roll(x, shift, dim):\n if isinstance(shift, (tuple, list)):\n assert len(shift) == len(dim)\n for s, d in zip(shift, dim):\n x = roll(x, s, d)\n return x\n shift = shift % x.size(dim)\n if shift == 0:\n return x\n left = x.narrow(dim, 0, x.size(dim) - shift)\n right = x.narrow(dim, x.size(dim) - shift, shift)\n return torch.cat((right, left), dim=dim)",
"def roll(x, shift, dim):\n if isinstance(shift, (tuple, list)):\n assert len(shift) == len(dim)\n for s, d in zip(shift, dim):\n x = roll(x, s, d)\n return x\n shift = shift % x.size(dim)\n if shift == 0:\n return x\n left = x.narrow(dim, 0, x.size(dim) - shift)\n right = x.narrow(dim, x.size(dim) - shift, shift)\n return torch.cat((right, left), dim=dim)"
] | [
"0.69308263",
"0.66388756",
"0.65359557",
"0.6450406",
"0.6376182",
"0.63319093",
"0.6328476",
"0.62932926",
"0.6225093",
"0.61923605",
"0.6165442",
"0.6009935",
"0.59374416",
"0.59149414",
"0.590938",
"0.5865252",
"0.5850488",
"0.5823703",
"0.5793596",
"0.57894117",
"0.5678299",
"0.56507105",
"0.5634325",
"0.5625966",
"0.56207883",
"0.5599706",
"0.5580364",
"0.5580364",
"0.5580364",
"0.5580364"
] | 0.667068 | 1 |
Perform a bitwise lshift op with bit_size > bitmap. | def test_bit_lshift_bit_size_too_large(self):
ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 41, 1, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_lshift_wrap(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 40, 8, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 4 + [0])\n assert bins[self.test_bin_ones] == expected_result",
"def bitwise_lshift(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_lshift_op, other)",
"def test_bit_lshift(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 8, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([8] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_lshift_across_bytes(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 4, 12, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([8] * 2 + [1] * 3)\n assert bins[self.test_bin_ones] == expected_result",
"def lshift(self, value):\n return self.clone().lshift_(value)",
"def lshift(self, count):\n self._c = self._c[count:] + (bitarray('0') * count)",
"def lrshift(val, n) -> np.int64:\n return (val % (1 << 64)) >> n",
"def __lshift__(self, other):\r\n # TODO: extend to secret offset\r\n if not isinstance(other, int):\r\n return NotImplemented\r\n\r\n return runtime.mul(self, 1<<other)",
"def test_bit_lshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def rotl(x, count):\n ret = 0\n for i in range(64):\n bit = (x >> i) & 1\n ret |= bit << ((i + count) % 64)\n return ret",
"def __lshift__(self, other: Any) -> ColumnOperators:\n return self.operate(lshift, other)",
"def shift_left_bit_length(x: int) -> int:\n return 1 << (x - 1).bit_length()",
"def test_lshift():\n value = 42\n num_a = param.Integer(value=value)\n assert num_a.value == value\n\n new_value = operator.lshift(value, 1)\n num_a.value <<= 1\n assert num_a.value == new_value",
"def __lshift__(self, other):\r\n return NotImplemented",
"def lshift_(self, value):\n assert isinstance(value, int), \"lshift must take an integer argument.\"\n self.share <<= value\n return self",
"def test_bit_rshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def rshift(val, n):\n return (val % 0x100000000) >> n",
"def rshift(val, n):\n return (val % 0x100000000) >> n",
"def leftshift(x, c):\n return x << c",
"def test_bit_lshift_bad_arg(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 1.5, 8, 1, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def rel_shift(x, klen=-1):\n x_size = x.shape\n\n x = x.reshape(x_size[1], x_size[0], x_size[2], x_size[3])\n x = x[1:, ...]\n x = x.reshape(x_size[0], x_size[1] - 1, x_size[2], x_size[3])\n # x = x[:, 0:klen, :, :]\n x = torch.index_select(x, 1, torch.arange(klen, device=x.device, dtype=torch.long))\n\n return x",
"def lshift(self):\n self.lcd_byte(0x18, LCD_CMD)",
"def circular_left_shift(bits, numberofbits):\n shiftedbits = bits[numberofbits:] + bits[:numberofbits]\n return shiftedbits",
"def test_bit_lscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def shift_bits(x, k):\n if (k >= 0):\n return x << k\n else:\n return x >> -k",
"def RotL_64(x, N):\n #return (x << np.uint64(N & 63)) | (x >> np.uint64((64-N) & 63))\n return(np.left_shift(x, (N & 63), dtype=np.uint64) |\n np.right_shift(x, ((64-N) & 63), dtype=np.uint64))",
"def rshift(val: int, n: int) -> int:\n return (val % 0x100000000) >> n",
"def shift_left(self):\n self.pointer = (self.pointer - 1) % len(self.data)",
"def left_shift(key,shift):\n if shift > len(key):\n shift = shift % len(key)\n return key[shift:] + key[:shift]",
"def test_bit_lscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 7, 8, value)]\n\n expected_value = 1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.test_bin_ones] == expected_value"
] | [
"0.6950515",
"0.6931721",
"0.6767711",
"0.67303616",
"0.6553696",
"0.64958674",
"0.6486794",
"0.6405344",
"0.6370063",
"0.6367465",
"0.61931336",
"0.61865187",
"0.6111606",
"0.59819406",
"0.5948448",
"0.5942128",
"0.59374654",
"0.59374654",
"0.5933737",
"0.5898842",
"0.58755004",
"0.5874804",
"0.58700794",
"0.5858171",
"0.58382",
"0.57934326",
"0.57535744",
"0.5739089",
"0.5695996",
"0.56576073"
] | 0.7226745 | 0 |
Perform a bitwise not op with a bit_size > bitmap. | def test_bit_not_bit_size_too_large(self):
ops = [bitwise_operations.bit_not(self.five_255_bin, 0, 41, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def bitwise_not(data):\n return _make.bitwise_not(data)",
"def NOT(bmp):\n\n maxX, maxY = size = bmp.size()\n result = bitmap(size)\n for x in range(maxX):\n for y in range(maxY):\n result.set(x,y, not bmp.get(x,y))\n return result",
"def test_bit_not_small_bit_size(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 5, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([248] + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_not(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 0, 40, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def not_(bits: int) -> int:\n # The `& ALL_` is necessary so python doesn't treat bits as 2's compliment\n return ~bits & ALL_",
"def bitwise_not(self) -> ColumnOperators:\n\n return self.operate(bitwise_not_op)",
"def __ne__(*args, **kwargs):\n return _gdi_.Bitmap___ne__(*args, **kwargs)",
"def test_bit_not_offset_out_of_range(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 41, 8, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def unset_bit(x, k):\n\n return x & ~(1 << k)",
"def test_bit_remove_byte_size_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 0, 6, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def bitwise_not(self, destination):\n value = bytearray()\n\n value.append(0xf7) # F7 /2 \tNOT r/m32\n rm = get_register_encoding(destination)\n reg = 2 # F7 /2 \tNOT r/m32\n # ModR_byte encoded operands ( ModR/M Byte) MOD 11, RM source and\n # REG destination\n\n mod = 0b11\n modr_byte = (mod << 6) + (reg << 3) + (rm << 0)\n value.append(modr_byte)\n\n return value",
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def graph_exclude_bits(self, targ_row=None, targ_col=None):\n self.bitcell_array.graph_exclude_bits(targ_row, targ_col)",
"def test_bit_not_bad_arg(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 2.7, 8, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def logical_not(data):\n return _make.logical_not(data)",
"def convert_logical_not(g, op, block):\n\n ipt0 = g.get_node(op.input(\"X\")[0])\n op_func = get_relay_op(op.type)\n out = op_func(ipt0)\n g.add_node(op.output(\"Out\")[0], out)",
"def test_bit_subtract_bit_size_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def clear_exclude_bits(self):\n self.bitcell_array.init_graph_params()",
"def instruction_not(self, register, value):\n if Vm.is_register(value):\n value = self.get_register(value)\n\n # do the inverse and flip bit 16\n self.set_register(register, ~value % MAX_INT)",
"def test_bit_xor_bit_size_too_large(self):\n value = bytearray([8] * 6)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 41, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __invert__(self):\n return BitBoard(~self.num)",
"def logical_not(x, f=None):\n return _cur_framework(x, f=f).logical_not(x)",
"def test_bit_remove_offset_out_of_range(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def ConvertToDisabled(*args, **kwargs):\n return _gdi_.Bitmap_ConvertToDisabled(*args, **kwargs)",
"def convert_logical_not(node, **kwargs):\n return create_basic_op_node('Not', node, kwargs)",
"def _logical_not(x):\n x_ = _static_value(x)\n if x_ is None:\n return math_ops.logical_not(x)\n return constant_op.constant(np.logical_not(x_))",
"def test_bit_remove_randnumbytes_randoffset(self):\n offset = random.randint(0, 4)\n num_bytes = random.randint(1, (5 - offset))\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, offset, num_bytes, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * (5 - num_bytes))\n # should have removed num_bytes 0s",
"def unset_dq_bits(value, okbits=32+64+512, verbose=False):\n bin_bits = np.binary_repr(okbits)\n n = len(bin_bits)\n for i in range(n):\n if bin_bits[-(i+1)] == '1':\n if verbose:\n print(2**i)\n \n value -= (value & 2**i)\n \n return value",
"def cnot(control: QubitInput, target: QubitInput) -> Instruction:\n return Instruction(CNot(), target=[control, target])",
"def clear_bit(num, i):\n return num & ~(1 << i)"
] | [
"0.7226076",
"0.72110623",
"0.70213264",
"0.7011794",
"0.6715211",
"0.6617093",
"0.62654257",
"0.62304515",
"0.62099355",
"0.6074832",
"0.60745364",
"0.6057515",
"0.605546",
"0.6027605",
"0.59840214",
"0.58479655",
"0.5844934",
"0.5838357",
"0.5771804",
"0.57580274",
"0.56813323",
"0.5654953",
"0.564741",
"0.5610486",
"0.560203",
"0.5589801",
"0.558897",
"0.5585396",
"0.5558429",
"0.55423456"
] | 0.7249606 | 0 |
Perform a bitwise or op on multiple bytes. | def test_bit_or_multiple_bytes(self):
value = bytearray([8] * 5)
ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 40, 5, value, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([9] * 5)
assert bins[self.test_bin_ones] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def bitwise_or(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] | self.registers[register[1]])\n logger.info(\"Bitwise OR on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def test_bit_or(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([9] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def bitwise_or(lhs, rhs):\n return _make.bitwise_or(lhs, rhs)",
"def bitwise_or(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_or_op, other)",
"def test_bit_or_multiple_bytes_value_unchanged(self):\n value = bytearray([255])\n ops = [bitwise_operations.bit_or(self.five_255_bin, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def instruction_or(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n self.set_register(register, (a | b) % MAX_INT)",
"def convert_broadcast_logical_or(node, **kwargs):\n return create_basic_op_node('Or', node, kwargs)",
"def test_bit_or_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def __or__(self, other):\n a, b = Trits.match_length(self, other)\n return Trits([x | y for x, y in zip(a, b)])",
"def test_bit_xor_multiple_bytes(self):\n value = bytearray([8] * 5)\n ops = [bitwise_operations.bit_xor(self.five_255_bin, 0, 40, 5, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([247] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def distribute_and_over_or(s):\n if s.op == '|':\n s = associate('|', s.args)\n if s.op != '|':\n return distribute_and_over_or(s)\n if len(s.args) == 0:\n return FALSE\n if len(s.args) == 1:\n return distribute_and_over_or(s.args[0])\n conj = find_if((lambda d: d.op == '&'), s.args)\n if not conj:\n return s\n others = [a for a in s.args if a is not conj]\n rest = associate('|', others)\n return associate('&', [distribute_and_over_or(c|rest)\n for c in conj.args])\n elif s.op == '&':\n return associate('&', map(distribute_and_over_or, s.args))\n else:\n return s",
"def test_bit_or_bit_size_too_large(self):\n value = bytearray([8] * 6)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 41, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __or__(self, other):\n return self.fam.c_binop('or', self, other)",
"def test_bit_or_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def or_(a, b):",
"def __or__(self, other):\n return BitBoard(self.num | other.num)",
"def bitwise_or(self, source, destination):\n value = bytearray()\n\n value.append(0x09) # OR r/m32, r32\n rm = get_register_encoding(destination)\n reg = get_register_encoding(source)\n # ModR_byte encoded operands ( ModR/M Byte) MOD 11, RM source and\n # REG destination\n\n mod = 0b11\n modr_byte = (mod << 6) + (reg << 3) + (rm << 0)\n value.append(modr_byte)\n\n return value",
"def test_bit_and_multiple_bytes(self):\n value = bytearray()\n value.append(1)\n value.append(1)\n value.append(1)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 8, 17, 3, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 1 + [1] * 2 + [127] * 1 + [255] * 1)\n assert bins[self.five_255_bin] == expected_result",
"def OR(self, values: pdarray) -> Tuple[Union[pdarray, List[Union[pdarray, Strings]]], pdarray]:\n if values.dtype not in [akint64, akuint64, bigint]:\n raise TypeError(\"OR is only supported for pdarrays of dtype int64, uint64, or bigint\")\n\n return self.aggregate(values, \"or\") # type: ignore",
"def OR(r, s):\n return lambda l, i: r(l, i) or s(l, i)",
"def test_or_multichain(self) -> None:\n err: Result[int, int] = Err(5)\n assert err.or_(Err(6)).or_(Err(7)).or_(Ok(8)) == Ok(8)",
"def tuple_operation(a: list, b: list, op: str) -> list:\n o = []\n for i in range(0, 3):\n if op == \"xor\":\n o.append(a[i] ^ b[i])\n elif op == \"and\":\n o.append(a[i] & b[i])\n elif op == \"or\":\n o.append(a[i] | b[i])\n else:\n raise RuntimeError('Unknown operation')\n return o[0], o[1], o[2]",
"def or_list(conditionList):\n return functools.reduce(numpy.logical_or, conditionList)",
"def or_(*args, **kwargs):\n ...",
"def bXor(byte_string_1,byte_string_2):\n return bytes([b1 ^ b2 for b1, b2 in zip(byte_string_1, byte_string_2)])",
"def or_filter(self, filters: List[Union[Tuple, BinaryExpression]]) -> B[B, E]:\n pass",
"def logical_or(lhs, rhs):\n return _make.logical_or(lhs, rhs)",
"def _or(cls, arg1, arg2):\n return arg1 or arg2",
"def join_bits(byteseq) -> int:\n return reduce(lambda acc, bit: (acc << 1) | int(bit), byteseq)",
"def xor(data1=None, data2=None):\n\n return bytearray(a ^ b for a, b in zip(*map(bytearray, [data1, data2])))"
] | [
"0.7118076",
"0.6908915",
"0.68121326",
"0.67484117",
"0.6612568",
"0.64334434",
"0.63509226",
"0.62192816",
"0.61630046",
"0.61462665",
"0.6096318",
"0.60574114",
"0.6025009",
"0.6018953",
"0.5995515",
"0.5988682",
"0.59162784",
"0.5895464",
"0.58875316",
"0.586352",
"0.58144605",
"0.5791749",
"0.57569814",
"0.57448345",
"0.5724732",
"0.5716791",
"0.57152104",
"0.5704699",
"0.5700045",
"0.5693531"
] | 0.7336967 | 0 |
Perform a bitwise or op with bit_offset > bitmap. | def test_bit_or_bit_offset_out_of_range(self):
value = bytearray()
value.append(8)
ops = [bitwise_operations.bit_or(self.test_bin_ones, 41, 8, 1, value, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_or(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([9] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def bitwise_or(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] | self.registers[register[1]])\n logger.info(\"Bitwise OR on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def bitwise_or(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_or_op, other)",
"def __or__(self, other):\n return BitBoard(self.num | other.num)",
"def bitwise_or(lhs, rhs):\n return _make.bitwise_or(lhs, rhs)",
"def convert_broadcast_logical_or(node, **kwargs):\n return create_basic_op_node('Or', node, kwargs)",
"def instruction_or(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n self.set_register(register, (a | b) % MAX_INT)",
"def test_bit_or_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_or_bit_size_too_large(self):\n value = bytearray([8] * 6)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 41, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_or_multiple_bytes(self):\n value = bytearray([8] * 5)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 40, 5, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([9] * 5)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_and_offset_out_of_range(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __or__(self, other):\n return self.fam.c_binop('or', self, other)",
"def binary_or(binary1, binary2):\n if binary1.shape == binary2.shape:\n binary = np.where(np.logical_or(binary1,binary2)==True, 1., 0.)\n return binary\n else:\n return None",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def _orReg(address, mask):\n _setReg(address, _getReg(address)|mask)",
"def test_bit_or_multiple_bytes_value_unchanged(self):\n value = bytearray([255])\n ops = [bitwise_operations.bit_or(self.five_255_bin, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_xor_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_or_bad_arg(self):\n value = 1\n ops = [bitwise_operations.bit_or(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 41, 1)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def logical_or(x1, x2, f=None):\n return _cur_framework(x1, f=f).logical_or(x1, x2)",
"def visit_or(self, left_result: T, right_result: T) -> T:",
"def logical_or(lhs, rhs):\n return _make.logical_or(lhs, rhs)",
"def boolean(operation, bitmaps):\n\n maxX, maxY = size = bitmaps[0].size()\n result = bitmap(size)\n for x in range(maxX):\n for y in range(maxY):\n pixel = bitmaps[0].get(x,y)\n for b in bitmaps[1:]:\n pixel = apply(operation, (pixel, b.get(x,y)))\n result.set(x,y,pixel)\n return result",
"def bitwise_or(self, source, destination):\n value = bytearray()\n\n value.append(0x09) # OR r/m32, r32\n rm = get_register_encoding(destination)\n reg = get_register_encoding(source)\n # ModR_byte encoded operands ( ModR/M Byte) MOD 11, RM source and\n # REG destination\n\n mod = 0b11\n modr_byte = (mod << 6) + (reg << 3) + (rm << 0)\n value.append(modr_byte)\n\n return value",
"def __or__(self, other):\n return self._operation_or(other)",
"def RewriteOR(self, left, right):\n return None",
"def __or__(self, other):\n a, b = Trits.match_length(self, other)\n return Trits([x | y for x, y in zip(a, b)])",
"def or_(a, b):",
"def _operation_or(self, other):\n self._check_items(other)\n if self._active_procs is not None:\n raise DontCallWhenIterRunError('Do not call the operation in iter_run loop.')\n return ReadingSet(self._set | self._get_other_set(other))",
"def __or__(self, other):\n return MyCustomNumber(self.value | other.value)"
] | [
"0.6729167",
"0.6678208",
"0.65645045",
"0.6495425",
"0.6474674",
"0.64089435",
"0.61538225",
"0.61365926",
"0.6038137",
"0.59736896",
"0.5905584",
"0.5881746",
"0.57951003",
"0.5723682",
"0.570876",
"0.5666415",
"0.56518066",
"0.5618289",
"0.55157775",
"0.54992855",
"0.54678226",
"0.54569036",
"0.54547787",
"0.5452247",
"0.5402494",
"0.5384208",
"0.5374889",
"0.5372757",
"0.5356988",
"0.5347595"
] | 0.6939254 | 0 |
Perform a bitwise or op with bit_size > value. | def test_bit_or_bit_size_larger_than_value(self):
value = bytearray()
value.append(8)
ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 9, 1, value, None)]
with pytest.raises(e.InvalidRequest):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_or_bit_size_too_large(self):\n value = bytearray([8] * 6)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 41, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_or_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_or(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([9] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def bitwise_or(lhs, rhs):\n return _make.bitwise_or(lhs, rhs)",
"def test_bit_and_offset_value_byte_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_or_multiple_bytes(self):\n value = bytearray([8] * 5)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 40, 5, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([9] * 5)\n assert bins[self.test_bin_ones] == expected_result",
"def __or__(self, other):\n return BitBoard(self.num | other.num)",
"def test_bit_or_multiple_bytes_value_unchanged(self):\n value = bytearray([255])\n ops = [bitwise_operations.bit_or(self.five_255_bin, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def bitwise_or(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] | self.registers[register[1]])\n logger.info(\"Bitwise OR on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def test_bit_xor_bit_size_too_large(self):\n value = bytearray([8] * 6)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 41, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def bitwise_or(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_or_op, other)",
"def __or__(self, other):\n a, b = Trits.match_length(self, other)\n return Trits([x | y for x, y in zip(a, b)])",
"def test_bit_set_bit_value_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 48, 6, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __or__(self, other):\n\t\tif isinstance(other, int):\n\t\t\treturn self.value | other\n\t\telif type(self) is type(other):\n\t\t\treturn self.value | other.value",
"def test_bit_or_bad_arg(self):\n value = 1\n ops = [bitwise_operations.bit_or(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __or__(self, other):\n return MyCustomNumber(self.value | other.value)",
"def ROR(self, value):\n carry = value & 0b1\n result = ((value >> 1) & 0b01111111) | (0b10000000 if self.reg.C else 0)\n self.reg.C = carry\n self.reg.N = result >> 7\n self.reg.Z = result == 0\n return result",
"def test_bit_set_bit_bit_size_too_large(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 16, 1, value, None)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def instruction_or(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n self.set_register(register, (a | b) % MAX_INT)",
"def test_bit_get_bit_size_too_large(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 0, 41)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __or__(self, other):\n return self.fam.c_binop('or', self, other)",
"def convert_broadcast_logical_or(node, **kwargs):\n return create_basic_op_node('Or', node, kwargs)",
"def test_bit_and_offset_out_of_range(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def ORA(self, value):\n result = self.reg.A | value\n self.reg.N = result >> 7\n self.reg.Z = result == 0\n self.reg.A = result",
"def getTwosComplement(raw_val, length):\n val = raw_val\n if raw_val & (1 << (length - 1)):\n val = raw_val - (1 << length)\n return val",
"def test_bit_not_bit_size_too_large(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 0, 41, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def twos_comp(val, num_bits):\n if ((val & (1 << (num_bits - 1))) != 0):\n val = val - (1 << num_bits)\n return val"
] | [
"0.7268937",
"0.64769953",
"0.6328302",
"0.61380446",
"0.6119461",
"0.60546505",
"0.60256964",
"0.5878146",
"0.58711094",
"0.58374584",
"0.5796204",
"0.57682717",
"0.57471216",
"0.57353663",
"0.5596316",
"0.55628544",
"0.5561486",
"0.5496804",
"0.54590476",
"0.5422026",
"0.5418747",
"0.5334116",
"0.5329933",
"0.53294986",
"0.5324776",
"0.5297148",
"0.5296299",
"0.52938056",
"0.52300245",
"0.52243537"
] | 0.7830411 | 0 |
Perform a bitwise or op with bit_size > bitmap. | def test_bit_or_bit_size_too_large(self):
value = bytearray([8] * 6)
ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 41, 6, value, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_or_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_or(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([9] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def bitwise_or(lhs, rhs):\n return _make.bitwise_or(lhs, rhs)",
"def __or__(self, other):\n return BitBoard(self.num | other.num)",
"def bitwise_or(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_or_op, other)",
"def bitwise_or(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] | self.registers[register[1]])\n logger.info(\"Bitwise OR on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def test_bit_or_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def convert_broadcast_logical_or(node, **kwargs):\n return create_basic_op_node('Or', node, kwargs)",
"def test_bit_or_multiple_bytes(self):\n value = bytearray([8] * 5)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 40, 5, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([9] * 5)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_or_multiple_bytes_value_unchanged(self):\n value = bytearray([255])\n ops = [bitwise_operations.bit_or(self.five_255_bin, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def instruction_or(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n self.set_register(register, (a | b) % MAX_INT)",
"def test_bit_xor_bit_size_too_large(self):\n value = bytearray([8] * 6)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 41, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def binary_or(binary1, binary2):\n if binary1.shape == binary2.shape:\n binary = np.where(np.logical_or(binary1,binary2)==True, 1., 0.)\n return binary\n else:\n return None",
"def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def __or__(self, other):\n return self.fam.c_binop('or', self, other)",
"def boolean(operation, bitmaps):\n\n maxX, maxY = size = bitmaps[0].size()\n result = bitmap(size)\n for x in range(maxX):\n for y in range(maxY):\n pixel = bitmaps[0].get(x,y)\n for b in bitmaps[1:]:\n pixel = apply(operation, (pixel, b.get(x,y)))\n result.set(x,y,pixel)\n return result",
"def __or__(self, other):\n a, b = Trits.match_length(self, other)\n return Trits([x | y for x, y in zip(a, b)])",
"def test_bit_or_bad_arg(self):\n value = 1\n ops = [bitwise_operations.bit_or(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_value_byte_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def orbits(self, rep=False):\n return _orbits(self._degree, self._generators)",
"def logical_or(lhs, rhs):\n return _make.logical_or(lhs, rhs)",
"def test_bit_not_bit_size_too_large(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 0, 41, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_bit_size_too_large(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 0, 41)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def visit_or(self, left_result: T, right_result: T) -> T:",
"def bits_apply(op, n):\n return verts_to_bits(op[v] for v in bits_to_verts(n))",
"def test_bit_rshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def logical_or(x1, x2, f=None):\n return _cur_framework(x1, f=f).logical_or(x1, x2)",
"def test_degrade_widemask_or(self):\n\n nside_coverage = 32\n nside_map = 256\n nside_map2 = 64\n sparse_map = healsparse.HealSparseMap.make_empty(nside_coverage, nside_map,\n WIDE_MASK, wide_mask_maxbits=7)\n sparse_map_or = healsparse.HealSparseMap.make_empty(nside_coverage, nside_map2,\n WIDE_MASK, wide_mask_maxbits=7)\n # Fill some pixels in the \"high-resolution\" map\n pixel = np.arange(4000, 8000)\n sparse_map.set_bits_pix(pixel, [4])\n\n # Check which pixels will be full in the \"low-resolution\" map and fill them\n pixel2 = np.unique(np.right_shift(pixel, healsparse.utils._compute_bitshift(nside_map2, nside_map)))\n sparse_map_or.set_bits_pix(pixel2, [4])\n\n # Degrade with or\n sparse_map_test = sparse_map.degrade(nside_map2, reduction='or')\n\n # Check the results\n testing.assert_almost_equal(sparse_map_or._sparse_map, sparse_map_test._sparse_map)\n\n # Repeat for maxbits > 8\n sparse_map = healsparse.HealSparseMap.make_empty(nside_coverage, nside_map,\n WIDE_MASK, wide_mask_maxbits=16)\n sparse_map_or = healsparse.HealSparseMap.make_empty(nside_coverage, nside_map2,\n WIDE_MASK, wide_mask_maxbits=16)\n # Fill some pixels in the \"high-resolution\" map\n pixel = np.arange(0, 1024)\n pixel = np.concatenate([pixel[:512], pixel[512::3]]).ravel()\n sparse_map.set_bits_pix(pixel, [4, 12])\n sparse_map.clear_bits_pix(pixel[:16], [4]) # set low value in the first pixel\n\n # Check which pixels will be full in the \"low-resolution\" map and fill them\n # Note that we are filling more than the ones that are going to be True\n # since we want to preserve the coverage_map\n pixel2_all = np.unique(np.right_shift(pixel,\n healsparse.utils._compute_bitshift(nside_map2, nside_map)))\n sparse_map_or.set_bits_pix(pixel2_all, [4, 12])\n\n # Get the pixel number of the bad pixels\n pixel2_bad = np.array([0])\n sparse_map_or.clear_bits_pix(pixel2_bad, [4]) # set low value in the first pixel\n\n # Degrade with or\n sparse_map_test = sparse_map.degrade(nside_map2, reduction='or')\n\n # Check the results\n testing.assert_almost_equal(sparse_map_test._sparse_map, sparse_map_or._sparse_map)\n\n # Test degrade-on-read\n self.test_dir = tempfile.mkdtemp(dir='./', prefix='TestHealSparse-')\n\n fname = os.path.join(self.test_dir, 'test_wide_degrade.hs')\n sparse_map.write(fname)\n\n sparse_map_test2 = healsparse.HealSparseMap.read(fname, degrade_nside=nside_map2, reduction='or')\n testing.assert_almost_equal(sparse_map_test2._sparse_map, sparse_map_or._sparse_map)"
] | [
"0.6960213",
"0.66661066",
"0.65235865",
"0.64447516",
"0.6371661",
"0.6339229",
"0.6302238",
"0.6228568",
"0.6185054",
"0.58057094",
"0.5755791",
"0.5741155",
"0.57355267",
"0.56997937",
"0.56335616",
"0.5625084",
"0.56033003",
"0.5583323",
"0.5559221",
"0.5544787",
"0.54311514",
"0.54261404",
"0.54241884",
"0.5409002",
"0.53959",
"0.5387601",
"0.5374201",
"0.5363899",
"0.5292495",
"0.5278974"
] | 0.71554786 | 0 |
Perform a bitwise or op with a non existent bin. | def test_bit_or_bad_bin_name(self):
value = bytearray([8])
ops = [bitwise_operations.bit_or("bad_name", 0, 8, 1, value, None)]
with pytest.raises(e.BinNotFound):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_or(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([9] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def bitwise_or(lhs, rhs):\n return _make.bitwise_or(lhs, rhs)",
"def test_bit_or_bad_arg(self):\n value = 1\n ops = [bitwise_operations.bit_or(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def bitwise_or(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_or_op, other)",
"def test_bit_or_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def convert_broadcast_logical_or(node, **kwargs):\n return create_basic_op_node('Or', node, kwargs)",
"def binary_or(binary1, binary2):\n if binary1.shape == binary2.shape:\n binary = np.where(np.logical_or(binary1,binary2)==True, 1., 0.)\n return binary\n else:\n return None",
"def bitwise_or(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] | self.registers[register[1]])\n logger.info(\"Bitwise OR on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def __or__(self, other):\n return BitBoard(self.num | other.num)",
"def __or__(self, other):\n return self.fam.c_binop('or', self, other)",
"def instruction_or(self, register, a, b):\n if Vm.is_register(a):\n a = self.get_register(a)\n\n if Vm.is_register(b):\n b = self.get_register(b)\n\n self.set_register(register, (a | b) % MAX_INT)",
"def or_(a, b):",
"def test_bit_and_invalid_bin_name(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_or_multiple_bytes(self):\n value = bytearray([8] * 5)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 40, 5, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([9] * 5)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_xor_bad_bin_name(self):\n value = bytearray([8])\n ops = [bitwise_operations.bit_xor(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def __or__(self, obj):\n return self._boolean_operation(obj, operator.__or__)",
"def xor(self, *args):\n return Xor(self, *args)",
"def test_bit_or_multiple_bytes_value_unchanged(self):\n value = bytearray([255])\n ops = [bitwise_operations.bit_or(self.five_255_bin, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_or_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def convert_broadcast_logical_xor(node, **kwargs):\n return create_basic_op_node('Xor', node, kwargs)",
"def OR(f, g):\n def _or(x):\n return f(x) | g(x)\n return _or",
"def or_(*args, **kwargs):\n ...",
"def test_bit_or_bit_size_too_large(self):\n value = bytearray([8] * 6)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 41, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def visit_BinOp(self, node):\n if node and not config.mutated:\n return self.visit_node(node)\n elif node and config.mutated and config.recovering:\n return self.recover_node(node)\n return node",
"def __or__(self, y):\n return self.__and__(y) ^ self ^ y",
"def __or__(self, other: Any) -> Operators:\n return self.operate(or_, other)",
"def __or__(self, other):\n return self._operation_or(other)",
"def logical_or(lhs, rhs):\n return _make.logical_or(lhs, rhs)",
"def test_bit_xor_with_policy(self):\n value = bytearray([0])\n bit_policy = {\n \"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY,\n }\n ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, bit_policy)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_xor_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)"
] | [
"0.7058968",
"0.68445206",
"0.6766226",
"0.6755977",
"0.66884106",
"0.6688318",
"0.662055",
"0.6593961",
"0.6555172",
"0.65347177",
"0.64945513",
"0.6492931",
"0.6429049",
"0.6394153",
"0.63550234",
"0.6181719",
"0.61228025",
"0.61127645",
"0.6107482",
"0.60979706",
"0.60833657",
"0.6078307",
"0.6070918",
"0.6064855",
"0.6051343",
"0.6020466",
"0.60176694",
"0.6003816",
"0.599429",
"0.5993583"
] | 0.7370496 | 0 |
Perform a bitwise rscan op. | def test_bit_rscan(self):
value = True
ops = [bitwise_operations.bit_rscan(self.count_bin, 32, 8, value)]
expected_value = 7
_, _, result = self.as_connection.operate(self.test_key, ops)
assert result[self.count_bin] == expected_value | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_rscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.count_bin, 4, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_rscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rshift(self):\n ops = [bitwise_operations.bit_rshift(self.count_bin, 8, 8, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [10] * 1 + [86] * 1 + [255] * 1 + [3] * 1)\n assert bins[self.count_bin] == expected_result",
"def test_bit_rshift_wrap(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 40, 8, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_rscan_value_not_found(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.five_255_bin, 0, 40, value)]\n\n expected_value = -1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.five_255_bin] == expected_value",
"def test_bit_rshift_across_bytes(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 4, 16, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] + [32] + [33] + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def scan(self, mask):",
"def bitwise_rshift(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_rshift_op, other)",
"def test_bit_rscan_bad_bin_name(self):\n value = True\n ops = [bitwise_operations.bit_rscan(\"bad_name\", 0, 8, value)]\n\n expected_value = None\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"bad_name\"] == expected_value",
"def test_bit_rshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rshift_bad_arg(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 1.5, 8, 1, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_lscan(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 32, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_rshift():\n value = 42\n num_a = param.Integer(value=value)\n assert num_a.value == value\n\n new_value = operator.rshift(value, 1)\n num_a.value >>= 1\n assert num_a.value == new_value",
"def useRadix(self) -> \"Scanner\":\n raise NotImplementedError",
"def right_shift(self):\n register = (self.opcode & 0xFFF) >> 8\n bits = self.registers[register]\n \"\"\"if bits & 0b1 == 1:\n self.registers[0xF] = 1\n else:\n self.registers[0xF] = 0\n \"\"\"\n self.registers[0xF] = bits & 0b1\n self.registers[register] = self.registers[register] >> 1\n logger.info(\"Shifted register V{} 1 bit to the right got {}\".format(\n register,\n hex(self.registers[register])))",
"def test_bit_lscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 7, 8, value)]\n\n expected_value = 1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.test_bin_ones] == expected_value",
"def ROL(byte, count):\n return ((byte << count) | (byte >> (32 - count))) & 0xffffffff",
"def SRR():\n\tglobal pointer, memory, registers\n\tregisters[memory[pointer + 0x02]] = registers[memory[pointer + 0x02]] >> memory[pointer + 0x01]\n\tpointer += 0x03",
"def scanr(func, start, itr):\n if not callable(func):\n raise TypeError(\"First argument to scanr must be callable\")\n itr = iter(itr)\n \n return _scanr(func, start, itr)",
"def __rshift__(self, other):\r\n # TODO: extend to secret offset\r\n if not isinstance(other, int):\r\n return NotImplemented\r\n\r\n return self.__floordiv__(1<<other)",
"def rotl(x, count):\n ret = 0\n for i in range(64):\n bit = (x >> i) & 1\n ret |= bit << ((i + count) % 64)\n return ret",
"def rshift(val, n):\n return (val % 0x100000000) >> n",
"def rshift(val, n):\n return (val % 0x100000000) >> n",
"def test_bit_rshift_bad_bin_name(self):\n ops = [bitwise_operations.bit_rshift(\"bad_name\", 0, 8, 1, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def do_AXIWRRC(self, value):\n assert(len(value) == 1)\n assert(type(value) == bytes)\n self.__send__(bytes(pc.PROBE_CMD_AXIWRRC))\n self.__send__(value)\n return None",
"def ROR(self, value):\n carry = value & 0b1\n result = ((value >> 1) & 0b01111111) | (0b10000000 if self.reg.C else 0)\n self.reg.C = carry\n self.reg.N = result >> 7\n self.reg.Z = result == 0\n return result",
"def __LFSR(self, key: bytearray) -> int:\n x = key.pop()\n out = x ^ key[254] ^ key[244]\n key.append(out)\n return out",
"def rshift(val: int, n: int) -> int:\n return (val % 0x100000000) >> n"
] | [
"0.74822855",
"0.6734437",
"0.6538638",
"0.6246549",
"0.62174636",
"0.6194373",
"0.618414",
"0.607976",
"0.59486955",
"0.57588637",
"0.5621344",
"0.5594654",
"0.5458126",
"0.52684414",
"0.5247702",
"0.51422316",
"0.51344895",
"0.51321477",
"0.5124892",
"0.5113414",
"0.50904137",
"0.5086191",
"0.50589377",
"0.50317454",
"0.50317454",
"0.49875337",
"0.49652478",
"0.49549708",
"0.49060264",
"0.4905926"
] | 0.75062853 | 0 |
Perform a bitwise rscan op with an offset that causes the scan to search multiple bytes. | def test_bit_rscan_across_bytes(self):
value = False
ops = [bitwise_operations.bit_rscan(self.count_bin, 4, 8, value)]
expected_value = 6
_, _, result = self.as_connection.operate(self.test_key, ops)
assert result[self.count_bin] == expected_value | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_rscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rscan(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 32, 8, value)]\n\n expected_value = 7\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_rscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rshift_across_bytes(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 4, 16, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] + [32] + [33] + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def scan(self, mask):",
"def test_bit_rshift_wrap(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 40, 8, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_rshift(self):\n ops = [bitwise_operations.bit_rshift(self.count_bin, 8, 8, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [10] * 1 + [86] * 1 + [255] * 1 + [3] * 1)\n assert bins[self.count_bin] == expected_result",
"def test_bit_rscan_value_not_found(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.five_255_bin, 0, 40, value)]\n\n expected_value = -1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.five_255_bin] == expected_value",
"def rfind(a, sub, start=0, end=None):\n return _vec_string(\n a, int_, 'rfind', [sub, start] + _clean_args(end))",
"def test_bit_rshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def shift_right(self):\n self.pointer = (self.pointer + 1) % len(self.data)",
"def rfind(self, sub) -> int:\n pass",
"def bitwise_rshift(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_rshift_op, other)",
"def rshift(val, n):\n return (val % 0x100000000) >> n",
"def rshift(val, n):\n return (val % 0x100000000) >> n",
"def ROL(byte, count):\n return ((byte << count) | (byte >> (32 - count))) & 0xffffffff",
"def rotl(x, count):\n ret = 0\n for i in range(64):\n bit = (x >> i) & 1\n ret |= bit << ((i + count) % 64)\n return ret",
"def rfind(self, sub, start=0, end=None):\n return rfind(self, sub, start, end)",
"def scanr(func, start, itr):\n if not callable(func):\n raise TypeError(\"First argument to scanr must be callable\")\n itr = iter(itr)\n \n return _scanr(func, start, itr)",
"def test_bit_rscan_bad_bin_name(self):\n value = True\n ops = [bitwise_operations.bit_rscan(\"bad_name\", 0, 8, value)]\n\n expected_value = None\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"bad_name\"] == expected_value",
"def rindex(self, sub) -> int:\n pass",
"def rshift(val: int, n: int) -> int:\n return (val % 0x100000000) >> n",
"def useRadix(self) -> \"Scanner\":\n raise NotImplementedError",
"def rshift(self, count):\n self._c = (bitarray('0') * count) + self._c[:-count]",
"def test_bit_lscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 7, 8, value)]\n\n expected_value = 1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.test_bin_ones] == expected_value",
"def undo_scan(self, sub_array_id: int):",
"def __rshift__(self, next: 'IO[TResult]') -> 'IO[TResult]':\n return self.bind(lambda _: next)",
"def SRR():\n\tglobal pointer, memory, registers\n\tregisters[memory[pointer + 0x02]] = registers[memory[pointer + 0x02]] >> memory[pointer + 0x01]\n\tpointer += 0x03",
"def test_bit_lscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)"
] | [
"0.65359974",
"0.62749314",
"0.61366034",
"0.5726591",
"0.56616104",
"0.5530678",
"0.53169584",
"0.525473",
"0.52101773",
"0.51923454",
"0.5138028",
"0.51262224",
"0.5119742",
"0.5088162",
"0.5071134",
"0.5071134",
"0.5028353",
"0.49690193",
"0.4927765",
"0.49174833",
"0.48938543",
"0.48721564",
"0.48587278",
"0.48165262",
"0.4815706",
"0.4761781",
"0.47542986",
"0.47237417",
"0.47074762",
"0.47065312"
] | 0.68539107 | 0 |
Perform a bitwise rscan op with bit_offset outside bitmap. | def test_bit_rscan_offset_out_of_range(self):
value = True
ops = [bitwise_operations.bit_rscan(self.count_bin, 41, 8, value)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_rscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.count_bin, 4, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_rscan(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 32, 8, value)]\n\n expected_value = 7\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_rscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def scan(self, mask):",
"def test_bit_rscan_value_not_found(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.five_255_bin, 0, 40, value)]\n\n expected_value = -1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.five_255_bin] == expected_value",
"def test_bit_rshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rshift_across_bytes(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 4, 16, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] + [32] + [33] + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_lscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rshift_wrap(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 40, 8, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_rscan_bad_bin_name(self):\n value = True\n ops = [bitwise_operations.bit_rscan(\"bad_name\", 0, 8, value)]\n\n expected_value = None\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"bad_name\"] == expected_value",
"def test_bit_rshift(self):\n ops = [bitwise_operations.bit_rshift(self.count_bin, 8, 8, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [10] * 1 + [86] * 1 + [255] * 1 + [3] * 1)\n assert bins[self.count_bin] == expected_result",
"def test_bit_lscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 7, 8, value)]\n\n expected_value = 1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.test_bin_ones] == expected_value",
"def bitscan_forward(bitboard):\n i = 1\n while not (bitboard >> np.uint64(i)) % 2:\n i += 1\n return i",
"def test_bit_rshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 41, 1)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_lscan(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 32, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_get_int_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 41, 1, False)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def writeScanMask(self, array):\n offset = self.scanOffset\n shape = self.scanShape\n stride = self.scanStride\n \n target = pg.subArray(array, offset, shape, stride)\n target[:] = 1",
"def undo_scan(self, sub_array_id: int):",
"def rotl(x, count):\n ret = 0\n for i in range(64):\n bit = (x >> i) & 1\n ret |= bit << ((i + count) % 64)\n return ret",
"def bitwise_rshift(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_rshift_op, other)",
"def test_bit_or_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_lscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def getInstructionBits(self, offset: int, startbit: int, size: int) -> int:\n ...",
"def analyse_roi(self, atomData):\n\n if self.copy_sampler:\n sampler = copyModule.deepcopy(self.sampler)\n else:\n sampler = self.sampler\n sInput = self.packSamplerInput(atomData)\n sampler.linkToData(sInput)\n\n logger.info('Treating region %d', atomData.get_roi_id())\n sampler.runSampling(atomData)\n logger.info('Cleaning memory ...')\n sampler.dataInput.cleanMem()\n return sampler",
"def test_bit_remove_offset_out_of_range(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def rfind(self, sub) -> int:\n pass",
"def read_rle_crop(\r\n self, ix0: int, ix1: int, iy0: int, iy1: int\r\n ) -> Union[Array, None]:\r\n if self.rle_mask is None:\r\n return None\r\n return util.rle_crop(\r\n self.rle_mask,\r\n ix0=ix0,\r\n ix1=ix1,\r\n iy0=iy0,\r\n iy1=iy1,\r\n image_shape=self.image.shape,\r\n )",
"def generate_rle_1bit(source):\n\n current = 0\n count = 0\n # We start with an implicit black pixel, which isn't actually part\n # of the image. The decoder must discard this pixel. This\n # implicit black pixel ensures that there are no 0 counts anywhere\n # in the resulting data.\n next = 0\n while True:\n while current == next:\n count += 1\n try:\n next = source.next()\n except StopIteration:\n yield count\n raise StopIteration\n yield count\n current = next\n count = 0"
] | [
"0.67986",
"0.66038847",
"0.6403984",
"0.6318248",
"0.599119",
"0.5979703",
"0.54372746",
"0.5428746",
"0.53934145",
"0.5282545",
"0.5277166",
"0.51844627",
"0.5067494",
"0.5055215",
"0.4952921",
"0.49221352",
"0.4920336",
"0.48970672",
"0.4873152",
"0.48365533",
"0.47873604",
"0.4783279",
"0.47720492",
"0.4733232",
"0.47314477",
"0.4705861",
"0.47042695",
"0.47032723",
"0.4673177",
"0.46611714"
] | 0.7030813 | 0 |
Perform a bitwise rscan op with bit_size larger than bitmap. | def test_bit_rscan_bit_size_too_large(self):
value = True
ops = [bitwise_operations.bit_rscan(self.test_bin_ones, 0, 41, value)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_rscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.count_bin, 4, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_rscan(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 32, 8, value)]\n\n expected_value = 7\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_rshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rscan_offset_out_of_range(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.count_bin, 41, 8, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def scan(self, mask):",
"def test_bit_lscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rscan_value_not_found(self):\n value = False\n ops = [bitwise_operations.bit_rscan(self.five_255_bin, 0, 40, value)]\n\n expected_value = -1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.five_255_bin] == expected_value",
"def test_bit_rshift(self):\n ops = [bitwise_operations.bit_rshift(self.count_bin, 8, 8, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [10] * 1 + [86] * 1 + [255] * 1 + [3] * 1)\n assert bins[self.count_bin] == expected_result",
"def test_bit_rshift_across_bytes(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 4, 16, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] + [32] + [33] + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_rshift_wrap(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 40, 8, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_rscan_bad_bin_name(self):\n value = True\n ops = [bitwise_operations.bit_rscan(\"bad_name\", 0, 8, value)]\n\n expected_value = None\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[\"bad_name\"] == expected_value",
"def test_bit_lscan_across_bytes(self):\n value = False\n ops = [bitwise_operations.bit_lscan(self.test_bin_ones, 7, 8, value)]\n\n expected_value = 1\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.test_bin_ones] == expected_value",
"def test_bit_lscan(self):\n value = True\n ops = [bitwise_operations.bit_lscan(self.count_bin, 32, 8, value)]\n\n expected_value = 6\n _, _, result = self.as_connection.operate(self.test_key, ops)\n assert result[self.count_bin] == expected_value",
"def test_bit_resize_shrink_removes_from_end(self):\n ops = [bitwise_operations.bit_resize(self.zero_one_bin, 5)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n\n assert len(bins[self.zero_one_bin]) == 5\n assert bins[self.zero_one_bin] == bytearray([0] * 5)",
"def test_bit_rshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_resize_shrink_only_does_not_allow_grow(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 10, resize_flags=aerospike.BIT_RESIZE_SHRINK_ONLY)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def benchmark_select_rle_conversions():\n import kwimage\n import ubelt as ub\n c_mask = kwimage.Mask.random(shape=(256, 256))\n f_mask = c_mask.to_fortran_mask(copy=True)\n\n img = c_mask.data\n\n ti = ub.Timerit(1000, bestof=50, verbose=1)\n\n for timer in ti.reset('img -> encode_run_length(non-binary)'):\n with timer:\n kwimage.encode_run_length(img, binary=False)\n\n for timer in ti.reset('img -> encode_run_length(binary)'):\n with timer:\n kwimage.encode_run_length(img, binary=True)\n\n for timer in ti.reset('c_mask -> to_array_rle'):\n with timer:\n c_mask.to_array_rle()\n\n for timer in ti.reset('c_mask -> to_bytes_rle'):\n with timer:\n c_mask.to_bytes_rle()\n\n for timer in ti.reset('f_mask -> to_array_rle'):\n with timer:\n f_mask.to_array_rle()\n\n for timer in ti.reset('f_mask -> to_bytes_rle'):\n with timer:\n f_mask.to_bytes_rle()",
"def rebin(self, *args, **kwargs):\n return _image.image_rebin(self, *args, **kwargs)",
"def test_bit_resize_shrink_only_allows_shrink(self):\n ops = [bitwise_operations.bit_resize(self.test_bin_ones, 1, resize_flags=aerospike.BIT_RESIZE_SHRINK_ONLY)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n\n assert len(bins[self.test_bin_ones]) == 1",
"def selective_search_roidb(self):\n # cache_path: data/cache/Actions/\n # self.name: rcnn_<>_<>\n # cache_file: data/cache/Actions/rcnn_<datatype>_<imageset>_selective_search_roidb.pkl\n cache_file = None\n if cfg.LESSEN_DEBUG_TIME:\n lessen_debug_str = cfg.LESSEN_DEBUG_STR\n cache_file = os.path.join(self.cache_path, self.name + \"_\" + \n lessen_debug_str + '_selective_search_roidb.pkl')\n else:\n cache_file = os.path.join(self.cache_path, self.name + '_selective_search_roidb.pkl')\n\n if os.path.exists(cache_file):\n with open(cache_file, 'rb') as fid:\n roidb = cPickle.load(fid)\n print '{} ss roidb loaded from {}'.format(self.name, cache_file)\n return roidb\n\n if self._image_set != 'test':\n gt_roidb = self.gt_roidb()\n gt_roidb, ss_roidb = self._load_selective_search_roidb(gt_roidb)\n roidb = action_datasets.imdb.merge_roidbs(gt_roidb, ss_roidb)\n else:\n roidb = self._load_selective_search_roidb(None)\n\n\n with open(cache_file, 'wb') as fid:\n cPickle.dump(roidb, fid, cPickle.HIGHEST_PROTOCOL)\n print 'wrote ss roidb to {}'.format(cache_file)\n\n return roidb",
"def test_bit_rshift_bad_arg(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 1.5, 8, 1, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def rebin_image(self):\r\n\r\n # bin the image down to smaller size by combining groups of bins\r\n\r\n print('Rebinning image')\r\n\r\n sh = self.imageData.shape\r\n\r\n if self.binsize > 1 or self.zbinsize > 1:\r\n\r\n nredx = int(sh[1]/self.binsize)\r\n\r\n nredy = int(sh[2]/self.binsize)\r\n\r\n nredz = int(self.imageData.shape[0]/self.zbinsize)\r\n print('nredx,nredy,nredz: ',[nredx,nredy,nredz])\r\n\r\n self.imageData = self.bin_ndarray(self.imageData, new_shape=(nredz, nredx, nredy), operation='mean')\r\n\r\n if nredz > 1:\r\n\r\n beforeFrames = self.nFrames\r\n\r\n self.nFrames = self.imageData.shape[0]\r\n\r\n self.framerate = self.nFrames/(self.nrepetitions*self.period)\r\n\r\n self.times = np.arange(0, self.nFrames/self.framerate, 1.0/self.framerate)\r\n\r\n print(' Image Rebinned')\r\n\r\n self.print_image_info()",
"def test_bit_get_bit_size_too_large(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 0, 41)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def generate_rle_1bit(source):\n\n current = 0\n count = 0\n # We start with an implicit black pixel, which isn't actually part\n # of the image. The decoder must discard this pixel. This\n # implicit black pixel ensures that there are no 0 counts anywhere\n # in the resulting data.\n next = 0\n while True:\n while current == next:\n count += 1\n try:\n next = source.next()\n except StopIteration:\n yield count\n raise StopIteration\n yield count\n current = next\n count = 0",
"def bitwise_rshift(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_rshift_op, other)",
"def test_bit_get_int_bit_size_too_large(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 0, 41, False)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def bitscan_forward(bitboard):\n i = 1\n while not (bitboard >> np.uint64(i)) % 2:\n i += 1\n return i",
"def rotl(x, count):\n ret = 0\n for i in range(64):\n bit = (x >> i) & 1\n ret |= bit << ((i + count) % 64)\n return ret",
"def scan_binary(self, filepath):\n with open(filepath, \"rb\") as input_file:\n return self.__make_api_call('scan/binary', files={'input_file': input_file}, method='POST')",
"def downsample_dataset(input_, output, cell_size, method=\"mean\", key_path=None,\n rescaling=False, nbit=16, minmax=None, skip=None,\n crop=(0, 0, 0, 0, 0, 0)):\n __check_output(output)\n results = __get_cropped_shape(input_, crop=crop, key_path=key_path)\n (d1, d2, h1, h2, w1, w2) = results[0]\n (depth1, height1, width1) = results[1]\n if method == \"median\":\n dsp_method = np.median\n elif method == \"max\":\n dsp_method = np.amax\n elif method == \"min\":\n dsp_method = np.amin\n else:\n dsp_method = np.mean\n if isinstance(cell_size, int):\n cell_size = (cell_size, cell_size, cell_size)\n depth_dsp = depth1 // cell_size[0]\n height_dsp = height1 // cell_size[1]\n width_dsp = width1 // cell_size[2]\n if (depth_dsp == 0) or (height_dsp == 0) or (width_dsp == 0):\n raise ValueError(\"Incorrect cell size {}\".format(cell_size))\n in_type = __get_input_type(input_)\n if in_type == \"tif\":\n data = losa.find_file(input_ + \"/*.tif*\")\n data_type = np.asarray(Image.open(data[0])).dtype\n elif in_type == \"hdf\":\n data = losa.load_hdf(input_, key_path)\n data_type = data.dtype\n else:\n data = input_\n data_type = data.dtype\n res_type = str(data_type)\n if rescaling is True:\n if nbit == 16:\n res_type = \"uint16\"\n elif nbit == 8:\n res_type = \"uint8\"\n else:\n raise ValueError(\"Only two options for nbit: 8 or 16 !!!\")\n if str(data_type) != res_type:\n if data_type == np.uint8:\n minmax = (0, 255)\n elif data_type == np.uint16:\n minmax = (0, 65535)\n else:\n if skip is None:\n skip = int(np.clip(np.ceil(0.15 * depth1), 1, depth1 - 1))\n if minmax is None:\n f_alias = get_statistical_information_dataset\n minmax = f_alias(input_, percentile=(0, 100), skip=skip,\n crop=crop, key_path=key_path)[0:2]\n else:\n rescaling = False\n out_type = __get_output_type(output)\n if out_type == \"hdf\":\n data_dsp = losa.open_hdf_stream(\n output, (depth_dsp, height_dsp, width_dsp),\n data_type=res_type, key_path=\"entry/data\", overwrite=True)\n elif out_type is None:\n data_dsp = []\n else:\n data_dsp = None\n num = 0\n for i in range(d1, d2, cell_size[0]):\n if (i + cell_size[0]) > (d1 + depth1):\n break\n else:\n if in_type == \"tif\":\n mat = np.asarray([losa.load_image(data[j])[h1:h2, w1:w2]\n for j in range(i, i + cell_size[0])])\n mat = mat[:, :height_dsp * cell_size[1],\n :width_dsp * cell_size[2]]\n mat = mat.reshape(1, cell_size[0], height_dsp,\n cell_size[1], width_dsp, cell_size[2])\n mat_dsp = dsp_method(\n dsp_method(dsp_method(mat, axis=-1), axis=1), axis=2)[0]\n else:\n mat = data[i:i + cell_size[0],\n h1:h1 + height_dsp * cell_size[1],\n w1:w1 + width_dsp * cell_size[2]]\n mat = mat.reshape(1, cell_size[0], height_dsp,\n cell_size[1], width_dsp,\n cell_size[2])\n mat_dsp = dsp_method(dsp_method(\n dsp_method(mat, axis=-1), axis=1), axis=2)[0]\n if rescaling:\n mat_dsp = rescale(mat_dsp, nbit, minmax)\n if out_type is None:\n data_dsp.append(mat_dsp)\n elif out_type == \"hdf\":\n data_dsp[num] = mat_dsp.astype(res_type)\n else:\n out_name = \"0000\" + str(num)\n losa.save_image(output + \"/img_\" + out_name[-5:] + \".tif\",\n mat_dsp.astype(res_type))\n num += 1\n if out_type is None:\n data_dsp = np.asarray(data_dsp).astype(res_type)\n return data_dsp"
] | [
"0.69535387",
"0.67778087",
"0.6079555",
"0.5970527",
"0.56409127",
"0.5558105",
"0.5542117",
"0.5486178",
"0.5464228",
"0.5384822",
"0.5123307",
"0.5029938",
"0.49641097",
"0.49303055",
"0.49159634",
"0.4879424",
"0.47828934",
"0.4773927",
"0.47594815",
"0.46685913",
"0.46619552",
"0.46439692",
"0.46434417",
"0.46326178",
"0.46303847",
"0.46286392",
"0.46036574",
"0.45951888",
"0.4571954",
"0.45598203"
] | 0.73615736 | 0 |
Perform a bitwise rshift op with offset > bitmap. | def test_bit_rshift_offset_out_of_range(self):
ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 41, 8, 1, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def bitwise_rshift(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_rshift_op, other)",
"def test_bit_rshift_wrap(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 40, 8, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_rshift_across_bytes(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 4, 16, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] + [32] + [33] + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_rshift(self):\n ops = [bitwise_operations.bit_rshift(self.count_bin, 8, 8, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [10] * 1 + [86] * 1 + [255] * 1 + [3] * 1)\n assert bins[self.count_bin] == expected_result",
"def rshift(val, n):\n return (val % 0x100000000) >> n",
"def rshift(val, n):\n return (val % 0x100000000) >> n",
"def __rshift__(self, other):\r\n # TODO: extend to secret offset\r\n if not isinstance(other, int):\r\n return NotImplemented\r\n\r\n return self.__floordiv__(1<<other)",
"def __rshift__(self, other: Any) -> ColumnOperators:\n return self.operate(rshift, other)",
"def rshift(self, value):\n return self.clone().rshift_(value)",
"def test_rshift():\n value = 42\n num_a = param.Integer(value=value)\n assert num_a.value == value\n\n new_value = operator.rshift(value, 1)\n num_a.value >>= 1\n assert num_a.value == new_value",
"def shift_right(self):\n self.pointer = (self.pointer + 1) % len(self.data)",
"def right_shift(lhs, rhs):\n return _make.right_shift(lhs, rhs)",
"def rshift_(self, value):\n assert isinstance(value, int), \"rshift must take an integer argument.\"\n self.share >>= value\n return self",
"def lrshift(val, n) -> np.int64:\n return (val % (1 << 64)) >> n",
"def rshift(val: int, n: int) -> int:\n return (val % 0x100000000) >> n",
"def shift(image,shift_x,shift_y):\n return np.roll(np.roll(image,shift_y,axis=0),shift_x,axis=1)",
"def __rshift__(self, other):\n other.set_upstream(self)\n # return other so a >> b >> c works\n return other",
"def right_shift(key,shift):\n if shift > len(key):\n shift = shift % len(key)\n return key[-shift:] + key[:-shift]",
"def test_bit_rshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def right_shift(self):\n register = (self.opcode & 0xFFF) >> 8\n bits = self.registers[register]\n \"\"\"if bits & 0b1 == 1:\n self.registers[0xF] = 1\n else:\n self.registers[0xF] = 0\n \"\"\"\n self.registers[0xF] = bits & 0b1\n self.registers[register] = self.registers[register] >> 1\n logger.info(\"Shifted register V{} 1 bit to the right got {}\".format(\n register,\n hex(self.registers[register])))",
"def rshift(self, count):\n self._c = (bitarray('0') * count) + self._c[:-count]",
"def __rshift__(self, other):\r\n return NotImplemented",
"def shift_right(input, pad=2):\n return tf.concat((tf.ones_like(input[:, :1]) * pad, input[:, :-1]), 1)",
"def right_shift_quirk(self):\n register = self.return_middle_registers(self.opcode)\n bits = self.registers[register[1]]\n self.registers[0xF] = bits & 0b1\n self.registers[register[0]] = self.registers[register[1]] >> 1\n logger.info(\"Shifted register V{} to the right into V{}({})\".format(\n register[1],\n register[0],\n hex(self.registers[register[0]])))",
"def __rlshift__(self, other):\r\n return NotImplemented",
"def __rlshift__(self, other):\r\n return NotImplemented",
"def test_bit_rshift_bad_arg(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 1.5, 8, 1, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def rshift(self):\n self.lcd_byte(0x1C, LCD_CMD)",
"def shift(self, da, dim, shift):\n # TODO: generalize rolling function, allow custom shifts, handle\n # boundary conditions, etc.\n return da.roll(**{dim: shift})",
"def imshift(im, yx, subsample=4):\n\n if subsample <= 1:\n subsample = 1\n\n sy = int(round(yx[0] * subsample)) # whole sampled pixels\n sx = int(round(yx[1] * subsample))\n\n sim = rebin(im, subsample, flux=True)\n sim = np.roll(sim, sy, 0)\n sim = np.roll(sim, sx, 1)\n\n return rebin(sim, -subsample, flux=True)"
] | [
"0.68082476",
"0.6507718",
"0.6502205",
"0.6427334",
"0.6422783",
"0.6422783",
"0.6422021",
"0.64078856",
"0.6404838",
"0.63749677",
"0.62379384",
"0.6169324",
"0.6154082",
"0.61445355",
"0.61361104",
"0.60724884",
"0.6042694",
"0.60101116",
"0.5978205",
"0.59142226",
"0.58438677",
"0.58236384",
"0.5743966",
"0.5729733",
"0.5725588",
"0.5725588",
"0.572207",
"0.5720975",
"0.5712362",
"0.56986237"
] | 0.6681683 | 1 |
Perform a bitwise rshift op with bit_size > bitmap. | def test_bit_rshift_bit_size_too_large(self):
ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 41, 1, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_rshift_wrap(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 0, 40, 8, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_rshift(self):\n ops = [bitwise_operations.bit_rshift(self.count_bin, 8, 8, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [10] * 1 + [86] * 1 + [255] * 1 + [3] * 1)\n assert bins[self.count_bin] == expected_result",
"def test_bit_rshift_across_bytes(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 4, 16, 3, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] + [32] + [33] + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def bitwise_rshift(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_rshift_op, other)",
"def rshift(val, n):\n return (val % 0x100000000) >> n",
"def rshift(val, n):\n return (val % 0x100000000) >> n",
"def rshift(val: int, n: int) -> int:\n return (val % 0x100000000) >> n",
"def __rshift__(self, other):\r\n # TODO: extend to secret offset\r\n if not isinstance(other, int):\r\n return NotImplemented\r\n\r\n return self.__floordiv__(1<<other)",
"def test_bit_rshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_rshift():\n value = 42\n num_a = param.Integer(value=value)\n assert num_a.value == value\n\n new_value = operator.rshift(value, 1)\n num_a.value >>= 1\n assert num_a.value == new_value",
"def rshift_(self, value):\n assert isinstance(value, int), \"rshift must take an integer argument.\"\n self.share >>= value\n return self",
"def rshift(self, value):\n return self.clone().rshift_(value)",
"def lrshift(val, n) -> np.int64:\n return (val % (1 << 64)) >> n",
"def __rshift__(self, other: Any) -> ColumnOperators:\n return self.operate(rshift, other)",
"def rshift(self, count):\n self._c = (bitarray('0') * count) + self._c[:-count]",
"def right_shift(lhs, rhs):\n return _make.right_shift(lhs, rhs)",
"def right_shift(self):\n register = (self.opcode & 0xFFF) >> 8\n bits = self.registers[register]\n \"\"\"if bits & 0b1 == 1:\n self.registers[0xF] = 1\n else:\n self.registers[0xF] = 0\n \"\"\"\n self.registers[0xF] = bits & 0b1\n self.registers[register] = self.registers[register] >> 1\n logger.info(\"Shifted register V{} 1 bit to the right got {}\".format(\n register,\n hex(self.registers[register])))",
"def rotl(x, count):\n ret = 0\n for i in range(64):\n bit = (x >> i) & 1\n ret |= bit << ((i + count) % 64)\n return ret",
"def test_bit_rshift_bad_arg(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 1.5, 8, 1, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rscan_bit_size_too_large(self):\n value = True\n ops = [bitwise_operations.bit_rscan(self.test_bin_ones, 0, 41, value)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __rshift__(self, other):\n other.set_upstream(self)\n # return other so a >> b >> c works\n return other",
"def shift_right(n, b):\n return (n >> b), n & ((1 << b) - 1)",
"def shift_right(self):\n self.pointer = (self.pointer + 1) % len(self.data)",
"def test_bit_lshift_bit_size_too_large(self):\n ops = [bitwise_operations.bit_lshift(self.test_bin_ones, 0, 41, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def shift_bits(x, k):\n if (k >= 0):\n return x << k\n else:\n return x >> -k",
"def __rshift__(self, other):\r\n return NotImplemented",
"def _right_shift_scalar(x, y):\n return inner.bit_right_shift(x, y)",
"def __rshift__(self, fn):\n if self is Nothing:\n return Nothing\n else:\n v = self.right if self.is_right() else self.left\n fn = liftF(fn, self.__class__)\n return unlift(fn(v))",
"def right_shift(key,shift):\n if shift > len(key):\n shift = shift % len(key)\n return key[-shift:] + key[:-shift]",
"def r1(x, n, max_size=32):\n return (x << n) % (2 << (max_size - 1)) + (x >> (max_size - n))"
] | [
"0.6985838",
"0.6975781",
"0.6904481",
"0.6876606",
"0.6723617",
"0.6723617",
"0.64922476",
"0.6429139",
"0.6359374",
"0.63542265",
"0.6311663",
"0.62846226",
"0.6275696",
"0.6140997",
"0.6140134",
"0.60402584",
"0.60362566",
"0.60202444",
"0.5996184",
"0.5978953",
"0.59533614",
"0.594108",
"0.5937391",
"0.5864995",
"0.58602375",
"0.5791105",
"0.57851666",
"0.5761825",
"0.57315993",
"0.5717595"
] | 0.73658377 | 0 |
Perform a bitwise subtract op with an offset that lands inbetween bytes. | def test_bit_subtract_inbetween_bytes(self):
ops = [bitwise_operations.bit_subtract(self.five_255_bin, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([240] * 1 + [15] * 1 + [255] * 3)
assert bins[self.five_255_bin] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_subtract_bit_offset_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def subtract(A, b, offset=0):\n return _diag_ufunc(A, b, offset, np.subtract)",
"def sub64(a,b):\n return(np.subtract(a, b, dtype=np.uint64))",
"def _offset_subtract(col):\n offset = col.values[:-1]\n offset = np.insert(offset, 0, 0)\n return col - offset",
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def subtract(A, b, offset=0):\r\n return _diag_ufunc(A, b, offset, np.subtract)",
"def test_bit_remove_offset_out_of_range(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def subtract(x, y):\n return x - y",
"def subtract(x, y):\n return x - y",
"def subtract(x, y):\n return x - y",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def test_bit_subtract_multiple_bytes(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [0] * 2 + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def subtract(x: int, y: int):\n return x - y",
"def subtract(x, y):\n\n return x - y",
"def subtract(self,*datas):\n\t\tdatas = list(datas)\n\t\tresult = datas.pop(0)\n\t\tfor data in datas:\n\t\t\tresult -= data\n\t\treturn result",
"def substraction_nocarry(a,b): #Beware, it is not commuative\n result = bytearray()\n carry = 0\n for byte1, byte2 in zip(a,b):\n byte_res = (byte1-byte2-carry)\n #print(byte_res)\n if byte_res < 0:\n carry = 1\n result.append(byte_res%256)\n else:\n carry = 0\n result.append(byte_res)\n return(result)",
"def SUB():\n global pointer, memory, registers\n registers[memory[pointer + 0x02]] -= memory[pointer + 0x01]\n pointer += 0x03",
"def subtract(a, b):\n return a - b",
"def subtract(a, b):\n return a - b",
"def test_bit_subtract_bit_size_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def subtraction(self, first_value, second_value):\n return bytes(first_value - second_value)",
"def subtract(first, second):\n return first - second",
"def decrement(self):\n self.data[self.pointer] -= 1\n self.data[self.pointer] %= 256",
"def test_bit_subtract_bit_size_signed(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 156, True, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([99] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def sub_reg_from_reg(self):\n register = self.return_middle_registers(self.opcode)\n if self.registers[register[0]] > self.registers[register[1]]:\n self.registers[0xF] = 1\n self.registers[register[0]] -= self.registers[register[1]]\n else:\n self.registers[0xF] = 0\n self.registers[register[0]] = (\n 256\n + self.registers[register[0]]\n - self.registers[register[1]])\n # the 256 is there to simulate a wrap around of an unsigned integer\n logger.info(\"Subtracted V{} from V{} and got {}\".format(\n register[1],\n register[0],\n self.registers[register[0]]))",
"def subtract(lhs, rhs):\n return _make.subtract(lhs, rhs)",
"def sub(a, b):\n if not type(a) is Blob and not type(b) is Blob:\n raise ValueError('At least one of `a` and `b` should be neoml.Blob.')\n\n return a - b",
"def sub(self, a, b):\n return a - b",
"def sub(self, addr):\n\n val = self.mem.read(addr)\n result = self.alu.neg_add(self.reg.accum, val)\n self.reg.accum = result",
"def subtraction(x, y):\n return x - y"
] | [
"0.64977556",
"0.62412834",
"0.6239557",
"0.62195957",
"0.6215681",
"0.618028",
"0.59770906",
"0.5848042",
"0.5848042",
"0.5848042",
"0.58252114",
"0.5815021",
"0.5802187",
"0.5801449",
"0.5796449",
"0.5793272",
"0.5781425",
"0.5732522",
"0.5732522",
"0.57230633",
"0.5714507",
"0.5669246",
"0.56188476",
"0.5601109",
"0.5577816",
"0.55718565",
"0.5561652",
"0.5543352",
"0.55276775",
"0.5509498"
] | 0.6829426 | 0 |
Perform a bitwise subtract op with multiple bytes. | def test_bit_subtract_multiple_bytes(self):
ops = [
bitwise_operations.bit_subtract(self.test_bin_ones, 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)
]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([1] * 1 + [0] * 2 + [1] * 2)
assert bins[self.test_bin_ones] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_subtract_inbetween_bytes(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([240] * 1 + [15] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result",
"def substraction_nocarry(a,b): #Beware, it is not commuative\n result = bytearray()\n carry = 0\n for byte1, byte2 in zip(a,b):\n byte_res = (byte1-byte2-carry)\n #print(byte_res)\n if byte_res < 0:\n carry = 1\n result.append(byte_res%256)\n else:\n carry = 0\n result.append(byte_res)\n return(result)",
"def subtract(self,*datas):\n\t\tdatas = list(datas)\n\t\tresult = datas.pop(0)\n\t\tfor data in datas:\n\t\t\tresult -= data\n\t\treturn result",
"def test_bit_subtract_simple(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def subtract(*args):\n return args[0] - reduce(lambda x, y: x + y, args[1:])",
"def subtract(a, b):\n return a - b",
"def subtract(a, b):\n return a - b",
"def subtract(*args):\n\n result = int(args[0]) - int(args[1])\n\n return str(result)",
"def test_bit_subtract_bit_size_signed(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 156, True, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([99] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def v3minus(a, b):\n return [a[i] - b[i] for i, j in enumerate(a)]",
"def subtract(first, second):\n return first - second",
"def subtract(*args):\n\n # TODO: Fill sum with the correct value, based on the\n # args provided.\n difference = str(args[0] - args[1])\n return difference",
"def test_bit_subtract_overflow_wrap(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([254] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_overflow_fail(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def subtraction(self, first_value, second_value):\n return bytes(first_value - second_value)",
"def test_bit_subtract_bit_size_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def subtract(x, y):\n\n return x - y",
"def subtract(a, b):\n print(\"SUBTRACTING %d - %d\" % (a, b))\n return a - b",
"def subtract(x, y):\n return x - y",
"def subtract(x, y):\n return x - y",
"def subtract(x, y):\n return x - y",
"def subtract(lhs, rhs):\n return _make.subtract(lhs, rhs)",
"def sub64(a,b):\n return(np.subtract(a, b, dtype=np.uint64))",
"def subtract(x: int, y: int):\n return x - y",
"def sub(self, a, b):\n return a - b",
"def minus(self, a, b):\n return a - b",
"def subtraction(a, b):\n return a - b",
"def test_bit_subtract_bad_bin_name(self):\n ops = [bitwise_operations.bit_subtract(\"bad_name\", 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"async def subtract(message, number1: ParamType.NUMBER, number2: ParamType.NUMBER):\n diff = number1 - number2\n return \"difference = \" + str(diff)"
] | [
"0.7051683",
"0.6489156",
"0.6265554",
"0.62049377",
"0.6195712",
"0.61772144",
"0.61772144",
"0.60979056",
"0.60612816",
"0.6039638",
"0.6035834",
"0.6015598",
"0.5974205",
"0.59607345",
"0.5958435",
"0.58393854",
"0.58328086",
"0.5803468",
"0.579507",
"0.5792536",
"0.5792536",
"0.5792536",
"0.57783645",
"0.5761532",
"0.57532316",
"0.5728301",
"0.57118356",
"0.5706552",
"0.5633853",
"0.5625158"
] | 0.75186557 | 0 |
Perform a bitwise subtract op on a nonexistent bin. | def test_bit_subtract_bad_bin_name(self):
ops = [bitwise_operations.bit_subtract("bad_name", 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)]
with pytest.raises(e.BinNotFound):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_subtract_overflow_fail(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_simple(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_subtract_bit_offset_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_bad_bin_name(self):\n ops = [bitwise_operations.bit_remove(\"bad_name\", 3, 3, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_inbetween_bytes(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([240] * 1 + [15] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_bit_size_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_bit_size_signed(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 156, True, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([99] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_multiple_bytes(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [0] * 2 + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_subtract_overflow_wrap(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([254] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def test_bit_subtract_overflow_saturate(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 255, False, aerospike.BIT_OVERFLOW_SATURATE, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_remove_offset_out_of_range(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_two_bytes(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 1, 2, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * 3)\n # should have removed 2 0s)\n\n assert len(bins[self.test_bin_zeroes]) == 3\n # should have len 3 after removing 2 0s",
"def test_bit_not(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 0, 40, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_not_bad_bin_name(self):\n ops = [bitwise_operations.bit_not(\"bad_name\", 0, 8, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_not_bad_arg(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 2.7, 8, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor_bad_bin_name(self):\n value = bytearray([8])\n ops = [bitwise_operations.bit_xor(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_not_offset_out_of_range(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 41, 8, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_bad_arg_type(self):\n ops = [bitwise_operations.bit_remove(\"bad_name\", 3, 3.5, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def testBinizeUnbinize(self):\n console.terse(\"{0}\\n\".format(self.testBinizeUnbinize.__doc__))\n\n n = 5\n u = aiding.binize(n, 8)\n self.assertEqual(u, '00000101')\n n = aiding.unbinize(u)\n self.assertEqual(n, 5)",
"def subtract(a, b):\n return a - b",
"def subtract(a, b):\n return a - b",
"def test_bit_get_bad_bin_name(self):\n ops = [bitwise_operations.bit_get(\"bad_name\", 0, 1)]\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = None\n assert result[\"bad_name\"] == expected_result",
"def test_bit_remove_randnumbytes_randoffset(self):\n offset = random.randint(0, 4)\n num_bytes = random.randint(1, (5 - offset))\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, offset, num_bytes, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * (5 - num_bytes))\n # should have removed num_bytes 0s",
"def test_bit_get_int_bad_bin_name(self):\n ops = [bitwise_operations.bit_get_int(\"bad_name\", 0, 1, False)]\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = None\n assert result[\"bad_name\"] == expected_result",
"def subtract(value, arg):\n try:\n return int(value) - int(arg)\n except (ValueError, TypeError):\n try:\n return value - arg\n except Exception:\n return \"\"",
"def test_bit_rshift_bad_bin_name(self):\n ops = [bitwise_operations.bit_rshift(\"bad_name\", 0, 8, 1, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_invalid_bin_name(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_binary_complement_longer_mask(self):\n self.assertEqual(utils.binary_complement('11010', '000010'), '00000')"
] | [
"0.6932047",
"0.68951654",
"0.68864524",
"0.68545467",
"0.68055755",
"0.668892",
"0.6510099",
"0.64084166",
"0.628363",
"0.62496334",
"0.6238307",
"0.6140046",
"0.6119843",
"0.6021742",
"0.5957144",
"0.5939512",
"0.5780383",
"0.5756103",
"0.56450284",
"0.56420887",
"0.5607923",
"0.55847424",
"0.55847424",
"0.5531545",
"0.55277187",
"0.5518112",
"0.5510535",
"0.5510434",
"0.5491034",
"0.5462144"
] | 0.78149927 | 0 |
Perform a bitwise subtract op with a bit_offset that is out of range for the bitmap being modified. | def test_bit_subtract_bit_offset_out_of_range(self):
ops = [
bitwise_operations.bit_subtract(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)
]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_remove_offset_out_of_range(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_bit_size_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_inbetween_bytes(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([240] * 1 + [15] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_overflow_fail(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def test_bit_not_offset_out_of_range(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 41, 8, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_bit_size_signed(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 156, True, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([99] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_overflow_saturate(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 255, False, aerospike.BIT_OVERFLOW_SATURATE, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def subtract(A, b, offset=0):\n return _diag_ufunc(A, b, offset, np.subtract)",
"def subtract(A, b, offset=0):\r\n return _diag_ufunc(A, b, offset, np.subtract)",
"def test_bit_subtract_overflow_wrap(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([254] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def _offset_subtract(col):\n offset = col.values[:-1]\n offset = np.insert(offset, 0, 0)\n return col - offset",
"def test_bit_subtract_bad_bin_name(self):\n ops = [bitwise_operations.bit_subtract(\"bad_name\", 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_simple(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_get_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get(self.test_bin_ones, 41, 1)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_multiple_bytes(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [0] * 2 + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_remove_randnumbytes_randoffset(self):\n offset = random.randint(0, 4)\n num_bytes = random.randint(1, (5 - offset))\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, offset, num_bytes, None)]\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n assert bins[self.test_bin_zeroes] == bytearray([0] * (5 - num_bytes))\n # should have removed num_bytes 0s",
"def test_bit_get_int_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_get_int(self.test_bin_ones, 41, 1, False)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_rshift_offset_out_of_range(self):\n ops = [bitwise_operations.bit_rshift(self.test_bin_ones, 41, 8, 1, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def SUB():\n global pointer, memory, registers\n registers[memory[pointer + 0x02]] -= memory[pointer + 0x01]\n pointer += 0x03",
"def sub64(a,b):\n return(np.subtract(a, b, dtype=np.uint64))",
"def sub_reg_from_reg(self):\n register = self.return_middle_registers(self.opcode)\n if self.registers[register[0]] > self.registers[register[1]]:\n self.registers[0xF] = 1\n self.registers[register[0]] -= self.registers[register[1]]\n else:\n self.registers[0xF] = 0\n self.registers[register[0]] = (\n 256\n + self.registers[register[0]]\n - self.registers[register[1]])\n # the 256 is there to simulate a wrap around of an unsigned integer\n logger.info(\"Subtracted V{} from V{} and got {}\".format(\n register[1],\n register[0],\n self.registers[register[0]]))",
"def sub(self, addr):\n\n val = self.mem.read(addr)\n result = self.alu.neg_add(self.reg.accum, val)\n self.reg.accum = result",
"def test_bit_add_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_out_of_range(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def subtract_update_(X, c, Y):\n if X.size > 2048:\n _nb_subtract_update_par(X, c, Y, out=X)\n else:\n _nb_subtract_update_seq(X, c, Y, out=X)",
"def test_bit_remove_byte_size_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 0, 6, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def subtract(self, m): \n f = m.negate()\n return self.add(f)"
] | [
"0.68870574",
"0.6712617",
"0.66374624",
"0.6593059",
"0.6452417",
"0.6321592",
"0.6146227",
"0.6096179",
"0.6046044",
"0.5997577",
"0.59970427",
"0.5973413",
"0.59491795",
"0.5849707",
"0.57583743",
"0.57313645",
"0.5667159",
"0.5593854",
"0.55748856",
"0.55695486",
"0.5569022",
"0.5568028",
"0.5534377",
"0.54662746",
"0.5449679",
"0.5441797",
"0.54299706",
"0.5330279",
"0.530082",
"0.522529"
] | 0.743607 | 0 |
Perform a bitwise subtract op that overflows with the BIT_OVERFLOW_FAIL action. | def test_bit_subtract_overflow_fail(self):
ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_subtract_bit_offset_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_bit_size_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_overflow_wrap(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([254] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_bad_bin_name(self):\n ops = [bitwise_operations.bit_subtract(\"bad_name\", 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_overflow_saturate(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 255, False, aerospike.BIT_OVERFLOW_SATURATE, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_inbetween_bytes(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([240] * 1 + [15] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_bit_size_signed(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 156, True, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([99] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_add_overflow_fail(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_simple(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_subtract_multiple_bytes(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [0] * 2 + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_not_offset_out_of_range(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 41, 8, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_not_bad_arg(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 2.7, 8, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_offset_out_of_range(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def test_subtract_zero_arg(self):\n try:\n self.assertEqual(subtract(0, -6), 7)\n except Exception as error:\n print(f'Got error in {inspect.stack()[0][3]}, {error}')",
"def test_bit_not_bit_size_too_large(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 0, 41, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_bad_arg_type(self):\n ops = [bitwise_operations.bit_remove(\"bad_name\", 3, 3.5, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)",
"def test_subtract_all_args_greater_zero(self):\n try:\n self.assertEqual(subtract(30, 16), 15)\n except Exception as error:\n print(f'Got error in {inspect.stack()[0][3]}, {error}')",
"def test_subtract_all_args_less_zero(self):\n try:\n self.assertEqual(subtract(-18, -5), -13)\n except Exception as error:\n print(error)",
"def subtract(val, otherval=None):\n if otherval is None:\n return val\n\n try:\n answer = val - int(otherval)\n return answer\n except ValueError:\n return val",
"def subtract(a, b):\n return a - b",
"def subtract(a, b):\n return a - b",
"def test_subtract(self):\n self.assertEqual(work_file.subtract(10, 5), 5)\n self.assertEqual(work_file.subtract(-1, 1), -2)\n self.assertEqual(work_file.subtract(-1, -1), 0)",
"def test_subtract_negative_result(self):\n\n a = random.randint(100, 1000)\n b = random.randint(10000, 100000)\n\n path = \"/subtract/{}/{}\".format(a, b)\n\n response = self.get_response(path)\n self.assertEqual(200, response.getcode())\n\n self.assertIn(str(a - b).encode(), response.read())",
"def subtract(x: int, y: int):\n return x - y",
"def subtract(value, arg):\n try:\n return int(value) - int(arg)\n except (ValueError, TypeError):\n try:\n return value - arg\n except Exception:\n return \"\"",
"def substraction_nocarry(a,b): #Beware, it is not commuative\n result = bytearray()\n carry = 0\n for byte1, byte2 in zip(a,b):\n byte_res = (byte1-byte2-carry)\n #print(byte_res)\n if byte_res < 0:\n carry = 1\n result.append(byte_res%256)\n else:\n carry = 0\n result.append(byte_res)\n return(result)",
"def subtract(a, b):\n print(\"SUBTRACTING %d - %d\" % (a, b))\n return a - b",
"def test_bit_add_bit_offset_out_of_range(self):\n ops = [bitwise_operations.bit_add(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)"
] | [
"0.7370349",
"0.7360217",
"0.67168427",
"0.66955477",
"0.6690933",
"0.6342002",
"0.63284343",
"0.62131953",
"0.6136948",
"0.6106323",
"0.60354006",
"0.595727",
"0.590616",
"0.58953905",
"0.58631927",
"0.58592397",
"0.58166087",
"0.5726038",
"0.5701894",
"0.56896704",
"0.56878614",
"0.5650672",
"0.5650672",
"0.5579814",
"0.5571786",
"0.5537364",
"0.55266196",
"0.5521783",
"0.5499487",
"0.5450291"
] | 0.819887 | 0 |
Perform a bitwise subtract op that overflows with the BIT_OVERFLOW_SATURATE action. | def test_bit_subtract_overflow_saturate(self):
ops = [
bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 255, False, aerospike.BIT_OVERFLOW_SATURATE, None)
]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([255] * 5)
assert bins[self.five_255_bin] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_subtract_overflow_fail(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_bit_offset_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_overflow_wrap(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([254] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_bit_size_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_bit_size_signed(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 156, True, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([99] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_inbetween_bytes(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([240] * 1 + [15] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_simple(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_subtract_multiple_bytes(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [0] * 2 + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_subtract_bad_bin_name(self):\n ops = [bitwise_operations.bit_subtract(\"bad_name\", 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def subtract(a, b):\n return a - b",
"def subtract(a, b):\n return a - b",
"def __sub__(self, tc):\n tc = TwosComplement(tc)._negative()\n return self.__add__(tc)",
"def subtract(lhs, rhs):\n return _make.subtract(lhs, rhs)",
"def test_bit_remove_offset_out_of_range(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 6, 1, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def subtract(x: int, y: int):\n return x - y",
"def complement(x):\n out = 1 - x\n return out",
"def twos_complement(val, bits):\n if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255\n val = val - (1 << bits) # compute negative value\n return val # return positive value as is",
"def subtract(x, y):\n return x - y",
"def subtract(x, y):\n return x - y",
"def subtract(x, y):\n return x - y",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def subtract(first, second):\n return first - second",
"def subtract(self, other):\n warnings.warn(\"`BaseOperator.subtract` method is deprecated, use\"\n \"`op - other` instead\", DeprecationWarning)\n return self._add(-other)",
"def subtract(x, y):\n\n return x - y",
"def minus(self, a, b):\n return a - b",
"def subtract(self, other):\n return self.add(other.neg())",
"def twos_complement(value: int, width: int) -> int:\n signmask = 1 << (width - 1)\n if (value & signmask) == 0:\n # Mask off sign bit.\n return value & (signmask - 1)\n else:\n # Two's complement.\n return -bit_invert(value, width - 1) - 1",
"def subtract(val, otherval=None):\n if otherval is None:\n return val\n\n try:\n answer = val - int(otherval)\n return answer\n except ValueError:\n return val",
"def subtract(*args):\n return args[0] - reduce(lambda x, y: x + y, args[1:])"
] | [
"0.726783",
"0.6864169",
"0.67772174",
"0.67653507",
"0.67579377",
"0.6566348",
"0.61904657",
"0.6066806",
"0.59181464",
"0.57647073",
"0.57319677",
"0.57319677",
"0.5728272",
"0.56917715",
"0.56846565",
"0.5678812",
"0.56218684",
"0.5600619",
"0.5527363",
"0.5527363",
"0.5527363",
"0.5523733",
"0.5521506",
"0.54885435",
"0.54649305",
"0.545772",
"0.54453176",
"0.54450804",
"0.5437761",
"0.54137635"
] | 0.72179174 | 1 |
Perform a bitwise subtract op that overflows with the BIT_OVERFLOW_WRAP action. | def test_bit_subtract_overflow_wrap(self):
ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([254] * 1 + [255] * 4)
assert bins[self.five_255_bin] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_subtract_overflow_fail(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_bit_size_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 0, 41, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_overflow_saturate(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 255, False, aerospike.BIT_OVERFLOW_SATURATE, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([255] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_bit_offset_out_of_range(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_zeroes, 41, 1, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_subtract_inbetween_bytes(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 4, 8, 255, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([240] * 1 + [15] * 1 + [255] * 3)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_multiple_bytes(self):\n ops = [\n bitwise_operations.bit_subtract(self.test_bin_ones, 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)\n ]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([1] * 1 + [0] * 2 + [1] * 2)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_subtract_bit_size_signed(self):\n ops = [bitwise_operations.bit_subtract(self.five_255_bin, 0, 8, 156, True, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([99] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_subtract_simple(self):\n ops = [bitwise_operations.bit_subtract(self.test_bin_ones, 0, 8, 1, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def subtract(lhs, rhs):\n return _make.subtract(lhs, rhs)",
"def test_bit_subtract_bad_bin_name(self):\n ops = [bitwise_operations.bit_subtract(\"bad_name\", 8, 16, 257, False, aerospike.BIT_OVERFLOW_FAIL, None)]\n\n with pytest.raises(e.BinNotFound):\n self.as_connection.operate(self.test_key, ops)",
"def negate_gate(wordlen, input='x', output='~x'):\n neg = bitwise_negate(wordlen, input, \"tmp\")\n inc = inc_gate(wordlen, \"tmp\", output)\n return neg >> inc",
"def subtract(a, b):\n return a - b",
"def subtract(a, b):\n return a - b",
"def getTwosComplement(raw_val, length):\n val = raw_val\n if raw_val & (1 << (length - 1)):\n val = raw_val - (1 << length)\n return val",
"def subtract(x: int, y: int):\n return x - y",
"def __sub__(self, tc):\n tc = TwosComplement(tc)._negative()\n return self.__add__(tc)",
"def subtract(x, y):\n return x - y",
"def subtract(x, y):\n return x - y",
"def subtract(x, y):\n return x - y",
"def sub64(a,b):\n return(np.subtract(a, b, dtype=np.uint64))",
"def subtract(x, y):\n\n return x - y",
"def subtract(*args):\n return args[0] - reduce(lambda x, y: x + y, args[1:])",
"def substraction_nocarry(a,b): #Beware, it is not commuative\n result = bytearray()\n carry = 0\n for byte1, byte2 in zip(a,b):\n byte_res = (byte1-byte2-carry)\n #print(byte_res)\n if byte_res < 0:\n carry = 1\n result.append(byte_res%256)\n else:\n carry = 0\n result.append(byte_res)\n return(result)",
"def test_bit_add_overflow_wrap(self):\n ops = [bitwise_operations.bit_add(self.five_255_bin, 0, 8, 1, False, aerospike.BIT_OVERFLOW_WRAP, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [255] * 4)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_get_negative_offset(self):\n ops = [bitwise_operations.bit_get(self.count_bin, -2, 2)]\n\n _, _, result = self.as_connection.operate(self.test_key, ops)\n\n expected_result = bytearray([192] * 1)\n assert result[self.count_bin] == expected_result",
"def subtract(self, other):\n return self.add(other.neg())",
"def __sub__(self,that):\n #return self.__opExpand1(that, np.subtract)\n return self.__opExpand2(that,np.subtract)",
"def subtract(a, b):\n print(\"SUBTRACTING %d - %d\" % (a, b))\n return a - b",
"def subtract(self, other=None, **units):\n if isinstance(other, (datetime, timedelta, relativedelta)):\n return self - other\n\n units = {unit: -units.get(unit, 0) for unit in SHIFT_UNITS}\n\n return self.shift(**units)"
] | [
"0.71338594",
"0.63404083",
"0.6331683",
"0.6260237",
"0.625121",
"0.61504817",
"0.6129522",
"0.60416776",
"0.56835353",
"0.5678757",
"0.56779814",
"0.5620698",
"0.55475885",
"0.55475885",
"0.5547116",
"0.5539497",
"0.54920566",
"0.5421593",
"0.5421593",
"0.5421593",
"0.53716356",
"0.53547007",
"0.53404033",
"0.5332772",
"0.5246184",
"0.52430993",
"0.52154094",
"0.52152497",
"0.52110106",
"0.51797825"
] | 0.7361038 | 0 |
Perform a bitwise xor op with bit_offset > bitmap. | def test_bit_xor_bit_offset_out_of_range(self):
value = bytearray()
value.append(8)
ops = [bitwise_operations.bit_xor(self.test_bin_ones, 41, 8, 1, value, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_xor_with_policy(self):\n value = bytearray([0])\n bit_policy = {\n \"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY,\n }\n ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, bit_policy)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def xor(a, b):",
"def xor_inplace(a,b):",
"def test_bit_xor(self):\n value = bytearray([1])\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def bitXor(img1, img2=None, mask = None):\n\tif img2 is None:\n\t\timg2 = img1\n\treturn cv2.bitwise_xor(img1, img2, mask=mask)",
"def bitwise_xor(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] ^ self.registers[register[1]])\n logger.info(\"Bitwise XOR on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def bitwise_xor(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_xor_op, other)",
"def xor_(l1, l2):\n return np.bitwise_xor(l1,l2)",
"def _xorReg(address, mask):\n _setReg(address, _getReg(address)^mask)",
"def xor(it):\n return 0 if it[0]==it[1] else 1",
"def convert_broadcast_logical_xor(node, **kwargs):\n return create_basic_op_node('Xor', node, kwargs)",
"def test_bit_xor_multiple_bytes(self):\n value = bytearray([8] * 5)\n ops = [bitwise_operations.bit_xor(self.five_255_bin, 0, 40, 5, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([247] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def test_bit_xor_multiple_bytes_value_unchanged(self):\n value = bytearray([0])\n ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def bitwise_xor(lhs, rhs):\n return _make.bitwise_xor(lhs, rhs)",
"def __xor__(self, obj):\n return self._boolean_operation(obj, operator.__xor__)",
"def xor_folding(self):\n lbs = round(self.bit_size / 2)\n cap = round(self.capacity / 2)\n\n fold_pos = round( len(self.filter) / 2 )\n\n a = self.filter[0:fold_pos]\n b = self.filter[fold_pos:]\n # print('======>',self.bit_size,'#',len(a),len(b))\n\n r = BloomFilter(cap=cap, fpr=self.false_positive_rate, bfpower=self.potencia, bs=lbs)\n r.filter = a.__ixor__(b)\n return r",
"def xor(self):\n\n \"\"\" fisrt i pick element we need to xor each other and put theme in list\"\"\"\n bits_to_xor = []\n for i in self.xor_input:\n bits_to_xor.append(self.state[i])\n\n \"\"\" next xor the list elemet usin reduce with lambda func.\"\"\"\n res = reduce(lambda x, y: x ^ y, bits_to_xor)\n return res",
"def xor(self, *args):\n return Xor(self, *args)",
"def test_bit_xor_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor_bit_size_too_large(self):\n value = bytearray([8] * 6)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 41, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def xor(data1=None, data2=None):\n\n return bytearray(a ^ b for a, b in zip(*map(bytearray, [data1, data2])))",
"def _xorSelection(self):\n\n self._console_output(\"XOR'ing selected bytes...\")\n self.ba.xor_patcher()",
"def __xor__(self, other):\r\n return self + other - 2 * self * other",
"def logical_xor(a, b):\n return bool(a) ^ bool(b)",
"def xor(m, i, j):\n for e in range(len(m[0])):\n m[j][e] ^= m[i][e]\n return m",
"def double_xor(it):\n\n return [xor(it[2*i:2*i+2]) for i in range(len(it)/2)]",
"def logical_xor(lhs, rhs):\n return _make.logical_xor(lhs, rhs)",
"def __xor__(self, other):\n a, b = Trits.match_length(self, other)\n return Trits([x ^ y for x, y in zip(a, b)])",
"def __xor__(self, y):\n result = self.clone()\n if isinstance(y, BinarySharedTensor):\n broadcast_tensors = torch.broadcast_tensors(result.share, y.share)\n result.share = broadcast_tensors[0].clone()\n elif is_tensor(y):\n broadcast_tensors = torch.broadcast_tensors(result.share, y)\n result.share = broadcast_tensors[0].clone()\n return result.__ixor__(y)",
"def f_xor(*args):\n f = Xor(*args).factor()\n return f if f in B else f.factor()"
] | [
"0.65985656",
"0.65077275",
"0.6500673",
"0.6443339",
"0.6437669",
"0.63780266",
"0.6351648",
"0.6344364",
"0.6307836",
"0.62951785",
"0.62089914",
"0.6118041",
"0.6113544",
"0.6078223",
"0.5945127",
"0.59304786",
"0.58627397",
"0.5844661",
"0.5823797",
"0.57821214",
"0.57653713",
"0.5755596",
"0.5748016",
"0.57332593",
"0.57114774",
"0.5701471",
"0.5700891",
"0.57003844",
"0.5694152",
"0.56939584"
] | 0.67272615 | 0 |
Perform a bitwise xor op with bit_size > value. | def test_bit_xor_bit_size_larger_than_value(self):
value = bytearray()
value.append(8)
ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 9, 1, value, None)]
with pytest.raises(e.InvalidRequest):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_xor_bit_size_too_large(self):\n value = bytearray([8] * 6)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 41, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor_with_policy(self):\n value = bytearray([0])\n bit_policy = {\n \"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY,\n }\n ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, bit_policy)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_or_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor_multiple_bytes_value_unchanged(self):\n value = bytearray([0])\n ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def test_bit_or_bit_size_too_large(self):\n value = bytearray([8] * 6)\n ops = [bitwise_operations.bit_or(self.test_bin_ones, 0, 41, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor(self):\n value = bytearray([1])\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def test_bit_xor_multiple_bytes(self):\n value = bytearray([8] * 5)\n ops = [bitwise_operations.bit_xor(self.five_255_bin, 0, 40, 5, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([247] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def bit_in_place(x, n):\n return (x & 2**n)",
"def xor(a, b):",
"def bitset(x, n, bv):\n if bv==1:\n x |= 2**n\n else:\n x ^= bit_in_place(x, n)\n return(x)",
"def test_bit_not_bit_size_too_large(self):\n ops = [bitwise_operations.bit_not(self.five_255_bin, 0, 41, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def bitwise_xor(lhs, rhs):\n return _make.bitwise_xor(lhs, rhs)",
"def test_bit_set_bit_value_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 48, 6, value, None)]\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_set_bit_bit_size_too_large(self):\n value = bytearray()\n value.append(255)\n ops = [bitwise_operations.bit_set(self.test_bin_zeroes, 0, 16, 1, value, None)]\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def encrypt_single_byte_xor(value, inputbyte):\r\n intIntputbyte = int(inputbyte)\r\n return bytes([b ^ intIntputbyte for b in bytes(value)])",
"def xor_folding(self):\n lbs = round(self.bit_size / 2)\n cap = round(self.capacity / 2)\n\n fold_pos = round( len(self.filter) / 2 )\n\n a = self.filter[0:fold_pos]\n b = self.filter[fold_pos:]\n # print('======>',self.bit_size,'#',len(a),len(b))\n\n r = BloomFilter(cap=cap, fpr=self.false_positive_rate, bfpower=self.potencia, bs=lbs)\n r.filter = a.__ixor__(b)\n return r",
"def __xor__(self, other):\n a, b = Trits.match_length(self, other)\n return Trits([x ^ y for x, y in zip(a, b)])",
"def __xor__(self, other):\n return MyCustomNumber(self.value ^ other.value)",
"def test_bit_remove_byte_size_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 0, 6, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_and_offset_value_byte_size_too_large(self):\n value = bytearray()\n for x in range(0, 5):\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 48, 6, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def xor_inplace(a,b):",
"def bitwise_xor(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_xor_op, other)",
"def __xor__(self, obj):\n return self._boolean_operation(obj, operator.__xor__)",
"def bitwise_xor(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] ^ self.registers[register[1]])\n logger.info(\"Bitwise XOR on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def test_bit_remove_byte_offset_with_byte_too_large(self):\n ops = [bitwise_operations.bit_remove(self.test_bin_zeroes, 3, 3, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def single_char_xor(input_bytes, char_value):\n keystring = struct.pack(\"B\", char_value)*len(input_bytes)\n #we reuse the bXor we implemented in problem #2\n return bXor(input_bytes, keystring)",
"def __setitem__(self, n, bit):\n self.num ^= (np.uint64(-bit) ^ self.num) & (UINT64_ONE << np.uint64(n))",
"def xor(self):\n\n \"\"\" fisrt i pick element we need to xor each other and put theme in list\"\"\"\n bits_to_xor = []\n for i in self.xor_input:\n bits_to_xor.append(self.state[i])\n\n \"\"\" next xor the list elemet usin reduce with lambda func.\"\"\"\n res = reduce(lambda x, y: x ^ y, bits_to_xor)\n return res",
"def xor(self, *args):\n return Xor(self, *args)"
] | [
"0.73067886",
"0.6601729",
"0.64713144",
"0.63067836",
"0.6222421",
"0.6178869",
"0.60622954",
"0.6051137",
"0.5981829",
"0.58503556",
"0.58304",
"0.57703584",
"0.57439303",
"0.57016945",
"0.5671008",
"0.5643629",
"0.56371194",
"0.56351",
"0.5610179",
"0.5597002",
"0.5594237",
"0.5585272",
"0.5562282",
"0.5546959",
"0.5541807",
"0.5541585",
"0.5513037",
"0.55124795",
"0.5506657",
"0.5503393"
] | 0.7796739 | 0 |
Perform a bitwise xor op with bit_size > bitmap. | def test_bit_xor_bit_size_too_large(self):
value = bytearray([8] * 6)
ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 41, 6, value, None)]
with pytest.raises(e.OpNotApplicable):
self.as_connection.operate(self.test_key, ops) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_bit_xor_bit_size_larger_than_value(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 9, 1, value, None)]\n\n with pytest.raises(e.InvalidRequest):\n self.as_connection.operate(self.test_key, ops)",
"def test_bit_xor_with_policy(self):\n value = bytearray([0])\n bit_policy = {\n \"bit_write_flags\": aerospike.BIT_WRITE_UPDATE_ONLY,\n }\n ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, bit_policy)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def xor(a, b):",
"def test_bit_xor(self):\n value = bytearray([1])\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def bitXor(img1, img2=None, mask = None):\n\tif img2 is None:\n\t\timg2 = img1\n\treturn cv2.bitwise_xor(img1, img2, mask=mask)",
"def test_bit_xor_multiple_bytes(self):\n value = bytearray([8] * 5)\n ops = [bitwise_operations.bit_xor(self.five_255_bin, 0, 40, 5, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([247] * 5)\n assert bins[self.five_255_bin] == expected_result",
"def xor_inplace(a,b):",
"def xor_(l1, l2):\n return np.bitwise_xor(l1,l2)",
"def bitwise_xor(lhs, rhs):\n return _make.bitwise_xor(lhs, rhs)",
"def convert_broadcast_logical_xor(node, **kwargs):\n return create_basic_op_node('Xor', node, kwargs)",
"def bitwise_xor(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_xor_op, other)",
"def xor_folding(self):\n lbs = round(self.bit_size / 2)\n cap = round(self.capacity / 2)\n\n fold_pos = round( len(self.filter) / 2 )\n\n a = self.filter[0:fold_pos]\n b = self.filter[fold_pos:]\n # print('======>',self.bit_size,'#',len(a),len(b))\n\n r = BloomFilter(cap=cap, fpr=self.false_positive_rate, bfpower=self.potencia, bs=lbs)\n r.filter = a.__ixor__(b)\n return r",
"def bitwise_xor(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] ^ self.registers[register[1]])\n logger.info(\"Bitwise XOR on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def xor(self):\n\n \"\"\" fisrt i pick element we need to xor each other and put theme in list\"\"\"\n bits_to_xor = []\n for i in self.xor_input:\n bits_to_xor.append(self.state[i])\n\n \"\"\" next xor the list elemet usin reduce with lambda func.\"\"\"\n res = reduce(lambda x, y: x ^ y, bits_to_xor)\n return res",
"def xor(it):\n return 0 if it[0]==it[1] else 1",
"def test_bit_xor_multiple_bytes_value_unchanged(self):\n value = bytearray([0])\n ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 5)\n assert bins[self.test_bin_zeroes] == expected_result",
"def xorbits(num1,num2):\n thingstoadd = []\n for i in range(31):\n bit1=setbit(num1,i)\n bit2=setbit(num2,i)\n bit1=shiftleft(bit1,31 - i)\n bit2=shiftleft(bit2,31 - i)\n bitsum=add(bit1,bit2)\n bitsum=shiftright(bitsum,31 - i)\n thingstoadd.append(bitsum)\n return sum(thingstoadd)",
"def test_bit_xor_bit_offset_out_of_range(self):\n value = bytearray()\n value.append(8)\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 41, 8, 1, value, None)]\n\n with pytest.raises(e.OpNotApplicable):\n self.as_connection.operate(self.test_key, ops)",
"def __xor__(self, other):\n a, b = Trits.match_length(self, other)\n return Trits([x ^ y for x, y in zip(a, b)])",
"def __xor__(self, obj):\n return self._boolean_operation(obj, operator.__xor__)",
"def _xorReg(address, mask):\n _setReg(address, _getReg(address)^mask)",
"def logical_xor(lhs, rhs):\n return _make.logical_xor(lhs, rhs)",
"def f_xor(*args):\n f = Xor(*args).factor()\n return f if f in B else f.factor()",
"def double_xor(it):\n\n return [xor(it[2*i:2*i+2]) for i in range(len(it)/2)]",
"def __xor__(self, y):\n result = self.clone()\n if isinstance(y, BinarySharedTensor):\n broadcast_tensors = torch.broadcast_tensors(result.share, y.share)\n result.share = broadcast_tensors[0].clone()\n elif is_tensor(y):\n broadcast_tensors = torch.broadcast_tensors(result.share, y)\n result.share = broadcast_tensors[0].clone()\n return result.__ixor__(y)",
"def xor(self, *args):\n return Xor(self, *args)",
"def logical_xor(a, b):\n return bool(a) ^ bool(b)",
"def __xor__(self, other):\r\n return self + other - 2 * self * other",
"def xor(m, i, j):\n for e in range(len(m[0])):\n m[j][e] ^= m[i][e]\n return m",
"def _xorSelection(self):\n\n self._console_output(\"XOR'ing selected bytes...\")\n self.ba.xor_patcher()"
] | [
"0.6650416",
"0.6514225",
"0.6504798",
"0.64670455",
"0.63607264",
"0.6328545",
"0.62608737",
"0.6258549",
"0.62444615",
"0.6225799",
"0.6198831",
"0.6184471",
"0.61594546",
"0.6144056",
"0.61243796",
"0.6093759",
"0.5990066",
"0.5982106",
"0.5820446",
"0.58060426",
"0.5798693",
"0.5780425",
"0.5774258",
"0.57727623",
"0.5760931",
"0.5723577",
"0.57168347",
"0.57109773",
"0.5698231",
"0.56951183"
] | 0.6932577 | 0 |
Perform a bitwise xor op with a policy. | def test_bit_xor_with_policy(self):
value = bytearray([0])
bit_policy = {
"bit_write_flags": aerospike.BIT_WRITE_UPDATE_ONLY,
}
ops = [bitwise_operations.bit_xor(self.test_bin_zeroes, 7, 8, 1, value, bit_policy)]
self.as_connection.operate(self.test_key, ops)
_, _, bins = self.as_connection.get(self.test_key)
expected_result = bytearray([0] * 5)
assert bins[self.test_bin_zeroes] == expected_result | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def xor(a, b):",
"def xor(self, *args):\n return Xor(self, *args)",
"def bitwise_xor(lhs, rhs):\n return _make.bitwise_xor(lhs, rhs)",
"def logical_xor(lhs, rhs):\n return _make.logical_xor(lhs, rhs)",
"def convert_broadcast_logical_xor(node, **kwargs):\n return create_basic_op_node('Xor', node, kwargs)",
"def __xor__(self, obj):\n return self._boolean_operation(obj, operator.__xor__)",
"def bitwise_xor(self, other: Any) -> ColumnOperators:\n\n return self.operate(bitwise_xor_op, other)",
"def __rxor__(self, other):\n return self.runtime.xor(self, other)",
"def test_bit_xor(self):\n value = bytearray([1])\n ops = [bitwise_operations.bit_xor(self.test_bin_ones, 0, 8, 1, value, None)]\n\n self.as_connection.operate(self.test_key, ops)\n\n _, _, bins = self.as_connection.get(self.test_key)\n expected_result = bytearray([0] * 1 + [1] * 4)\n assert bins[self.test_bin_ones] == expected_result",
"def bitwise_xor(self):\n register = self.return_middle_registers(self.opcode)\n self.registers[register[0]] = (\n self.registers[register[0]] ^ self.registers[register[1]])\n logger.info(\"Bitwise XOR on V{} and V{} for {}\".format(\n register[0],\n register[1],\n self.registers[register[0]]))",
"def xor(it):\n return 0 if it[0]==it[1] else 1",
"def xor_(l1, l2):\n return np.bitwise_xor(l1,l2)",
"def logical_xor(a, b):\n return bool(a) ^ bool(b)",
"def f_xor(*args):\n f = Xor(*args).factor()\n return f if f in B else f.factor()",
"def xor_inplace(a,b):",
"def __xor__(self, other):\r\n if self.field.characteristic == 2:\r\n return runtime.xor(self, other)\r\n\r\n return super().__xor__(other)",
"def __xor__(self, other):\n a, b = Trits.match_length(self, other)\n return Trits([x ^ y for x, y in zip(a, b)])",
"def __xor__(self, other):\r\n return self + other - 2 * self * other",
"def xor(a: bool, b: bool) -> bool:\n return (a and not b) or (not a and b)",
"def xor(self):\n\n \"\"\" fisrt i pick element we need to xor each other and put theme in list\"\"\"\n bits_to_xor = []\n for i in self.xor_input:\n bits_to_xor.append(self.state[i])\n\n \"\"\" next xor the list elemet usin reduce with lambda func.\"\"\"\n res = reduce(lambda x, y: x ^ y, bits_to_xor)\n return res",
"def func(plaintext, key):\n ciphertext = xor(plaintext, key)\n return ciphertext",
"def xor_network():\n # fmt: off\n tpm = np.array([\n [0, 0, 0],\n [0, 1, 1],\n [1, 0, 1],\n [1, 1, 0],\n [1, 1, 0],\n [1, 0, 1],\n [0, 1, 1],\n [0, 0, 0],\n ])\n cm = np.array([\n [0, 1, 1],\n [1, 0, 1],\n [1, 1, 0],\n ])\n # fmt: on\n return Network(tpm, cm=cm, node_labels=LABELS[:tpm.shape[1]])",
"def xor(data1=None, data2=None):\n\n return bytearray(a ^ b for a, b in zip(*map(bytearray, [data1, data2])))",
"def xor(data: bytes, key: bytes) -> bytes:\n key = key[: len(data)]\n int_var = int.from_bytes(data, _sys.byteorder)\n int_key = int.from_bytes(key, _sys.byteorder)\n int_enc = int_var ^ int_key\n return int_enc.to_bytes(len(data), _sys.byteorder)",
"def _XOR(integer1, integer2):\n _checkInt(integer1, minvalue=0, description='integer1')\n _checkInt(integer2, minvalue=0, description='integer2')\n\n return integer1 ^ integer2",
"def bitXor(img1, img2=None, mask = None):\n\tif img2 is None:\n\t\timg2 = img1\n\treturn cv2.bitwise_xor(img1, img2, mask=mask)",
"def bitwise_or(lhs, rhs):\n return _make.bitwise_or(lhs, rhs)",
"def xor(t1, t2):\n\n return [x ^ y for x, y in zip(t1, t2)]",
"def __xor__(self, other):\n return MyCustomNumber(self.value ^ other.value)",
"def test_bit_xor_bad_arg(self):\n value = 1\n ops = [bitwise_operations.bit_xor(\"bad_name\", 0, 8, 1, value, None)]\n\n with pytest.raises(e.ParamError):\n self.as_connection.operate(self.test_key, ops)"
] | [
"0.70831174",
"0.70623076",
"0.7059884",
"0.6676336",
"0.6656898",
"0.664496",
"0.66145754",
"0.64989746",
"0.6422519",
"0.6372238",
"0.6363608",
"0.6344332",
"0.63420236",
"0.6274215",
"0.6215274",
"0.6188354",
"0.61743647",
"0.6155858",
"0.61499715",
"0.6121868",
"0.6027265",
"0.59521604",
"0.5939882",
"0.5926742",
"0.5910949",
"0.5891061",
"0.58719486",
"0.5833461",
"0.5832976",
"0.5827075"
] | 0.7542527 | 0 |
Attempts to find a candidate layer to use for CAM extraction | def locate_candidate_layer(mod: nn.Module, input_shape: Tuple[int, ...] = (3, 224, 224)) -> Optional[str]:
# Set module in eval mode
module_mode = mod.training
mod.eval()
output_shapes: List[Tuple[Optional[str], Tuple[int, ...]]] = []
def _record_output_shape(module: nn.Module, input: Tensor, output: Tensor, name: Optional[str] = None) -> None:
"""Activation hook."""
output_shapes.append((name, output.shape))
hook_handles: List[torch.utils.hooks.RemovableHandle] = []
# forward hook on all layers
for n, m in mod.named_modules():
hook_handles.append(m.register_forward_hook(partial(_record_output_shape, name=n)))
# forward empty
with torch.no_grad():
_ = mod(torch.zeros((1, *input_shape), device=next(mod.parameters()).data.device))
# Remove all temporary hooks
for handle in hook_handles:
handle.remove()
# Put back the model in the corresponding mode
mod.training = module_mode
# Check output shapes
candidate_layer = None
for layer_name, output_shape in reversed(output_shapes):
# Stop before flattening or global pooling
if len(output_shape) == (len(input_shape) + 1) and any(v != 1 for v in output_shape[2:]):
candidate_layer = layer_name
break
return candidate_layer | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def find_CA_layer(arch, target_layer_name):\n\n hierarchy = target_layer_name.rsplit(\"_\",1)\n \n\n if target_layer_name == \"layer1\":\n return arch.layer1\n elif target_layer_name == \"layer2\":\n return arch.layer2\n elif target_layer_name == \"layer3\":\n return arch.layer3\n \n hierarchy = target_layer_name.rsplit(\"_\",1)\n \n if target_layer_name.rsplit(\"_\",1)[0] == \"maxpool_4\":\n target_layer = arch.maxpool_4\n \n elif target_layer_name.rsplit(\"_\",1)[0] == \"maxpool_5\":\n target_layer = arch.maxpool_5\n \n elif target_layer_name.rsplit(\"_\",1)[0] == \"maxpool_6\":\n target_layer = arch.maxpool_6\n \n if len(hierarchy) == 2:\n target_layer = target_layer[int(hierarchy[1])] \n\n return target_layer",
"def find_vgg_layer(arch, target_layer_name):\n if target_layer_name is None:\n target_layer_name = 'features'\n\n hierarchy = target_layer_name.split('_')\n\n if len(hierarchy) >= 1:\n target_layer = arch.features\n else:\n return None\n\n if len(hierarchy) == 2:\n target_layer = target_layer[int(hierarchy[1])]\n\n return target_layer",
"def find_ResNet_layer(arch, target_layer_name):\n\n hierarchy = target_layer_name.rsplit(\"_\",1)\n \n\n if target_layer_name.rsplit(\"_\",1)[0] == \"layer1\":\n target_layer = arch.layer1\n elif target_layer_name.rsplit(\"_\",1)[0] == \"layer2\":\n target_layer = arch.layer2\n elif target_layer_name.rsplit(\"_\",1)[0] == \"layer3\":\n target_layer = arch.layer3\n elif target_layer_name.rsplit(\"_\",1)[0] == \"layer4\":\n target_layer = arch.layer4\n \n# print(target_layer)\n if len(hierarchy) == 2:\n target_layer = target_layer[int(hierarchy[1])]\n\n return target_layer",
"def findLayer(job, layer):\n return Layer(Cuebot.getStub('layer').FindLayer(\n job_pb2.LayerFindLayerRequest(job=job, layer=layer), timeout=Cuebot.Timeout).layer)",
"def _get_conv_pair(self, match_layer):\n return None, None",
"def singleLayerFind(self, method: Finder, layer: int = 0):\n prepared_image = None\n if len(self.image.shape) > 2: # atleast 3 dimesions in array e.g 100,100,5\n if self.image.shape[0] > self.image.shape[2]: # one image array with multi samples e.g 100,100,5\n if self.image.shape[2] > layer: # check sample that exists\n prepared_image = self.image[:, :, layer]\n else:\n print('sample:', layer, ' out of bounds:', self.image.shape[2],\n 'from the following multi sample image', self.image.shape)\n return\n elif self.image.shape[0] < self.image.shape[2]: # image with more than one layer e.g 5,100,100\n if self.image.shape[0] > layer: # check layer exisits\n prepared_image = self.image[layer]\n else:\n print('layer:', layer, ' out of bounds:', self.image.shape[0],\n 'from the following multi layer image', self.image.shape)\n return\n else:\n print('Unrecognised dimesnsions:', self.image.shape)\n elif len(self.image.shape) == 2: # basic 2 dimesional array\n prepared_image = self.image\n else:\n print('invalid dimensions in image', self.image.shape)\n return\n\n if prepared_image is None:\n print('something went wrong')\n\n self.locations, self.intermediaryImage = method.findInImage(prepared_image)\n return self.locations, self.intermediaryImage",
"def find_1dcnn_layer(arch, target_layer_name):\n\n hierarchy = target_layer_name.rsplit(\"_\",1)\n \n\n if target_layer_name.rsplit(\"_\",1)[0] == \"conv_1\":\n target_layer = arch.conv_1\n elif target_layer_name.rsplit(\"_\",1)[0] == \"conv_2\":\n target_layer = arch.conv_2\n elif target_layer_name.rsplit(\"_\",1)[0] == \"conv_3\":\n target_layer = arch.conv_3\n elif target_layer_name.rsplit(\"_\",1)[0] == \"maxpool_4\":\n target_layer = arch.maxpool_4\n \n elif target_layer_name.rsplit(\"_\",1)[0] == \"maxpool_5\":\n target_layer = arch.maxpool_5\n \n elif target_layer_name.rsplit(\"_\",1)[0] == \"maxpool_6\":\n target_layer = arch.maxpool_6\n \n elif target_layer_name == \"conv1\":\n target_layer = arch.conv1\n elif target_layer_name == \"conv2\":\n target_layer = arch.conv2\n elif target_layer_name == \"conv3\":\n target_layer = arch.conv3\n# print(target_layer)\n if len(hierarchy) == 2:\n target_layer = target_layer[int(hierarchy[1])]\n\n return target_layer",
"def locate_linear_layer(mod: nn.Module) -> Optional[str]:\n candidate_layer = None\n for layer_name, m in mod.named_modules():\n if isinstance(m, nn.Linear):\n candidate_layer = layer_name\n break\n\n return candidate_layer",
"def request_layers(url):\n layer_names = get_layers(url)\n for l in layer_names:\n print(\"Checking '%s'...\" % l)\n get_image(url, l, check_blank=True)",
"def find_layer_from_name(self, name):\n try:\n _first, *others = filter(lambda x: x.Name == name, self._file3dm.Layers)\n if others:\n raise ReferenceError(\n \"There are more than one layers with \" f\"the name '{name}'\"\n )\n return _first\n except ValueError:\n return None",
"def FindLayer(self, *args):\n return _XCAFDoc.XCAFDoc_LayerTool_FindLayer(self, *args)",
"def try_to_use_existing_tile(self, tx, ty, tz):\n for image_format in self.image_formats:\n if os.path.exists(self.get_full_path(tx, ty, tz, format_extension[image_format])):\n return image_format\n return None",
"def find_layer_from_fullpath(self, full_path):\n try:\n _layer, *_ = filter(lambda x: x.FullPath == full_path, self._file3dm.Layers)\n return _layer\n except ValueError:\n return None",
"def find_trainable_layer(self, layer):\n if layer.__class__.__name__ == 'TimeDistributed':\n return self.find_trainable_layer(layer.layer)\n return layer",
"def find_layer_from_id(self, id):\n try:\n _layer, *_ = filter(lambda x: x.Id == id, self._file3dm.Layers)\n return _layer\n except ValueError:\n return None",
"def get_layer(model, layer_name=None, layer_idx=None):\n\n _validate_args(layer_name, layer_idx, layer=None)\n if layer_idx is not None:\n return model.layers[layer_idx]\n\n layer = [layer for layer in model.layers if layer_name in layer.name]\n if len(layer) > 1:\n print(warn_str + \"multiple matching layer names found; \"\n + \"picking earliest\")\n elif len(layer) == 0:\n raise Exception(\"no layers found w/ names matching \"\n + \"substring: '%s'\" % layer_name)\n return layer[0]",
"def find_layer_by_name(self, layer_name):\n return next(x for x in self.layers if x.name == layer_name)",
"def get_layer(self, layer_id):\n (layer_class, layer_name, dim, \n dropout_prob, dropout_scale) = self.select_layer(layer_id)\n if layer_class == 'maxout':\n (num_units,\n num_pieces,\n pool_stride,\n randomize_pools,\n irange,\n sparse_init,\n sparse_stdev,\n include_prob,\n init_bias,\n W_lr_scale,\n b_lr_scale,\n max_col_norm,\n max_row_norm) = self.select_layer_maxout(layer_id)\n layer = Maxout(num_units,\n num_pieces,\n pool_stride,\n randomize_pools,\n irange,\n sparse_init,\n sparse_stdev,\n include_prob,\n init_bias,\n W_lr_scale,\n b_lr_scale,\n max_col_norm,\n max_row_norm)\n elif layer_class == 'linear':\n (init_id, init_bias, \n W_lr_scale, b_lr_scale, \n max_row_norm, max_col_norm) = self.select_layer_linear(layer_id)\n init_weights = self.get_init(init_id)\n layer = Linear(dim=dim, layer_name=layer_name, \n init_weights=init_weights, init_bias=init_bias,\n W_lr_scale=W_lr_scale, b_lr_scale=b_lr_scale, \n max_row_norm=max_row_norm, \n max_col_norm=max_col_norm)\n elif layer_class == 'tanh':\n (init_id, init_bias, \n W_lr_scale, b_lr_scale, \n max_row_norm, max_col_norm) = self.select_layer_tanh(layer_id)\n init_weights = self.get_init(init_id)\n layer = Tanh(dim=dim, layer_name=layer_name, \n init_weights=init_weights, init_bias=init_bias,\n W_lr_scale=W_lr_scale, b_lr_scale=b_lr_scale, \n max_row_norm=max_row_norm, \n max_col_norm=max_col_norm)\n elif layer_class == 'sigmoid':\n (init_id, init_bias, \n W_lr_scale, b_lr_scale, \n max_row_norm, max_col_norm) \\\n = self.select_layer_sigmoid(layer_id) \n init_weights = self.get_init(init_id)\n layer = Sigmoid(dim=dim, layer_name=layer_name, \n init_weights=init_weights, init_bias=init_bias,\n W_lr_scale=W_lr_scale, b_lr_scale=b_lr_scale, \n max_row_norm=max_row_norm, \n max_col_norm=max_col_norm)\n elif layer_class == 'softmaxpool':\n (detector_layer_dim, pool_size,\n\t init_id, init_bias,\n\t W_lr_scale, b_lr_scale) \\\n = self.select_layer_softmaxpool(layer_id) \n init_weights = self.get_init(init_id)\n layer = SoftmaxPool(detector_layer_dim=detector_layer_dim, \n layer_name=layer_name, pool_size=pool_size,\n init_weights=init_weights, init_bias=init_bias,\n W_lr_scale=W_lr_scale, b_lr_scale=b_lr_scale)\n elif layer_class == 'softmax':\n (init_id, init_bias, \n W_lr_scale, b_lr_scale, \n max_row_norm, max_col_norm) \\\n = self.select_layer_softmax(layer_id) \n init_weights = self.get_init(init_id)\n layer = Softmax(dim=dim, layer_name=layer_name, \n init_weights=init_weights, init_bias=init_bias,\n W_lr_scale=W_lr_scale, b_lr_scale=b_lr_scale, \n max_row_norm=max_row_norm, \n max_col_norm=max_col_norm)\n elif layer_class == 'rectifiedlinear':\n (init_id, init_bias, \n W_lr_scale, b_lr_scale, \n max_row_norm, max_col_norm,\n left_slope) = self.select_layer_rectifiedlinear(layer_id) \n init_weights = self.get_init(init_id)\n layer = RectifiedLinear(dim=dim, layer_name=layer_name, \n init_weights=init_weights, init_bias=init_bias,\n W_lr_scale=W_lr_scale, b_lr_scale=b_lr_scale, \n max_row_norm=max_row_norm, \n max_col_norm=max_col_norm, left_slope=left_slope)\n elif layer_class == 'convrectifiedlinear':\n (output_channels, kernel_shape, pool_shape,\n pool_stride, border_mode, init_id,\n init_bias, W_lr_scale,\n b_lr_scale, left_slope,\n max_kernel_norm) \\\n = self.select_layer_convrectifiedlinear(layer_id) \n init_weights = self.get_init(init_id)\n layer = ConvRectifiedLinear(output_channels=output_channels,\n kernel_shape=(kernel_shape, kernel_shape),\n pool_shape=(pool_shape, pool_shape),\n pool_stride=(pool_stride, pool_stride),\n layer_name=layer_name, init_weights=init_weights, \n init_bias=init_bias,\n W_lr_scale=W_lr_scale, b_lr_scale=b_lr_scale, \n max_kernel_norm=max_kernel_norm, \n left_slope=left_slope)\n layer.dropout_prob = dropout_prob\n layer.dropout_scale= dropout_scale\n return layer",
"def extract_face(seq):\n img, locations = extract_image(seq)\n if img is None:\n # No frame with a face was found.\n return None\n else:\n # We found a frame with a face.\n # If there are multiple faces, choose the largest.\n loc = get_largest_face(locations)\n cropped = crop_face(img, loc, ZOOMOUT_FACTOR)\n return cropped",
"def find_initial_position(img1, img2):\n # find points of interest in points\n img1_kp, img1_des = compute_orb(img1)\n img2_kp, img2_des = compute_orb(img2)\n\n # get closest 2 matches per point\n bf = cv2.BFMatcher(normType=cv2.NORM_HAMMING)\n matches = bf.knnMatch(img1_des, img2_des, k=2)\n\n good_matches = []\n pts1 = []\n pts2 = []\n # Lowe's ratio test\n for m, n in matches:\n if m.distance < 0.75*n.distance:\n good_matches.append(m)\n pts1.append(img1_kp[m.queryIdx].pt)\n pts2.append(img2_kp[m.trainIdx].pt)\n\n pts1 = np.float32(pts1)\n pts2 = np.float32(pts2)\n\n # essential matrix gives the motion of the points\n # to get motion of the camera, flip the inputs between pts1 and pts2\n essential_matrix, e_mask = cv2.findEssentialMat(pts2, pts1, intrinsic_camera_matrix)\n\n # select only inlier points as per the RANSAC method\n pts1 = pts1[e_mask.ravel() == 1]\n pts2 = pts2[e_mask.ravel() == 1]\n\n _, rotation, translation, mask, triangulated_points = cv2.recoverPose(essential_matrix, pts2, pts1, intrinsic_camera_matrix, distanceThresh=50)\n triangulated_points = np.asarray([np.divide(triangulated_points[0], triangulated_points[3]),\n np.divide(triangulated_points[1], triangulated_points[3]),\n np.divide(triangulated_points[2], triangulated_points[3])]).transpose()\n\n CAMERA_POSES.clear()\n CAMERA_POSES.append(np.hstack((np.identity(3), np.array([[0], [0], [0]]))))\n CAMERA_POSES.append(np.hstack((rotation, translation)))\n return rotation, translation, triangulated_points",
"def _get_resnet_fc_layer(self):\n\t\tlayer_iterator = ww.WeightWatcher().make_layer_iterator(self.model)\n\t\tfc_layer= None\n\t\tfor ww_layer in layer_iterator:\n\t\t\tprint(ww_layer.name)\n\t\t\tif ww_layer.name=='fc':\n\t\t\t\tfc_layer = ww_layer\n\t\t\n\t\treturn fc_layer",
"def get_features(img1,mask1, depth1):\n colors = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)\n img3 = img1.copy()\n img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n img1 = clahe.apply(img1) # Applying Clahe\n kp, des = orb.detectAndCompute(img1, mask=mask1) # Computing ORB features\n kp_pts = np.float32([ kp[m].pt for m in range(len(kp))]).reshape(-1,2)\n # Getting Colors\n col = []\n for i in range(len(kp)):\n col.append(colors[kp_pts[i,1].astype(int), kp_pts[i,0].astype(int)])\n col = np.array(col)\n # Getting 2D points\n kp_2d = []\n for m in range(len(kp)):\n kp_2d.append([int(kp[m].pt[0]), int(kp[m].pt[1])])\n kp_2d = np.array(kp_2d).reshape(-1,2)\n \n # Getting the 3D points\n kp_3d, _, _ = convert_3d(kp_2d, depth1, img3)\n \n # Removing points with Zero depth\n my_ind = np.where(kp_3d[:,2]!=0)[0]\n new_kp_3d = kp_3d[my_ind,:]\n new_kp_2d = kp_2d[my_ind,:]\n new_des = des[my_ind,:]\n new_col = col[my_ind,:]\n \n # Removing the duplicates\n uni_3d = np.unique(new_kp_3d, return_index= True, axis=0)[1]\n new_kp_3d1 = new_kp_3d[uni_3d,:]\n new_kp_2d1 = new_kp_2d[uni_3d,:]\n new_des1 = new_des[uni_3d,:]\n new_col1 = new_col[uni_3d,:]\n return kp_3d, kp_2d, des, col",
"def get_layer(self, l):\n\n if l == 0:\n return self.input_layer\n elif 0 < l < self.num_layers() - 1:\n return self.hidden_layers[l - 1]\n elif l == self.num_layers() - 1:\n return self.output_layer\n else:\n return None",
"def _get_layers(self) :\n \n return self._layers",
"def getLayer(uniq):\n return Layer(Cuebot.getStub('layer').GetLayer(\n job_pb2.LayerGetLayerRequest(id=uniq), timeout=Cuebot.Timeout).layer)",
"def closest_card(model, img):\r\n features = preprocess(img)\r\n closest_match = sorted(model.values(), key=lambda x: img_compare(x[1], features))[0]\r\n return closest_match[0]",
"def find_cloud_layers(example_dict, min_path_kg_m02, for_ice=False):\n\n error_checking.assert_is_greater(min_path_kg_m02, 0.)\n error_checking.assert_is_boolean(for_ice)\n\n if for_ice:\n path_matrix_kg_m02 = get_field_from_dict(\n example_dict=example_dict, field_name=UPWARD_ICE_WATER_PATH_NAME\n )\n else:\n path_matrix_kg_m02 = get_field_from_dict(\n example_dict=example_dict, field_name=UPWARD_LIQUID_WATER_PATH_NAME\n )\n\n path_diff_matrix_kg_m02 = numpy.diff(path_matrix_kg_m02, axis=1, prepend=0.)\n\n num_examples = path_matrix_kg_m02.shape[0]\n cloud_mask_matrix = numpy.full(path_matrix_kg_m02.shape, False, dtype=bool)\n cloud_layer_counts = numpy.full(num_examples, 0, dtype=int)\n\n for i in range(num_examples):\n these_diffs = path_diff_matrix_kg_m02[i, :] + 0.\n\n if for_ice:\n these_diffs[these_diffs <= 1e9] = 0\n else:\n these_diffs[these_diffs <= 1e6] = 0\n\n these_start_indices, these_end_indices = _find_nonzero_runs(\n path_diff_matrix_kg_m02[i, :]\n )\n\n this_num_layers = len(these_start_indices)\n\n for j in range(this_num_layers):\n this_path_kg_m02 = numpy.sum(\n path_diff_matrix_kg_m02[\n i, these_start_indices[j]:(these_end_indices[j] + 1)\n ]\n )\n\n if this_path_kg_m02 < min_path_kg_m02:\n continue\n\n cloud_layer_counts[i] += 1\n cloud_mask_matrix[\n i, these_start_indices[j]:(these_end_indices[j] + 1)\n ] = True\n\n return cloud_mask_matrix, cloud_layer_counts",
"def image_decoder(x,y,layers_ls):\n for layer in layers_ls:\n if layer.loc[x,y]=='1':\n return int(1)\n elif layer.loc[x,y]=='0':\n return int(0)\n return int(2)",
"def get_layer(key):\n layer1 = {'gm': u'Global_Projection', 'np': u'North_Polar_Projection', 'radar': u'Sigma0_Data', 'flag': u'flag'}\n return layer1[key]",
"def getCarLocation():\n cams = CAMS\n img1, img2 = cams[0].getImage(), cams[1].getImage()\n potint1op, point2op = GetBalloonOld.getCar(img1), GetBalloonOld.getCar(\n img2)\n for j in range(len(point1op)):\n point1op[j] = np.array(np.array([point1op[j][0], point1op[j][1]]))\n for j in range(len(point2op)):\n point2op[j] = np.array(np.array([point2op[j][0], point2op[j][1]]))\n if len(point1op) == 0 or len(point2op) == 0:\n return None\n points = [[point1op[0]], [point2op[0]]]\n car = getTargetsPlaces(copy.deepcopy(points))[0]\n diff = abs(car[2] - CAR_Z)\n for op1 in point1op:\n for op2 in point2op:\n testPoint = [[op1], [op2]]\n testCar = getTargetsPlaces(copy.deepcopy(testPoint))[0]\n testDiff = abs(testCar[2] - CAR_Z)\n if testDiff < diff:\n diff = testDiff\n car = testCar\n return car"
] | [
"0.62724084",
"0.6052908",
"0.5938766",
"0.5923088",
"0.58682144",
"0.5823416",
"0.5793721",
"0.5652858",
"0.56480765",
"0.5600004",
"0.55514055",
"0.55042034",
"0.5492678",
"0.54090405",
"0.53978735",
"0.53533643",
"0.53379434",
"0.5288922",
"0.52618504",
"0.5260588",
"0.5244236",
"0.52197355",
"0.5214398",
"0.52114433",
"0.5193849",
"0.5176338",
"0.51758367",
"0.51500416",
"0.5145672",
"0.5122566"
] | 0.6229697 | 1 |
Returns the asset with the given id. | def get_asset(self, asset_id):
text, code = ApiClient(self._config, 'assets/' + asset_id).get()
return Asset.deserialize(text) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_asset(self, asset_id):\n endpoint = '/assets/{}'.format(asset_id)\n return self._api_call('get', endpoint)",
"def asset(self, asset_id):\n headers, items = self._get('/asset/%s' % asset_id)\n return Asset.fromdict(items[0], api=self, full=True)",
"def get_asset(self, asset_id, asset_type):\n return self.asset(asset_id, asset_type=asset_type)",
"def retrieveAsset(self, assetId):\n return self.get_json('/asset/%s' % assetId)",
"def get_asset(self, id):\n\n if not isinstance(id, six.string_types):\n raise ValueError('Param \"id\" must be a str|unicode.')\n\n asset = self.stub.get_asset(opac_pb2.TaskId(id=id))\n\n return {\n 'file': asset.file,\n 'filename': asset.filename,\n 'type': asset.type,\n 'metadata': asset.metadata,\n 'task_id': asset.task_id\n }",
"def retrieve_asset(self, sid, default_none=False):\n try:\n asset = self._asset_cache[sid]\n if asset is None and not default_none:\n raise SidsNotFound(sids=[sid])\n return asset\n except KeyError:\n return self.retrieve_all((sid,), default_none=default_none)[0]",
"def get_asset(self, name):\n assert self.has_asset(name), \"Asset is not created yet, use has_asset for checking\"\n return self.assets[name]",
"def getAssetWithName(self, name):\n return self.__assets[name]",
"def image_by_id(self, id):\n if not id:\n return None\n return next((image for image in self.images() if image['Id'] == id),\n None)",
"def get_url_asset(self, asset_id):\n return self.get_asset(asset_id, 'URL')",
"def retrieve_asset(self, site_id: Identifier, asset_id: Identifier\n ) -> Asset:\n try:\n site = self._registry_client.get_site_by_id(site_id)\n except KeyError:\n raise RuntimeError(f'Site or store at site {site_id} not found')\n\n if site.has_store:\n safe_asset_id = quote(asset_id, safe='')\n r = requests.get(\n f'{site.endpoint}/assets/{safe_asset_id}',\n params={'requester': self._site},\n verify=self._verify, cert=self._cred)\n if r.status_code == 404:\n raise KeyError('Asset not found')\n elif not r.ok:\n raise RuntimeError('Server error when retrieving asset')\n\n asset_json = r.json()\n validate_json('Asset', asset_json)\n return deserialize(Asset, asset_json)\n\n raise ValueError(f'Site {site_id} does not have a store')",
"def get_by_id(cls, id):\n return cls.query().get(id)",
"def get_by_id(cls, id):\n e = api.get([key.Key(cls.__name__, id)])\n if e:\n return cls.from_entity(e[0])\n raise ObjectDoesNotExist",
"def get_asset(location, filename):\r\n return contentstore().find(Transcript.asset_location(location, filename))",
"def getItem(self, id):\n path = 'item/' + id\n return self.sendRestRequest('GET', path)",
"def _get_image(self, asset_id):\n try:\n return self.app.module_map.uploader.get(asset_id)\n except AssetNotFound:\n return None\n except Exception, e:\n return None\n return None",
"def get_object(self, id_):\n return self._objects.get(id_, None)",
"def get_image_by_id(id):\n return Image.objects.get(id=id)",
"def getbyid(self, id):\n\n return esd.retrieve(id)",
"def get(self, id):\n file = (\n self.drive.files()\n .get(\n fileId=id,\n fields=\"id, name\",\n supportsAllDrives=self.shared_drive[0],\n )\n .execute()\n )\n return file",
"def get_handle_asset(self, asset_id):\n return self.get_asset(asset_id, 'HANDLE')",
"def get_image_by_id(id):\n return ImageModel.query.filter(ImageModel.id == id) \\\n .first()",
"def get_asset_info(self, id):\n\n if not isinstance(id, six.string_types):\n msg = 'Param id must be a str|unicode.'\n logger.exception(msg)\n raise ValueError(msg)\n\n asset_info = self.stub.get_asset_info(opac_pb2.TaskId(id=id))\n\n return {\n 'url': asset_info.url,\n 'url_path': asset_info.url_path\n }",
"def get_asset(self, short_name):\n return self._assets[short_name]",
"def get_volume_by_id(self, id):\n for vol in self.conn.volumes:\n if vol.id == id:\n return vol\n raise KeyError(\"Volume with ID \" + id + \" not found\")",
"def get(cls, id):\n\n return cls.query.get(id)",
"def get(cls, id):\n\n return cls.query.get(id)",
"def find(self, id):\n response = self._connection.session.get(self.url + \"/%s\" % id)\n return self._raise_or_return_json(response)",
"def _get_file_by_id(id):\n query = \"\"\"SELECT * FROM files WHERE id = (:id) LIMIT 1\"\"\"\n param_obj = {'id': id}\n return _execute(query, param_obj)",
"def asset_info(self, asset_id):\n response = self._client.get('workbenches/assets/%(asset_id)s/info',\n path_params={'asset_id': asset_id})\n return AssetInfo.from_dict(loads(response.text).get('info'))"
] | [
"0.86297536",
"0.8100816",
"0.7962342",
"0.7741411",
"0.74044025",
"0.7134656",
"0.7062719",
"0.7001603",
"0.68088776",
"0.67893684",
"0.6752635",
"0.6658891",
"0.6634489",
"0.6628158",
"0.6605129",
"0.66020226",
"0.6591007",
"0.6567516",
"0.6552751",
"0.6544386",
"0.6536535",
"0.6534889",
"0.6471511",
"0.64346874",
"0.63992083",
"0.6397355",
"0.6397355",
"0.6319953",
"0.6291755",
"0.62908626"
] | 0.85032684 | 1 |
Obtains Marketplace object given its ID. | def get_marketplace(self, marketplace_id):
return MarketplaceResource(self._config).get(marketplace_id) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_place_by_id(id):\n rv = query_db('select * from places where place_id = ?',\n [id])\n return rv[0] if rv else None",
"def get_object(self, id_):\n return self._objects.get(id_, None)",
"def get_place_by_id(place_id):\n place_obj = storage.get(\"Place\", place_id)\n if place_obj is None:\n abort(404)\n place_dict = place_obj.to_dict()\n return jsonify(place_dict)",
"def get_place(place_id):\n place = storage.get('Place', place_id)\n if place is None:\n abort(404)\n return (jsonify(place.to_json()))",
"def get_place(place_id):\n place = storage.get(Place, place_id)\n if place is None:\n abort(404)\n else:\n return jsonify(place.to_dict())",
"def get_place(place_id):\n place = storage.get(\"Place\", place_id)\n if not place:\n abort(404)\n return jsonify(place.to_dict())",
"def place_by_id(place_id):\n place = storage.get(Place, place_id)\n if place is None:\n abort(404)\n return jsonify(place.to_dict())",
"def get_by_id(cls, id):\n e = api.get([key.Key(cls.__name__, id)])\n if e:\n return cls.from_entity(e[0])\n raise ObjectDoesNotExist",
"def getPlace(place_id):\n place = storage.get(\"Place\", place_id)\n if place is None:\n abort(404)\n return jsonify(place.to_dict())",
"def get_by_id(cls, id):\n return cls.query().get(id)",
"def get_object(self, ObjectClass, id):\n try:\n object = ObjectClass.objects.get(id=id)\n except (ObjectClass.DoesNotExist, ObjectClass.MultipleObjectsReturned):\n object = None\n return object",
"def get_object(id):",
"def get(cls, id):\n\n return cls.query.get(id)",
"def get(cls, id):\n\n return cls.query.get(id)",
"def get_by_id(cls, id):\n try:\n return cls.objects.get(id=id)\n except(IntegrityError, OperationalError):\n return None",
"def get_by_id(cls, item_id):\n return db_session.query(cls).filter(cls.id == item_id).first()",
"def get_object(self, id=None):\n if id is None and self.kwargs.get('field') == 'id':\n id = self.kwargs.get('constraint')\n self.object = self.get_model_obj().objects.get(pk=id)\n return self.object",
"def find_by_id(id):\n query = \"SELECT * FROM parcels WHERE id=%s\"\n return db.find_one(query, (id,))",
"def get_object(self):\n pk = self.kwargs.get('id')\n return get_object_or_404(Book, pk=pk)",
"def get(self, id):\n return self.__model__.query.get(id)",
"def get_product_by_id(pid: int) -> Optional[Product]:\n return get_market().get_product(pid)",
"def find_by_id(cls, iid: int):\n return cls.query.filter_by(id=iid).first()",
"def get_by_id(cls, id):\n return db.session.query(cls).get(id)",
"def get_trade(self, id: int) -> TradeOffer | None:\n return self._connection.get_trade(id)",
"def get_object(self, object_id):\r\n model = self.model\r\n object_id = model._meta.pk.to_python(object_id)\r\n return self.queryset().get(pk=object_id)",
"def get_by_id(self, id):\n return Entry.all().filter('entry_id = ', id).get()",
"def getItem(self, id):\n path = 'item/' + id\n return self.sendRestRequest('GET', path)",
"def get(self, id):\n return Entry.query.filter(Entry.id == id).one()",
"def get_by_id(self, id: int):\n\n\t\traise NotImplemented",
"def find(cls, id=None):\n return cls.query.filter_by(id=id).one_or_none()"
] | [
"0.6927319",
"0.6671522",
"0.664275",
"0.66377103",
"0.662131",
"0.6612834",
"0.6585188",
"0.65535146",
"0.64867014",
"0.6379136",
"0.6267908",
"0.62560844",
"0.61420566",
"0.61420566",
"0.6021101",
"0.6012841",
"0.60083824",
"0.59366053",
"0.592935",
"0.59106505",
"0.590253",
"0.59019446",
"0.5876346",
"0.58665043",
"0.5853277",
"0.5850119",
"0.5843091",
"0.582645",
"0.58260953",
"0.5811495"
] | 0.78990203 | 0 |
List the tier configs. | def list_tier_configs(self, filters=None):
query = self._get_filters_query(filters, True)
text, code = ApiClient(self._config, 'tier/configs' + query.compile()).get()
return TierConfig.deserialize(text) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"async def getTiers(self, ctx):\n server_dict = self.get_server_dict(ctx)\n tierList = server_dict.setdefault(\"Tiers\", [])\n\n if(len(tierList) > 0):\n await self.bot.say(\"Tiers:\")\n for tier in tierList:\n await self.bot.say(tier)\n else:\n await self.bot.say(\":x: No tiers in tier list\")",
"def configure_tiers(self, datacenter, tier):\n print \"Enabling tier %s...\" % tier\n tiers = datacenter.listTiers()\n\n tiers[0].setName(tier)\n tiers[0].update()\n\n for i in range(1, 4):\n tiers[i].setEnabled(False)\n tiers[i].update()\n\n return tiers[0]",
"def list_config():\n console = Console()\n _config = loadConfig()\n json_data = richJSON.from_data({**asdict(_config)})\n console.print(Panel(json_data, title=\"SubmarineCliConfig\"))",
"def get_tier_config(self, tier_config_id):\n text, code = ApiClient(self._config, 'tier/configs/' + tier_config_id).get()\n return TierConfig.deserialize(text)",
"def antenny_list_configs(self):\n return self.antenny_config.list_configs()",
"def tier(self):\n\n if not hasattr(self, \"_tier\"):\n self._tier = self.opts.get(\"tier\")\n return self._tier",
"def list(self):\n for item in self._config:\n item.list()",
"def handle_tier_list():\n return jsonify(db.all())",
"def tier(self) -> str:\n return pulumi.get(self, \"tier\")",
"def tier(self) -> str:\n return pulumi.get(self, \"tier\")",
"def tier(self) -> str:\n return pulumi.get(self, \"tier\")",
"def tier(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"tier\")",
"def tier(self):\n return self._tier",
"def list_conf(self, kwargs):\n self.display(\n self.engine.query(\n self.engine.ALL_FILTER(),\n ALL, base=','.join([\"CN=Configuration\", self.engine.base_dn])\n ),\n True\n )",
"def list(obj):\n # lists pf9-express config files\n pf9_exp_conf_dir = obj['pf9_exp_conf_dir']\n\n if os.path.exists(pf9_exp_conf_dir):\n count = 1\n result = PrettyTable()\n result.field_names = [\"#\",\"Active\", \"Conf\", \"Management Plane\", \"Region\"]\n files = [f for f in os.listdir(pf9_exp_conf_dir) if os.path.isfile(os.path.join(pf9_exp_conf_dir, f))]\n\n for f in files:\n active = False\n if f == 'express.conf':\n active = True\n with open(pf9_exp_conf_dir + f, 'r') as config_file:\n config = Utils().config_to_dict(config_file)\n if active:\n result.add_row([count,'*', config[\"name\"], config[\"du_url\"], config[\"os_region\"]])\n else:\n result.add_row([count,' ', config[\"name\"], config[\"du_url\"], config[\"os_region\"]])\n count = count + 1\n\n click.echo(result)\n\n else:\n click.echo('No Platform9 management plane configs exist')",
"def list_subnets(self, kwargs):\n verbose = kwargs.get(\"verbose\", False)\n\n if not verbose:\n attributes = [\"distinguishedName\", \"name\", \"description\"]\n else:\n attributes = ALL\n\n if verbose:\n self.display(\n self.engine.query(\n self.engine.SITES_FILTER(),\n attributes, base=','.join([\"CN=Configuration\", self.engine.base_dn])\n ),\n verbose\n )\n else:\n entries = self.engine.query(self.engine.SITES_FILTER(), attributes, base=','.join([\"CN=Configuration\", self.engine.base_dn]))\n\n site_dn = \"\"\n site_name = \"\"\n site_description = \"\"\n # subnet_dn = \"\"\n subnet_name = \"\"\n subnet_description = \"\"\n for entry in entries:\n site_dn = entry[\"distinguishedName\"] if entry[\"distinguishedName\"] else \"\"\n site_name = entry[\"name\"] if entry[\"name\"] else \"\"\n site_description = entry[\"description\"][0] if entry[\"description\"] else \"\"\n subnet_entries = self.engine.query(self.engine.SUBNET_FILTER(site_dn), attributes, base=','.join([\"CN=Sites,CN=Configuration\", self.engine.base_dn]))\n for subnet in subnet_entries:\n # subnet_dn = subnet[\"distinguishedName\"] if subnet[\"distinguishedName\"] else \"\"\n subnet_name = subnet[\"name\"] if subnet[\"name\"] else \"\"\n subnet_description = subnet[\"description\"][0] if subnet[\"description\"] else \"\"\n servers = self.engine.query(\"(objectClass=server)\", ['cn'], base=site_dn)\n servers_list = [d['cn'] for d in servers]\n\n output = \"Site: {}\".format(site_name)\n output += \" | Subnet: {}\".format(subnet_name) if subnet_name else \"\"\n output += \" | Site description: {}\".format(site_description) if site_description else \"\"\n output += \" | Subnet description: {}\".format(subnet_description) if subnet_description else \"\"\n output += \" | Servers: {}\".format(', '.join(servers_list)) if servers_list else \"\"\n print(output)",
"def tier(self) -> Optional[str]:\n return pulumi.get(self, \"tier\")",
"def tier(self) -> Optional[str]:\n return pulumi.get(self, \"tier\")",
"def tier(self) -> Optional[str]:\n return pulumi.get(self, \"tier\")",
"def tier(self) -> Optional[str]:\n return pulumi.get(self, \"tier\")",
"def test_list_config_nodes(self):\n with self.override_role():\n self.config_client.list_config_nodes()",
"def tiers(self):\n return Parent.objects.filter(\n name=self.name,\n country=self.country\n ).order_by(\n '-start_date'\n ).values('tier', 'start_date')",
"def _config_table(self):\n return self.targets",
"def vinet_configs(connection):\n assert connection\n query = \"\"\"select * from configs()\"\"\"\n return [item.strip() for item in sqlio.read_sql_query(query, connection)['name']]",
"def list_configurations(ctx):\n config_set = __ensure_configuration_exists(ctx)\n formatter = ConfigSetListFormatter.build(config_set, format='plain')\n out = formatter.format()\n\n click.echo(out)",
"def tier(self) -> pulumi.Output[Optional['outputs.EnvironmentTier']]:\n return pulumi.get(self, \"tier\")",
"def test_tiers_tier_level_tier_name_get(self):\n pass",
"def tier(self) -> Optional[pulumi.Input['EnvironmentTierArgs']]:\n return pulumi.get(self, \"tier\")",
"def list(self):\n\n config = self.get_config()\n client = config['client']\n default_config = config[client]\n\n msg.run('Saved options for client %s' % client)\n msg.inf('Default application (%s)' % default_config.get('defapp'))\n msg.inf('environment (%s)' % default_config['environment'])\n msg.inf('databases prod (%s) test (%s)' %\n (default_config['database'],\n default_config['test_database']))\n msg.inf('Image (%s)' % default_config['image'])\n msg.inf('Nginx (%s) Debug (%s) Verbose (%s)' %\n (default_config['nginx'],\n default_config['debug'],\n default_config['verbose'])\n )\n msg.run('\\nOther clients in this environment')\n clients = [item for item in config if item != 'client']\n\n msg.inf(', '.join(clients))",
"def configs(self):\n raise NotImplementedError()"
] | [
"0.6430079",
"0.6417699",
"0.6046109",
"0.59574795",
"0.5842776",
"0.5786352",
"0.5761368",
"0.5682218",
"0.56768256",
"0.56768256",
"0.56768256",
"0.56163913",
"0.55981684",
"0.5581887",
"0.55486715",
"0.54345995",
"0.53955334",
"0.53955334",
"0.53955334",
"0.53955334",
"0.536907",
"0.53452796",
"0.5334327",
"0.5301826",
"0.52929354",
"0.526373",
"0.5249019",
"0.523081",
"0.52159655",
"0.52151555"
] | 0.7024054 | 0 |
Returns the tier config with the given id. | def get_tier_config(self, tier_config_id):
text, code = ApiClient(self._config, 'tier/configs/' + tier_config_id).get()
return TierConfig.deserialize(text) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def _get_tier(pkmn_id):\n if pkmn_id in tiers.TIERS[\"0\"]:\n return 0\n elif pkmn_id in tiers.TIERS[\"1\"]:\n return 1\n elif pkmn_id in tiers.TIERS[\"2\"]:\n return 2\n elif pkmn_id in tiers.TIERS[\"3\"]:\n return 3\n else:\n return 4",
"def get_tenant_config(tenant_id):\n for tenant in tenants:\n if tenant['tenant_id'] == tenant_id:\n return tenant\n raise errors.BaseTapisError(\"invalid tenant id.\")",
"def get_subnet_by_id(self, id):\n return self.network.get_subnet(id)",
"def get(cls, account_id, product_id, config=None):\n from .tier_config_request import TierConfigRequest\n from connect.resources.base import ApiClient\n\n response, _ = ApiClient(config, base_path='tier/config-requests').get(\n params={\n 'status': 'approved',\n 'configuration.product.id': product_id,\n 'configuration.account.id': account_id,\n }\n )\n objects = TierConfigRequest.deserialize(response)\n\n if isinstance(objects, list) and len(objects) > 0:\n return objects[0].configuration\n else:\n return None",
"def get_pvp_tier(self, region, namespace, tier_id, **filters):\n filters['namespace'] = namespace\n resource = 'data/wow/pvp-tier/{0}'\n return self.get_resource(resource, region, *[tier_id], **filters)",
"def from_id(self, id_):\n return self._id_to_loadout.get(id_)",
"def get_setting(self, id):\n return __settings__.getSetting(id)",
"def tier(self) -> Optional[str]:\n return pulumi.get(self, \"tier\")",
"def tier(self) -> Optional[str]:\n return pulumi.get(self, \"tier\")",
"def tier(self) -> Optional[str]:\n return pulumi.get(self, \"tier\")",
"def tier(self) -> Optional[str]:\n return pulumi.get(self, \"tier\")",
"def get_eip_group(self, id, config=None):\n path = utils.append_uri(self._get_path(), id)\n return self._send_request(http_methods.GET, path, config=config)",
"def get_network_by_id(self, id):\n return self.network.get_network(id)",
"def tier(self) -> str:\n return pulumi.get(self, \"tier\")",
"def tier(self) -> str:\n return pulumi.get(self, \"tier\")",
"def tier(self) -> str:\n return pulumi.get(self, \"tier\")",
"def find_rent(self, id):\n allR=self.__loadFromFile()\n for bk in allR:\n if bk.getId()==id:\n return bk",
"def tier(self):\n\n if not hasattr(self, \"_tier\"):\n self._tier = self.opts.get(\"tier\")\n return self._tier",
"def _get_trs_opts(service_id):\n return trs_config()[service_id]",
"def find_by_id(self, id_):\n return self.by_id.get(id_)",
"def tier(self):\n return self._tier",
"def _get_tier_color(pkmn_id):\n if pkmn_id in tiers.TIERS[\"0\"]:\n return 0x000000\n elif pkmn_id in tiers.TIERS[\"1\"]:\n return 0xB80800\n elif pkmn_id in tiers.TIERS[\"2\"]:\n return 0x0009C4\n elif pkmn_id in tiers.TIERS[\"3\"]:\n return 0xF7AB09\n else:\n return 0x9909F7",
"def tier(self) -> Optional[pulumi.Input['InstanceTier']]:\n return pulumi.get(self, \"tier\")",
"def get_by_id(self, id: int) -> BoundLoadBalancerType:\n response = self._client.request(\n url=f\"/load_balancer_types/{id}\",\n method=\"GET\",\n )\n return BoundLoadBalancerType(self, response[\"load_balancer_type\"])",
"def get_config(self, pipette_id: str) -> StaticPipetteConfig:\n try:\n return self._state.static_config_by_id[pipette_id]\n except KeyError as e:\n raise errors.PipetteNotLoadedError(\n f\"Pipette {pipette_id} not found; unable to get pipette configuration.\"\n ) from e",
"def get_server(self, id):\n\t\treturn self.__servers.get_server(id)",
"def get_by_id(self, id):\n # type: (int) -> BoundLoadBalancer\n response = self._client.request(\n url=\"/load_balancers/{load_balancer_id}\".format(load_balancer_id=id), method=\"GET\"\n )\n return BoundLoadBalancer(self, response[\"load_balancer\"])",
"def find_layer_from_id(self, id):\n try:\n _layer, *_ = filter(lambda x: x.Id == id, self._file3dm.Layers)\n return _layer\n except ValueError:\n return None",
"def standby_setting_get_by_id(context, id, session=None):\n result = model_query(context, models.StandbySetting, session=session).\\\n filter_by(id=id).first()\n if not result:\n raise exception.NotFound(\"setting\")\n\n return result",
"def get_variable_by_id(self, id, param_instance=None):\n\n\t\tif not isinstance(id, int):\n\t\t\traise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: id EXPECTED TYPE: int', None, None)\n\t\t\n\t\tif param_instance is not None and not isinstance(param_instance, ParameterMap):\n\t\t\traise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: param_instance EXPECTED TYPE: ParameterMap', None, None)\n\t\t\n\t\thandler_instance = CommonAPIHandler()\n\t\tapi_path = ''\n\t\tapi_path = api_path + '/crm/v2/settings/variables/'\n\t\tapi_path = api_path + str(id)\n\t\thandler_instance.set_api_path(api_path)\n\t\thandler_instance.set_http_method(Constants.REQUEST_METHOD_GET)\n\t\thandler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)\n\t\thandler_instance.set_param(param_instance)\n\t\ttry:\n\t\t\tfrom zcrmsdk.src.com.zoho.crm.api.variables.response_handler import ResponseHandler\n\t\texcept Exception:\n\t\t\tfrom .response_handler import ResponseHandler\n\t\treturn handler_instance.api_call(ResponseHandler.__module__, 'application/json')"
] | [
"0.6171392",
"0.6161959",
"0.6053528",
"0.58012205",
"0.56873274",
"0.5458873",
"0.54341584",
"0.54274875",
"0.54274875",
"0.54274875",
"0.54274875",
"0.54111546",
"0.54089653",
"0.53808326",
"0.53808326",
"0.53808326",
"0.5372766",
"0.53144056",
"0.5300942",
"0.5277725",
"0.52709895",
"0.5267864",
"0.52471083",
"0.52101374",
"0.5208849",
"0.519856",
"0.5186055",
"0.5174645",
"0.5173764",
"0.51469153"
] | 0.8059733 | 0 |
Property for the event description based on the code | def event_desc(self) -> str:
return _EVENT_DESC_MAPPINGS.get(self.transaction_event_code) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_interesting_event_description(self):\n pass",
"def new_desc_event(self, event):\r\n pass",
"def get_description(self, code):\n try:\n return self.message[str(code)]\n except KeyError:\n return \"Unknown (\" + str(code) + \")\"",
"def event_for_event_description(ed):\n return ed.context",
"def set_event_desc(self, event):\n self.set_form_or_event_attribute(\"desc\", self.lhs, event)\n self.msg(\"Desc of event set to:\\n%s\" % self.lhs)",
"def description(self):",
"def description(self):\n pass",
"def description(self):\n pass",
"def cal_desc(self):\n desc = ''\n desc += 'Requested by '\n orgs = self.event.org.all()\n for org in orgs:\n desc += org.name + ', '\n desc = desc[:-2] + '.\\n' # removes trailing comma\n desc += 'Crew Chief: ' + self.crew_chief.get_full_name() + '\\n'\n if self.event.description:\n desc += self.event.description + '\\n'\n return desc",
"def Description(self) -> str:",
"def Description(self) -> str:",
"def description():",
"def _description(self):\n return None",
"def get_description(self):",
"def description(self) -> str:\r\n raise NotImplementedError",
"def description(self) -> str:\r\n raise NotImplementedError",
"def description(self) -> str:\r\n raise NotImplementedError",
"def description(self) -> str:\n raise NotImplementedError",
"def description(self) -> str:\n raise NotImplementedError",
"def description(self) -> str:\n raise NotImplementedError",
"def description(self) -> str:\n pass",
"def get_description(self):\n raise NotImplementedError",
"def get_description(self):\n pass",
"def get_description():\n raise NotImplementedError",
"def hook_description(self) -> str:",
"def __str__(self):\n return str(self._event)",
"def get_description(self) -> str:\n pass",
"def description(self) -> str:\n return self.data['description']",
"def full_code(self):\n return self.event.slug.upper() + self.code",
"def listener_description(self) -> str:\n return pulumi.get(self, \"listener_description\")"
] | [
"0.7521428",
"0.71878743",
"0.7116342",
"0.6826529",
"0.6817979",
"0.67542845",
"0.6681775",
"0.6681775",
"0.6652655",
"0.6632184",
"0.6632184",
"0.6611476",
"0.65897524",
"0.6565737",
"0.65504605",
"0.65504605",
"0.65504605",
"0.65266895",
"0.65266895",
"0.65266895",
"0.64982945",
"0.64930993",
"0.64773494",
"0.6462443",
"0.64122784",
"0.6408032",
"0.6397741",
"0.63909465",
"0.63832736",
"0.634586"
] | 0.807602 | 0 |
Property for the enumeration of this transaction () | def transaction_status_enum(self) -> TransactionStatus:
return _TRANSACTION_STATUS_MAPPING.get(self.transaction_status) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def enum(self):\r\n raise NotImplementedError",
"def enumeration(self):\n raise exceptions.NotImplementedError()",
"def __index__(cls): # pylint: disable=invalid-index-returned\n return TransType(60)",
"def attr(self):\n\n return EnumAttr(self)",
"def natural_key(self):\n\t\tself_keys = {\n\t\t\t'name': self.name,\n\t\t}\n\t\tnatural_keys = super(TransactionStatus, self).natural_key(self_keys)\n\t\treturn natural_keys",
"def state(self):\n raise NotImplementedError",
"def field_2_transaction(cls):\n\n return cls._FIELD_2_TRANSACTION",
"def transaction_type(self) -> str:\n return self.chunks[2].decode(\"ascii\")",
"def __repr__(self):\n return u'<Transaction id={i}, amount={a}>'.format(\n i=self.id,\n a=self.amount\n )",
"def state(self):\n raise NotImplementedError()",
"def state(self):\n pass",
"def state(self):\n return self.status",
"def __unicode__(self):\r\n return \"%d (%d - %d)\" % (self.agreement_id, self.payer_email, self.state)",
"def enums(self):\n return self._enums",
"def state(self):\r\n return str(self)",
"def state(self):\n return self.__state",
"def state(self):\n return self.__state",
"def type(self):\n return self.EQUATION",
"def type(self):\n return self.EQUATION",
"def state(self):\n return self.get_state()",
"def state(self) -> Any:\n return self._state",
"def state(self):\n return str(self)",
"def status(self):\n raise NotImplementedError()",
"def status(self):\n return self.state",
"def state(self):\n\n\t\treturn str(self)",
"def state(self):\n return self.values.primary.value",
"def transaction_id(self):\n return self.private",
"def state(self):\n return self._attributes['status']",
"def transitiontype(self):\n return self._transitiontype",
"def state(self):\r\n return self._state"
] | [
"0.71118397",
"0.6270592",
"0.62465674",
"0.6158069",
"0.59486014",
"0.58366627",
"0.58330446",
"0.58252573",
"0.5776557",
"0.5740692",
"0.57314277",
"0.5705731",
"0.5659605",
"0.565769",
"0.5623061",
"0.56176597",
"0.56176597",
"0.561505",
"0.561505",
"0.5612701",
"0.5606627",
"0.5604071",
"0.5579971",
"0.55750364",
"0.5569833",
"0.55547994",
"0.55405056",
"0.5535993",
"0.55303645",
"0.55139756"
] | 0.6593331 | 1 |
Build the queryset's menu nodes | def queryset_nodes(queryset):
for article in queryset:
article_nodes.append(NavigationNode(
article.title,
aritcle.url,
article.menu.menuid,
article.menu.parent,
)
)
return article_nodes | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def create_menus( self ):",
"def create_all_menus(self, ):\n m = self._model\n if not m:\n return\n indizes = self._flatten_hierarchy(m)\n for i in indizes:\n self.create_menu_for_index(i)",
"def menu(self):\n menu = list()\n \n \n menu.extend([\n {\n 'title': 'Bootstrap Demo',\n 'href': self.request.route_url('bootstrap_demo'),\n 'icon': \"fa fa-twitter-square\"\n },\n {\n 'title': 'Jade Demo',\n 'href': self.request.route_url('jade_demo'),\n 'icon': \"fa fa-indent\"\n },\n ])\n if self.user:\n menu.extend([\n {\n 'title': 'Entities',\n 'icon': \"fa fa-bar-chart\",\n 'dropdown': [\n {\n 'title': 'All entities',\n 'href': self.request.route_url(\n 'entities',\n ext='html',\n _query={\n 'renderer': 'datatable',\n 'options': 'serverside-columnsearch'\n }\n ),\n 'icon': \"fa fa-bar-chart\"},\n {\n 'title': 'CPTs',\n 'href': self.request.route_url(\n 'cpts',\n ext='html',\n _query={\n 'renderer': 'datatable',\n 'options': 'columnsearch'\n }\n ),\n }\n ]\n }\n ]),\n if self.user.has_admin:\n menu.append(\n {\n 'title': \"User Management\",\n 'icon': \"fa fa-users\",\n 'dropdown': [\n {\n 'title': 'User Overview',\n 'href': self.request.route_url(\n 'users',\n ext='html',\n _query={\n 'renderer': 'datatable',\n 'options': 'serverside-columnsearch'\n }\n ),\n 'icon': 'fa fa-users',\n },\n {\n 'title': 'Add User',\n 'href': self.request.route_url('user_create'),\n 'icon': 'fa fa-user-plus',\n }\n ]\n }\n )\n\n return menu",
"def create_menu():",
"def get_menus(self):\n trees = []\n\n def add(node, index):\n label = self._get_item_text(index, \"label\").lstrip().replace(\"\\\\t\", \"\\t\")\n id = self._get_item_text(index, \"id\")\n name = self._get_item_text(index, \"name\")\n help_str = self._get_item_text(index, \"help_str\")\n event_handler = self._get_item_text(index, \"event_handler\")\n try:\n item_type = int(self._get_item_text(index, \"type\"))\n except ValueError:\n item_type = 0\n checkable = item_type == 1 and misc.wxstr(\"1\") or misc.wxstr(\"\")\n radio = item_type == 2 and misc.wxstr(\"1\") or misc.wxstr(\"\")\n n = MenuTree.Node(label, id, name, help_str, checkable, radio, handler=event_handler)\n node.children.append(n)\n n.parent = node\n return n\n level = 0\n curr_item = None\n for index in range(self.items.GetItemCount()):\n label = self._get_item_text(index, \"label\").replace(\"\\\\t\", \"\\t\")\n lvl = self.item_level(index)\n if not lvl:\n t = MenuTree( self._get_item_text(index, \"name\"), label,\n id=self._get_item_text(index, \"id\"), handler=self._get_item_text(index, \"event_handler\") )\n curr_item = t.root\n level = 1\n trees.append(t)\n continue\n elif lvl < level:\n for i in range(level-lvl):\n curr_item = curr_item.parent\n level = lvl\n elif lvl > level:\n curr_item = curr_item.children[-1]\n level = lvl\n add(curr_item, index)\n\n return trees",
"def get_all_menu():",
"def cache_nodes(request, queryset):\n if queryset:\n lang = get_language()\n site_id = Site.objects.get_current().pk\n prefix = getattr(settings, \"CMS_CACHE_PREFIX\", \"menu_cache_\")\n key = \"%smenu_nodes_%s_%s\" % (prefix, lang, site_id)\n parent_node = None\n\n # build article_nodes from queryset in menu cache\n article_nodes = []\n for article in queryset:\n article_nodes.append(NavigationNode(\n article.title,\n article.url,\n article.menu.menuid,\n article.menu.parent,\n )\n )\n\n # get the original cache nodes. if blank, get the whole nodes. if\n # article_nodes are already in cache nodes, return.\n cached_nodes = cache.get(key, None)\n if cached_nodes:\n str_cached_nodes = str(cached_nodes)\n if str(article_nodes[0]) in str_cached_nodes:\n return\n else:\n cached_nodes = menu_pool.get_nodes(request)\n \n parent_node = category_node(article, cached_nodes)\n\n # add parent_node to the article node and save into cached_node\n for node in article_nodes:\n node.parent = parent_node\n node.namespace = getattr(parent_node, 'namespace', None)\n cached_nodes.append(node)\n\n duration = getattr(settings, \"MENU_CACHE_DURATION\", 60*60)\n cache.set(key, cached_nodes, duration)\n else:\n return",
"def insert_menus(self, parent, first, last):\n for i in range(first, last + 1):\n index = self._model.index(i, 0, parent)\n flattened = [index]\n flattened.extend(self._flatten_hierarchy(self._model, index))\n for newi in flattened:\n self.create_menu_for_index(newi)",
"def _createBakeSetMenuItems(node):\n pass",
"def _createUtilityMenuItems(ned, node):\n pass",
"def createNodeMenu(dash_instance):\n\tnodeLabel = html.Label(id='NodeLabel', \n\t style=dict(fontWeight='bold', width=50, marginLeft='100', marginRight='20', marginTop='0px', display='block'), \n\t\t\t\t\t\t children='Nodes: ')\n\tnodeOptions = [{'label': 'Select a group first or search for specific node', 'value': 'None'}]\n\tnodeDropDown = dcc.Dropdown(id=\"NodeDropDown\", \n\t options=nodeOptions,\n\t\t\t\t\t\t\t\tstyle=dict(width=350, marginRight='20', marginBottom='50', display='block'), \n\t\t\t\t\t\t\t\tplaceholder='Select a node...', clearable=True, value='')\n\n\treturn nodeLabel, nodeDropDown",
"def atest_data_init(self):\n menus = self.session.query(User,Menu) \\\n .outerjoin(UserGroup,UserGroup.user_id==User.role_id) \\\n .outerjoin(Group,Group.id==UserGroup.group_id) \\\n .outerjoin(GroupMenu,GroupMenu.group_id==Group.id) \\\n .outerjoin(Menu,Menu.id==GroupMenu.menu_id) \\\n .filter(Menu.parent_id==None) \\\n .filter(User.user_name=='8888') \\\n .order_by(Menu.id).all()\n log.debug(menus)\n\n #menus = self.session.query(Menu)\\\n # .options(joinedload_all(\"children\", \"children\", \"children\")) \\\n # .filter(Menu.parent_id==None).order_by(Menu.id).all()\n\n tree = [utils.tree_dump(menu[1]) if menu[1] else [] for menu in menus]\n for re in tree:\n #log.debug(tree)\n log.debug(re)",
"def get_queryset(self, request):\n query = super(GipsyMenu, self).get_queryset(request)\n return query.filter(parent__isnull=True)",
"def nodes(self):\n return self._get_tree_queryset()",
"def _build_main_menu(self):\n if self._args.execution_environment:\n columns = [\"__name\", \"__version\", \"__shadowed\", \"__type\", \"path\"]\n else:\n columns = [\"__name\", \"__version\", \"__shadowed\", \"path\"]\n\n return Step(\n name=\"all_collections\",\n columns=columns,\n select_func=self._build_plugin_menu,\n tipe=\"menu\",\n value=self._collections,\n )",
"def _ui_content(self):\n\n # Cleat the tree\n self.clear()\n\n # Set the font\n font = QtGui.QFont()\n font.setPointSize(11)\n\n # Add the id sets and set items\n for id_set, id_dict in sorted(self.scnData.items()):\n tree_item = QtGui.QTreeWidgetItem(self)\n\n tree_item.setText(0, id_set)\n tree_item.setFont(0, font)\n\n icon_folder = os.path.dirname(os.path.abspath(__file__))\n icon_path = os.path.join(icon_folder, \"icons\", \"IdSet.png\")\n\n tree_item.setIcon(0, QtGui.QIcon(icon_path))\n\n tree_item.setData(0, QtCore.Qt.UserRole, \"set\")\n tree_item.setData(1, QtCore.Qt.UserRole, id_set)\n\n for id_color, id_objects in sorted(id_dict.items()):\n if id_color != \"Holdout\":\n self._add_id_color(id_objects,\n id_color,\n tree_item)\n\n self._add_id_color(id_dict[\"Holdout\"], \"Holdout\", tree_item)\n\n return",
"def menus(self):\r\n return []",
"def createMenus(self):\n\n self.fileMenu = QMenu(\"&File\", self)\n self.fileMenu.addAction(self.openAct)\n self.fileMenu.addAction(self.addAct)\n self.fileMenu.addSeparator()\n # self.fileMenu.addAction(self.showSessionAct)\n self.fileMenu.addAction(self.exitAct)\n\n self.helpMenu = QMenu(\"&Help\", self)\n self.helpMenu.addAction(self.aboutAct)\n self.helpMenu.addAction(self.aboutQtAct)\n\n self.viewMenu = QMenu(\"&View\", self)\n\n self.sortMenu = QMenu(\"Sort by\", self.viewMenu, enabled=False)\n self.groupMenu = QMenu(\"Group by\", self.viewMenu, enabled=False)\n\n self.showGroupMenu = QMenu(\"Load Group\", self.fileMenu, enabled=False)\n self.addGroupDataMenu = QMenu('Add Group', self.fileMenu, enabled=False)\n self.fileMenu.addMenu(self.showGroupMenu)\n self.fileMenu.addMenu(self.addGroupDataMenu)\n self.fileMenu.addAction(self.seeAllGroupAct)\n self.viewMenu.addMenu(self.groupMenu)\n self.viewMenu.addMenu(self.sortMenu)\n\n # Add filters to \"Sort by\"\n self.create_sort_menu()\n self.sortMenu.addAction(self.ageSortAct)\n self.sortMenu.addAction(self.sexSortAct)\n self.sortMenu.addAction(self.genotypeSortAct)\n self.sortMenu.addAction(self.speciesSortAct)\n self.sortMenu.addAction(self.subjectIDSortAct)\n self.sortMenu.addAction(self.weightSortAct)\n self.sortMenu.addAction(self.birthSortAct)\n self.sortMenu.addSeparator()\n\n self.sortMenu.addAction(self.fluorescenceSortAct)\n self.sortMenu.addAction(self.imagesegSortAct)\n self.sortMenu.addAction(self.rasterSortAct)\n\n # Add filters to \"Group by\"\n self.create_group_menu()\n self.groupMenu.addAction(self.ageGroupAct)\n self.groupMenu.addAction(self.sexGroupAct)\n self.groupMenu.addAction(self.genotypeGroupAct)\n self.groupMenu.addAction(self.speciesGroupAct)\n self.groupMenu.addAction(self.subjectIDGroupAct)\n self.groupMenu.addAction(self.weightGroupAct)\n self.groupMenu.addAction(self.birthGroupAct)\n\n self.groupMenu.addSeparator()\n\n self.groupMenu.addAction(self.fluorescenceGroupAct)\n self.groupMenu.addAction(self.imagesegGroupAct)\n self.groupMenu.addAction(self.rasterGroupAct)\n\n self.menuBar().addMenu(self.fileMenu)\n self.menuBar().addMenu(self.viewMenu)\n self.menuBar().addMenu(self.helpMenu)",
"def render(self):\n menu = etree.Element('openbox_pipe_menu')\n \n walk(self.menuItems, menu)\n \n print etree.tostring(menu)",
"def build_menuable_items(self):\n cols = []\n for bundle in app.bundles:\n bundle_metadata = bundle['Meta']['bundle-metadata']\n try:\n conjure_data = bundle['Meta']['extra-info/conjure-up']\n name = conjure_data.get('friendly-name',\n bundle['Meta']['id']['Name'])\n except KeyError:\n name = bundle['Meta']['id']['Name']\n self.fname_id_map[name] = bundle\n cols.append(\n Columns(\n [\n (\"weight\", 0.2, Color.body(\n menu_btn(label=name,\n on_press=self.done),\n focus_map=\"menu_button focus\")),\n (\"weight\", 0.3, Text(\n bundle_metadata.get('Description',\n 'Needs a description'),\n align=\"left\"))\n ],\n dividechars=1\n )\n )\n cols.append(Padding.line_break(\"\"))\n return Pile(cols)",
"def DebugMenuProviderMixin_on_buildUI(self):\n self._DebugMenuProviderMixin_build_menus()\n self._DebugMenuProviderMixin_build_actions() # the actions actually depend on the existance of the menus for this dynamic menu case",
"def get_menus():\n\n pass",
"def loadMenu(self):\r\n show_empty_root_items = pos.config['menu', 'show_empty_root_items']\r\n show_disabled_items = pos.config['menu', 'show_disabled_items']\r\n self.mainToolbook.AssignImageList(pos.menu.il)\r\n \r\n for root in pos.menu.main.items:\r\n if not root.enabled and not show_disabled_items:\r\n continue\r\n enabled_children = [i for i in root.children if i.enabled]\r\n if show_disabled_items:\r\n children = root.children\r\n else:\r\n children = enabled_children\r\n # Hide empty menu root items\r\n if len(children) == 0 and not show_empty_root_items:\r\n continue\r\n page = self.getToolbookPage(children)\r\n self.mainToolbook.AddPage(imageId=root.image, page=page, select=False, text=root.label)\r\n page.Enable(root.enabled)# and len(enabled_children) != 0)\r",
"def populate_menu(self):\n # TODO : Performance issue ?\n self.showGroupMenu.clear()\n self.addGroupDataMenu.clear()\n counter = 0\n for group_name in self.group_data.keys():\n counter +=1\n exec('self.groupAct' + str(counter) + ' = QAction(\"' + group_name+'\", self)')\n eval('self.groupAct' + str(counter) + '.triggered.connect(partial(self.load_group, group_name))')\n exec('self.groupAddAct' + str(counter) + ' = QAction(\"' + group_name+'\", self)')\n eval('self.groupAddAct' + str(counter) + '.triggered.connect(partial(self.add_group_data, group_name))')\n self.showGroupMenu.addAction(eval('self.groupAct' + str(counter)))\n self.addGroupDataMenu.addAction(eval('self.groupAddAct' + str(counter)))",
"def createNodeEditorMarkingMenu(ned):\n pass",
"def menu_(node, cur_node, node_prefix = PREFIX, indent = ''):\n\n global menu_code\n\n menu_code += indent + '<ul>\\n'\n for child in sorted(node.children, key=lambda n: n.page.src_pathname):\n if child.page.dst_file.startswith(\"index.\") or child.page.src_file in HIDDEN:\n continue\n menu_code += indent + '<li class=\"level-' + str(child.page.level) + '\"><a '\n if(child == cur_node\n or (cur_node.page.dst_file.startswith(\"index.\") and child == cur_node.parent)):\n menu_code += 'class=\"current\" '\n menu_code += 'href=\"' + node_prefix + child.page.dst_file\n if child.children:\n menu_code += \"/index.\" + DST_EXT + '\">' + child.page.name + '</a>\\n'\n menu_(child, cur_node, node_prefix + child.page.dst_file + '/', indent + '\\t')\n menu_code += indent + '</li>\\n'\n else:\n menu_code += '\">' + child.page.name + '</a></li>\\n'\n menu_code += indent + '</ul>\\n'",
"def get_children_queryset(self):\n pass",
"def show_categories(self):\n cat_model = TreeModel(('Categories', ))\n self.categoriesView.setModel(cat_model)\n\n categories = self.orm.fetch_parents()\n for category in categories:\n item = TreeItem(category, cat_model.rootItem)\n cat_model.rootItem.appendChild(item)\n\n subs = self.orm.fetch_subcategories_for_parent(category)\n\n for sub in subs:\n sub_item = TreeItem(sub, item)\n item.appendChild(sub_item)\n\n self.categoriesView.expandAll()",
"def createNodeItemMarkingMenu(ned, node):\n pass",
"def _addCustomNodeItemMenus(ned, node):\n pass"
] | [
"0.6887437",
"0.6695563",
"0.65804785",
"0.6051546",
"0.6004562",
"0.6000519",
"0.60000986",
"0.5959026",
"0.5901801",
"0.58684534",
"0.5846643",
"0.58404493",
"0.5832597",
"0.58244693",
"0.58063537",
"0.57588434",
"0.57193357",
"0.5719219",
"0.5705354",
"0.5689959",
"0.5638512",
"0.56366926",
"0.561264",
"0.5586269",
"0.5585713",
"0.5572547",
"0.55613655",
"0.55545205",
"0.55487657",
"0.5535091"
] | 0.734222 | 0 |
returns the list of products that is visible to the given account | def get_visible_products(self):
all_products = billing.loading.get_products(hidden=True)
public_products = billing.loading.get_products()
subscribed_product_types = ProductType.objects \
.filter(subscriptions__billing_account=self) \
.distinct()
subscribed_products = set(pt.get_product_class() for pt in subscribed_product_types)
visible_products = set(public_products).union(subscribed_products)
return [p for p in all_products if p in visible_products] | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def see_products_for_rent_handler():\n\n products = ShowProductsAndCustomers()\n my_list = products.see_products_for_rent()\n my_result_list = []\n for product in my_list:\n my_result_list.append(product)\n print(product)\n return my_result_list",
"def get_vendors_and_products_seen(cls, cb):\n url = \"/device_control/v3/orgs/{0}/products\".format(cb.credentials.org_key)\n resp = cb.get_object(url)\n return resp.get(\"results\", [])",
"def display_accounts(cls):\n return cls.account_list",
"def display_account(request):\n form = ProductSearch(request.POST or None)\n favoris = Favorite.objects.filter(\n user_link=request.user).order_by('movie_saved')\n paginator = Paginator(favoris, 10)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n return render(request, 'display_account.html', {'page_obj': page_obj, 'form': form})",
"def show_available_products():\n LOGGER.debug('Listing all available products.')\n available_products = {}\n with MongoDBConnection() as mongo:\n database = mongo.connection.hp_norton\n for product in database.products.find(\n {'quantity_available': {'$gt': 0}}):\n available_products[product['product_id']] = {\n 'description': product['description'],\n 'product_type': product['product_type'],\n 'quantity_available': product['quantity_available']}\n return available_products",
"def show_available_products(*args):\n logger.info(f\"Preparing dict of available prodcuts...\")\n available_products = {}\n\n with MONGO:\n mdb = eval(Settings.connect_string)\n products = mdb[\"product\"]\n for doc in products.find():\n del doc[\"_id\"]\n if int(doc[\"quantity_available\"]) > 0:\n product_id = doc[\"product_id\"]\n del doc[\"product_id\"]\n available_products[product_id] = doc\n\n return available_products",
"def show_available_products(): # {{{\n products_available = {}\n try:\n with MONGO:\n product_collection = MONGO.connection.assignment_07[\"product\"].find(\n )\n\n for product in product_collection:\n if int(product[\"quantity_available\"]) > 0:\n products_available[product[\"product_id\"]] = {\n \"description\": product[\"description\"],\n \"product_type\": product[\"product_type\"],\n \"quantity_available\": product[\"quantity_available\"],\n }\n except TypeError as excep:\n LOGGER.warning(\"Error looking up available products\")\n LOGGER.warning(excep)\n else:\n if not products_available:\n LOGGER.info('No products found')\n else:\n LOGGER.info(\"Available products retrieved successfully.\")\n return products_available # }}}",
"def list(request, queryset, *args, **kwargs):\r\n return object_list(\r\n request,\r\n queryset.filter(account = request.account), \r\n *args, \r\n **kwargs\r\n )",
"def see_all_different_products_handler():\n\n products = ShowProductsAndCustomers()\n my_list = products.see_all_different_products()\n my_result_list = []\n for product in my_list:\n my_result_list.append(product)\n print(product)\n return my_result_list",
"def visible(self):\n return self.get_queryset().filter(\n record_status=self.model.ACTIVE, merged_with=None)",
"def get_product_list_grid(self):\n product_list = WebDriverWait(self.driver, self.search_module_wait_time).until(EC.visibility_of_element_located(self.PRODUCT_LIST_GRID))\n return product_list",
"def list_products(self):\n return self._make_get_request(self._urls['products'])",
"def list_accounts(self):\n pass",
"def get_queryset(self, *args, **kwargs):\n return Order.objects.visible(self.request.user)",
"def get_shopping_partners(request):\n try:\n shopping_partners = Partner.objects.get(current_user=request.user)\n shopping_partners_list = shopping_partners.partners.all()\n except:\n shopping_partners = []\n shopping_partners_list = []\n\n return shopping_partners_list",
"def get_all_products(access_keeper):\n logger.debug('getting products...')\n headers = get_authorization_headers(access_keeper)\n\n response = requests.get('https://api.moltin.com/v2/products', headers=headers)\n raise_response_errors(response)\n\n products = response.json()['data']\n logger.debug(f'{len(products)} products was got')\n\n return products",
"def _get_product_accounts(self):\n accounts = super(ProductTemplate, self)._get_product_accounts()\n res = self._get_asset_accounts()\n accounts.update({\n 'import_stock_input': self.property_stock_account_import or self.categ_id.property_stock_account_import_categ_id,\n })\n return accounts",
"def get_queryset(self):\n # distinct is needed to prevent multiple instances of product in resultset if multiple subscriptions are present\n return self.model.objects.filter(subscription__owner=self.request.user).distinct()",
"def list_products(admin):\n fields = [\n \"id\",\n \"name\",\n \"price\",\n \"barcode\",\n \"active\",\n \"countable\",\n \"purchase_sum\",\n \"replenishment_sum\",\n \"balance_score\",\n \"revocable\",\n \"imagename\",\n \"tags\",\n \"creation_date\",\n ]\n\n query = QueryFromRequestParameters(Product, request.args, fields)\n result, content_range = query.result()\n products = convert_minimal(result, fields)\n for product in products:\n product[\"tags\"] = [t.id for t in product[\"tags\"]]\n response = jsonify(products)\n response.headers[\"Content-Range\"] = content_range\n return response",
"def get_all_products(self):\n\t\tpass",
"def test_list_available_product(self):\n view = AvailableProductListView.as_view({'get': 'list'})\n uri = reverse('products:list-available-products')\n request = self.factory.get(uri, HTTP_AUTHORIZATION='Token {}'.format(self.token_user.key))\n request.user = self.user['user']\n response = view(request)\n self.assertEqual(response.status_code, 200,\n f'Expected Response Code 200, received {response.status_code} instead.')",
"def products_list(driver, login_action, open_products_page, products_page, logger):\n try:\n return products_page.all_products_list()\n except logger.on_exception(exception, driver):\n print(exception)",
"def list(ctx):\n if ctx.obj.get('NAMESPACE') != 'accounts':\n click.echo(\n click.style('Only account data is available for listing.', fg='red')\n )\n return\n\n swag = create_swag_from_ctx(ctx)\n accounts = swag.get_all()\n _table = [[result['name'], result.get('id')] for result in accounts]\n click.echo(\n tabulate(_table, headers=[\"Account Name\", \"Account Number\"])\n )",
"def show_available_products():\n products = DATABASE['product'].find({'quantity_available': {'$ne':'0'}})\n products_dict = {prod['product_id']:\n {'description': prod['description'],\n 'product_type': prod['product_type'],\n 'quantity_available': int(prod['quantity_available'])}\n for prod in products}\n return products_dict",
"def shop_products(request):\n\n shop = Shop.objects.get(user=request.user)\n products = Products.objects.filter(shop_rel=shop)\n paginator = pagination.PageNumberPagination()\n paginator.page_size = 7\n result_page = paginator.paginate_queryset(products, request=request)\n serializer = ProductSerializer(result_page, many=True)\n return paginator.get_paginated_response(serializer.data)",
"def fetch_account_catalogs(account:str):\n for config in accounts:\n if account in config['streamers']:\n return config['catalogs']\n return",
"def display(auth_context):\n\n products = product_catalog.list_products()\n # Get promoted products recommended by the AutoML model.\n promos = product_catalog.get_promos()\n return render_template('product_catalog.html',\n products=products,\n promos=promos,\n auth_context=auth_context,\n bucket=product_catalog.BUCKET)",
"def list(ctx, show_hidden, oath_type, period):\n ensure_validated(ctx)\n controller = ctx.obj['controller']\n creds = [cred\n for cred in controller.list()\n if show_hidden or not cred.is_hidden\n ]\n creds.sort()\n for cred in creds:\n click.echo(cred.printable_key, nl=False)\n if oath_type:\n click.echo(u', {}'.format(cred.oath_type.name), nl=False)\n if period:\n click.echo(', {}'.format(cred.period), nl=False)\n click.echo()",
"def visible(self, **kwargs):\r\n return self.filter(is_deleted=False, **kwargs)",
"def query_accounts(self):\n return self._call_txtrader_api('query_accounts', {})"
] | [
"0.61855996",
"0.6172926",
"0.59688145",
"0.5910303",
"0.5864358",
"0.5848761",
"0.58424187",
"0.58332884",
"0.5669318",
"0.5644832",
"0.56349075",
"0.5614921",
"0.56030047",
"0.55888885",
"0.55652934",
"0.55594563",
"0.5548453",
"0.5529825",
"0.55008173",
"0.54984933",
"0.5496295",
"0.5492361",
"0.5469681",
"0.5465335",
"0.54540265",
"0.5444004",
"0.5442461",
"0.54382217",
"0.5436622",
"0.54261893"
] | 0.7699004 | 0 |
returns the subscriptions whose most recent status is one of those specified | def filter_by_current_statuses(self, statuses):
annotated = self.annotate(
newest=models.Max('approval_statuses__created'))
newest_subs = annotated.filter(
approval_statuses__created=models.F('newest'),
approval_statuses__status__in=statuses
)
return newest_subs | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def filter_by_current_status(self, status):\r\n return self.filter_by_current_statuses([status])",
"def get_latest_statuses(self):\n self.status_lock.acquire()\n status = copy.deepcopy(self.cached_status)\n self.status_lock.release()\n return status",
"def latest_payment(owner, status_in=[]):\n try:\n query = Payment.payments.filter(owner=owner)\n if status_in:\n query = query.filter(status__in=status_in)\n return query.latest('started_at')\n except ObjectDoesNotExist:\n return None",
"def get_subscriptions(self):\n return self.subscriptions.all()",
"def get_subscriptions(self):\n url = '{}/v2/subscriptions'.format(self.url)\n r = requests.get(url, headers=self.headers_v2)\n return r.json()",
"def get_last_text_status(self):\n with self.connection.cursor() as cursor:\n sql = \"\"\"SELECT * FROM `ow_newsfeed_action` \n WHERE `id`= (SELECT MAX(`id`) FROM `ow_newsfeed_action` WHERE `entityType`=\"user-status\")\n AND `entityType`=\"user-status\"\n \"\"\"\n cursor.execute(sql)\n response = cursor.fetchone()\n data = json.loads(response[\"data\"])\n\n self.connection.commit()\n print(data[\"statusId\"])\n return Status(text=data[\"status\"],id=data[\"statusId\"])",
"def query_tas_status(self):\n response = {}\n def _tas_status_callback(mqtt, userdata, msg):\n if 'STATUS' in msg.topic[-8:]:\n stat_num=re.sub(r'.*STATUS([0-9]*)$', r'\\1', msg.topic)\n msg = json.loads(msg.payload.decode('UTF-8'))\n for datum in tasmota_status_query[stat_num]:\n datumPath=tasmota_status_query[stat_num][datum]\n response[datum] = nested_get(msg, datumPath)\n response['status{num}'.format(num=stat_num)] = dt.datetime.now()\n s_topic = '{s_topic}/+'.format(**self)\n c_topic = '{c_topic}/status'.format(**self)\n self.mqtt.message_callback_add(s_topic, _tas_status_callback)\n self.mqtt.connect(self.mqtt_host)\n self.mqtt.subscribe(s_topic)\n\n #publish requests\n for status_number, ignored in tasmota_status_query.items():\n self.mqtt.publish(c_topic, status_number)\n\n # status numbers, converted to status2, etc\n def _status_words():\n return ['status{num}'.format(num=key) for key \\\n in tasmota_status_query.keys()]\n\n # while not all of the responses exist,\n # and we aren't too old since the start time\n startTime = dt.datetime.now()\n done = False\n while(not done and not too_old(startTime, waitForStatus)):\n done = True\n for status in _status_words():\n done = done and status in response\n if not done:\n self.mqtt.loop(timeout=loop_time)\n\n self.mqtt.unsubscribe(s_topic)\n self.mqtt.message_callback_remove(s_topic)\n self.mqtt.disconnect()\n\n self.reported = response\n return response",
"def get_pending_subscriber_update(self, limit, status):\n #TODO: Improve this part with a PL/SQL\n\n #We cannot use select_related here as it's not compliant with locking the rows\n list_subscriber = Subscriber.objects.select_for_update()\\\n .filter(campaign=self.id, status=SUBSCRIBER_STATUS.PENDING)\\\n .all()[:limit]\n if not list_subscriber:\n return (False, 0)\n id_list_sb = []\n count = 0\n for elem_subscriber in list_subscriber:\n count = count + 1\n id_list_sb.append(elem_subscriber.id)\n #Update in bulk\n Subscriber.objects.filter(id__in=id_list_sb).update(status=status)\n return (list_subscriber, count)",
"def latest_reports(max_iso_timestamp: str, database):\n report_uuids = database.reports.distinct(\"report_uuid\")\n reports = []\n for report_uuid in report_uuids:\n report = database.reports.find_one(\n filter={\"report_uuid\": report_uuid, \"timestamp\": {\"$lt\": max_iso_timestamp}},\n sort=[(\"timestamp\", pymongo.DESCENDING)])\n if report and not \"deleted\" in report:\n report[\"_id\"] = str(report[\"_id\"])\n reports.append(report)\n return reports",
"def _filter_resources_by_status(self, resources: [], statuses: []):\n all_resources = []\n for resource in resources:\n if statuses:\n status = ResourceModel.Status.from_string(resource.status)\n if status in statuses:\n all_resources.append(resource)\n else:\n all_resources.append(resource)\n return all_resources",
"def last_status_update(self):\n try:\n return StatusUpdate.objects.filter(section=self).latest(\"created_at\")\n except StatusUpdate.DoesNotExist:\n return None",
"async def find_notifications_by_status(db_session: Session, status: str):\n notifications = None\n if status == NotificationStatusEnum.FAILURE:\n seconds = get_api_settings().DELIVERY_FAILURE_RETRY_TIME_FRAME\n notifications = await NotificaitonCRUD.find_notifications_by_status_time(db_session,\n status,\n seconds)\n else:\n notifications = await NotificaitonCRUD.find_notifications_by_status(db_session, status)\n\n return notifications",
"def getsubscriptions(self):\n subs = {}\n for sub in self._subscriptions.values():\n subs[sub.ID] = sub.asTuple()\n return subs",
"def subscribed(cls, team):\n return cls.query(\n cls.status == 'subscribe',\n cls.team == team.lower()\n ).fetch(100)",
"def subscriptions(self):\r\n return subs.AccountSubscriptions(self)",
"def get_subscribers(cls, topic, count, starting_at_callback=None):\n\t\tquery = cls.all()\n\t\tquery.filter('topic_hash =', utils.sha1_hash(topic))\n\t\tquery.filter('subscription_state = ', cls.STATE_VERIFIED)\n\t\tif starting_at_callback:\n\t\t\tquery.filter('callback_hash >=', utils.sha1_hash(starting_at_callback))\n\t\tquery.order('callback_hash')\n\n\t\treturn query.fetch(count)",
"def pop_latest_statuses(self) -> Optional[ExtractStatusResult]:\n latest_result = None\n try:\n while True:\n latest_result = self.__status_result_queue.get(block=False)\n except queue.Empty:\n pass\n return latest_result",
"def list(cls, **kwargs):\n response = Yola().list_subscriptions(**kwargs)\n return [cls(**sub) for sub in response['results']]",
"def subscriptions(self):\r\n return v3.Subscriptions(self)",
"def get_by_status(status):\n return list(tasks.find({'status': status}))",
"def query_tas_status(self, attributes):\n def _tas_status_callback(mqtt, userdata, msg):\n for k, v in attributes['values'].items():\n setattr(self, k, nested_get(literal_eval(msg.payload.decode('UTF-8')), v))\n s_topic = '{s_topic}/{stat_topic}'.format(stat_topic=attributes['stat_topic'], **self)\n c_topic = '{c_topic}/status'.format(**self)\n self.mqtt.message_callback_add(s_topic, _tas_status_callback)\n self.mqtt.connect(self.mqtt_host)\n self.mqtt.subscribe(s_topic)\n starttime = datetime.datetime.now()\n self.mqtt.publish(c_topic, attributes['status_payload'])\n # check and see if the last attribute has been found yet\n while getattr(self, list(attributes['values'].keys())[-1]) == '' and (datetime.datetime.now() - starttime).total_seconds() < loop_time:\n self.mqtt.loop(timeout=loop_time)\n self.mqtt.unsubscribe(s_topic)\n self.mqtt.message_callback_remove(s_topic)\n self.mqtt.disconnect()",
"def filter_status_as_of(self, status_date: datetime.date) -> QuerySet:\n return self.model._filter_queryset_status_as_of(self, status_date)",
"def get_all_subscriptions(self, next_token=None):\r\n params = {'ContentType' : 'JSON'}\r\n if next_token:\r\n params['NextToken'] = next_token\r\n response = self.make_request('ListSubscriptions', params, '/', 'GET')\r\n body = response.read()\r\n if response.status == 200:\r\n return json.loads(body)\r\n else:\r\n boto.log.error('%s %s' % (response.status, response.reason))\r\n boto.log.error('%s' % body)\r\n raise self.ResponseError(response.status, response.reason, body)",
"def listSubscriptions() -> object:\n\n db = Db()\n return db.Subscriptions.objects().to_json()",
"def query_subscriptions(\n charge_status: Optional[Union[str, QuerySubscriptionsChargeStatusEnum]] = None,\n item_id: Optional[str] = None,\n limit: Optional[int] = None,\n offset: Optional[int] = None,\n sku: Optional[str] = None,\n status: Optional[Union[str, QuerySubscriptionsStatusEnum]] = None,\n subscribed_by: Optional[Union[str, QuerySubscriptionsSubscribedByEnum]] = None,\n user_id: Optional[str] = None,\n namespace: Optional[str] = None,\n x_additional_headers: Optional[Dict[str, str]] = None,\n **kwargs\n):\n if namespace is None:\n namespace, error = get_services_namespace()\n if error:\n return None, error\n request = QuerySubscriptions.create(\n charge_status=charge_status,\n item_id=item_id,\n limit=limit,\n offset=offset,\n sku=sku,\n status=status,\n subscribed_by=subscribed_by,\n user_id=user_id,\n namespace=namespace,\n )\n return run_request(request, additional_headers=x_additional_headers, **kwargs)",
"def subscriptions(self):\r\n return subs.Subscriptions(self)",
"def buildSubscriptionList(self):\r\n self._clearLists()\r\n unreadById = {}\r\n\r\n if not self.userId:\r\n self.getUserInfo()\r\n\r\n unreadJson = self.httpGet(ReaderUrl.UNREAD_COUNT_URL, { 'output': 'json', })\r\n unreadCounts = json.loads(unreadJson, strict=False)['unreadcounts']\r\n for unread in unreadCounts:\r\n unreadById[unread['id']] = unread['count']\r\n\r\n feedsJson = self.httpGet(ReaderUrl.SUBSCRIPTION_LIST_URL, { 'output': 'json', })\r\n subscriptions = json.loads(feedsJson, strict=False)['subscriptions']\r\n\r\n for sub in subscriptions:\r\n categories = []\r\n if 'categories' in sub:\r\n for hCategory in sub['categories']:\r\n cId = hCategory['id']\r\n if not cId in self.categoriesById:\r\n category = Category(self, hCategory['label'], cId)\r\n self._addCategory(category)\r\n categories.append(self.categoriesById[cId])\r\n\r\n try:\r\n feed = self.getFeed(sub['id'])\r\n if not feed:\r\n raise\r\n if not feed.title:\r\n feed.title = sub['title']\r\n for category in categories:\r\n feed.addCategory(category)\r\n feed.unread = unreadById.get(sub['id'], 0)\r\n except:\r\n feed = Feed(self,\r\n sub['title'],\r\n sub['id'],\r\n sub.get('htmlUrl', None),\r\n unreadById.get(sub['id'], 0),\r\n categories)\r\n if not categories:\r\n self.orphanFeeds.append(feed)\r\n self._addFeed(feed)\r\n\r\n specialUnreads = [id for id in unreadById\r\n if id.find('user/%s/state/com.google/' % self.userId) != -1]\r\n for type in self.specialFeeds:\r\n feed = self.specialFeeds[type]\r\n feed.unread = 0\r\n for id in specialUnreads:\r\n if id.endswith('/%s' % type):\r\n feed.unread = unreadById.get(id, 0)\r\n break\r\n\r\n return True",
"def get_subscriptions(self):\n return {}",
"def get_first_active_subscription(self):\n if self.has_active_subscription():\n return self.subscriptions.filter(active=True)[0]\n else:\n return None",
"def get_latest(course, asmt, submissions, users):\n latestSubmissions = []\n\n # Filter submissions by student\n for user in users:\n userSubs = submissions.filter(by=user)\n if userSubs:\n latestSubmissions.append(userSubs.latest())\n\n return latestSubmissions"
] | [
"0.5411569",
"0.5321596",
"0.53178895",
"0.5255911",
"0.51426303",
"0.50995034",
"0.50858927",
"0.5026834",
"0.4995144",
"0.4961031",
"0.49494302",
"0.49330226",
"0.4916144",
"0.48843575",
"0.48827955",
"0.48712513",
"0.4863807",
"0.48464385",
"0.48384252",
"0.4829559",
"0.48271126",
"0.47973916",
"0.47755083",
"0.4773197",
"0.47728196",
"0.47696027",
"0.47595382",
"0.4747369",
"0.4743575",
"0.47242525"
] | 0.641309 | 0 |
If the billing account already has an IOU account, return the update form. If there isn't an account yet, then return the creation form | def get_billing_details_form(billing_account):
try:
iou_account = billing_account.simple_processor_iou_account
return IOUAccountUpdateForm
except IOUAccount.DoesNotExist:
return IOUAccountCreationForm | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def manage():\n if current_user.is_agency:\n form = ManageAgencyUserAccountForm(user=current_user)\n else:\n form = ManageUserAccountForm(user=current_user)\n\n if request.method == \"POST\":\n if form.validate_on_submit():\n update_openrecords_user(form)\n redirect(url_for(\"auth.manage\"))\n else:\n flash(\"Account cannot be updated.\", category=\"danger\")\n return render_template(\"auth/manage_account.html\", form=form)\n else:\n form.autofill()\n\n return render_template(\n \"auth/manage_account.html\", form=form, is_agency=current_user.is_agency\n )",
"def edit_account_view(request):\n if request.user.is_authenticated:\n print(request.user.organization.phone)\n form = EditAccountForm(initial={\n #User model\n 'username': request.user,\n # Organization model\n 'name': request.user.organization.name,\n 'phone': request.user.organization.phone,\n 'address_line_1': request.user.organization.address_line_1,\n 'address_line_2': request.user.organization.address_line_2,\n 'zip_code' : request.user.organization.zip_code,\n 'city': request.user.organization.city,\n 'country': request.user.organization.country,\n },\n user=request.user\n )\n\n #If we receive POST data\n context = {\n 'form': form,\n 'submit_button_text': _('Update account details')\n }\n if request.method == 'POST':\n # Create a form instance and populate it with data from the request (binding):\n form = EditAccountForm(request.POST, user=request.user)\n context.update({'form': form})\n # Check if the form is valid:\n if form.is_valid():\n request.user.username = form.cleaned_data['username']\n request.user.email = form.cleaned_data['username']\n request.user.organization.name = form.cleaned_data['name']\n request.user.organization.phone = form.cleaned_data['phone']\n request.user.organization.address_line_1 = form.cleaned_data['address_line_1']\n request.user.organization.address_line_2 = form.cleaned_data['address_line_2']\n request.user.organization.zip_code = form.cleaned_data['zip_code']\n request.user.organization.city = form.cleaned_data['city']\n request.user.organization.country = form.cleaned_data['country']\n\n request.user.save()\n request.user.organization.save()\n messages.success(request, _('Your profile details was updated.'), extra_tags='alert alert-success')\n\n return render(request, 'edit_account_form.html', context)\n #if user not authenticated\n else:\n #this should never occcur\n logger.warning(\"%s %s: %s tried to edit someone else's account\"%(datetime.datetime.now().strftime('[%d/%m/%Y %H:%M:%S]'), 'WARNING: ', request.user))\n messages.error(request, _(\"Can't edit profile when you are not logged in.\"), extra_tags='alert alert-danger')\n return HttpResponseRedirect(reverse('loginc'))",
"def account():\n form = UpdateAccountForm()\n new_project_form = ProjectForm()\n\n if form.validate_on_submit():\n\n if form.picture.data: # if statement responsible for change of default picture\n picture_file = save_image(form.picture.data)\n current_user.img_file = picture_file\n\n current_user.user_name = form.user_name.data\n current_user.email = form.email.data\n db.session.commit()\n flash(\"Changes saved\", \"success\")\n\n return redirect(url_for('users.account'))\n\n elif request.method == \"GET\":\n form.user_name.data = current_user.user_name\n form.email.data = current_user.email\n\n img_file = url_for('static', filename='images/' + current_user.img_file)\n\n return render_template('account.html',\n title=\"Account\",\n form=form,\n img_file=img_file,\n new_project_form=new_project_form)",
"def account():\n \n form = UpdateAccountForm()\n \n # perform actions when the form is submitted\n if form.validate_on_submit():\n # checking if the form contains a picture file\n if form.picture.data:\n picture_file = save_picture(form.picture.data)\n current_user.image_file = picture_file\n # changing the current user details with the form data\n current_user.username = form.username.data\n current_user.email = form.email.data\n db.session.commit()\n flash('Your account has been updated!', 'success')\n return redirect(url_for('account'))\n # performs action if the form method is get\n elif request.method == 'GET':\n # setting the form data with the user data from the database\n form.username.data = current_user.username\n form.email.data = current_user.email\n image_file = url_for('static', filename='profile_pics/' + current_user.image_file)\n return render_template('account.html', title='Account',\n image_file=image_file, form=form)",
"def apply(self):\n changed = False\n account_exists = False\n update_account = False\n account_detail = self.get_account()\n\n if account_detail:\n account_exists = True\n\n if self.state == 'absent':\n changed = True\n\n elif self.state == 'present':\n # Check if we need to update the account\n\n if account_detail.username is not None and self.new_element_username is not None and \\\n account_detail.username != self.new_element_username:\n update_account = True\n changed = True\n\n elif account_detail.status is not None and self.status is not None \\\n and account_detail.status != self.status:\n update_account = True\n changed = True\n\n elif account_detail.initiator_secret is not None and self.initiator_secret is not None \\\n and account_detail.initiator_secret != self.initiator_secret:\n update_account = True\n changed = True\n\n elif account_detail.target_secret is not None and self.target_secret is not None \\\n and account_detail.target_secret != self.target_secret:\n update_account = True\n changed = True\n\n elif account_detail.attributes is not None and self.attributes is not None \\\n and account_detail.attributes != self.attributes:\n update_account = True\n changed = True\n else:\n if self.state == 'present' and self.status is None:\n changed = True\n\n if changed:\n if self.module.check_mode:\n pass\n else:\n if self.state == 'present':\n if not account_exists:\n self.create_account()\n elif update_account:\n self.update_account()\n\n elif self.state == 'absent':\n self.delete_account()\n\n self.module.exit_json(changed=changed)",
"def get_form(self, *args, **kwargs):\n form = super(ExpenseUpdateView, self).get_form(*args, **kwargs)\n # Only include Accounts in the Account dropdown that are associated with the current user\n form.fields['account'].queryset = Account.objects.filter(owner=self.request.user)\n return form",
"def account():\n\n form = UpdateUserForm()\n\n if form.validate_on_submit():\n print(form)\n if form.picture.data:\n username = current_user.username\n pic = add_profile_pic(form.picture.data,username)\n current_user.profile_image = pic\n\n current_user.username = form.username.data\n current_user.email = form.email.data\n db.session.commit()\n flash('User Account Updated')\n return redirect(url_for('users.account'))\n\n elif request.method == 'GET':\n form.username.data = current_user.username\n form.email.data = current_user.email\n\n profile_image = url_for('static', filename='profile_pics/' + current_user.profile_image)\n return render_template('account.html', profile_image=profile_image, form=form)",
"def create_account_form(request, post):\n username = post.get(\"username\")\n first_name = post.get(\"first_name\")\n last_name = post.get(\"last_name\")\n email = post.get(\"email\")\n\n phone_number = post.get(\"phone\")\n\n password = post.get(\"password\")\n\n height = float(post.get(\"height\"))\n weight = float(post.get(\"weight\"))\n sex = post.get(\"sex\")\n\n current_medications = post.get(\"medications\")\n allergies = post.get(\"allergies\")\n medical_conditions = post.get(\"medical_conditions\")\n family_history = post.get(\"family_history\")\n additional_info = post.get(\"additional_info\")\n primary_hospital = Hospital.objects.get(pk=post.get(\"primary_hospital\"))\n\n policy_number = int(post.get(\"policy_number\"))\n company = post.get(\"company\")\n\n if User.objects.filter(username=username).exists():\n messages.add_message(request, messages.ERROR, 'User already exists!')\n return False\n\n else:\n new_user = User.objects.create_user(\n username=username, password=password,\n first_name=first_name, last_name=last_name, email=email\n )\n\n new_user_profile = UserProfile.objects.create(\n user=new_user,\n phone_number=phone_number, status=UserStatus.objects.get(pk=3),\n primary_hospital=primary_hospital\n )\n\n medical_info = MedicalInformation.objects.create(\n height=height, weight=weight, sex=sex,\n medical_conditions=medical_conditions,\n allergies=allergies, medications=current_medications,\n family_history=family_history, additional_info=additional_info,\n user=new_user_profile\n )\n\n insurance = Insurance.objects.create(\n policy_number=policy_number, company=company, medical_information=medical_info,\n )\n\n return True",
"def acquisition_update(request, slug, id):\n #verifies if the company exists if not returns a 404 page\n company =get_object_or_404(Company,slug=slug)\n acquisition_reference = get_object_or_404(Acquisition, id=id,company=company)\n acquisition_form = AcquisitionForm(instance=acquisition_reference)\n\n #verifies the person has access to the company or is an incubator employee\n edit = validate_user_company_access_or_redirect(request,company)\n\n #if the request is GET presents info, \n if request.method == 'GET':\n return render_to_response('acquisition_form.html',{'form':acquisition_form, 'info': acquisition_reference},context_instance=RequestContext(request))\n else:\n acquisition_form = AcquisitionForm(request.POST, instance=acqusition_reference)\n #if is POST Validates the form is well filled and save it redirecting to the company page \n if acquisition_form.is_valid():\n acquisition_form.save()\n\n return HttpResponseRedirect('/company/'+str(slug))\n #if not well filled redirect to the original update page and display error\n else:\n return render_to_response('acquisition_form.html', \n {'form': acquisition_form, 'form_errors': acquisition_form.errors, 'info': acquisition_reference},\n context_instance=RequestContext(request))",
"def customer_profile(request):\r\n\r\n if request.method == \"GET\":\r\n user = request.user\r\n context = {\"user\": request.user}\r\n return render(request, 'customer_profile.html', context)\r\n\r\n elif request.method == \"POST\":\r\n\r\n if 'edit' in request.POST:\r\n user = request.user\r\n form = {\"formA\": UserCustomerFormA(instance = user), \"formB\": UserCustomerFormB(instance = user.customer)}\r\n context = {\"user\": request.user,\r\n \"form\": form}\r\n return render(request, 'customer_profile.html', context)\r\n\r\n else:\r\n req=request.POST\r\n form_user = {\"last_name\": req[\"last_name\"]}\r\n form_cust = {\"phone_number\": req[\"phone_number\"], \"street_address\": req[\"street_address\"], \"city\": req[\"city\"], \"state\": req[\"state\"], \"zipcode\": req[\"zipcode\"]}\r\n\r\n\r\n user_form = UserCustomerFormA(form_user)\r\n\r\n if user_form.is_valid():\r\n with connection.cursor() as cursor:\r\n cursor.execute(\"UPDATE auth_user SET last_name=%s WHERE id=%s\", [req[\"last_name\"], request.user.id])\r\n\r\n customer_form = UserCustomerFormB(form_cust)\r\n\r\n if customer_form.is_valid():\r\n with connection.cursor() as cursor:\r\n cursor.execute(\"UPDATE website_customer SET phone_number=%s, street_address=%s, city=%s, state=%s, zipcode=%s WHERE id=%s\", [req[\"phone_number\"], req[\"street_address\"], req[\"city\"], req[\"state\"], req[\"zipcode\"], request.user.customer.id])\r\n\r\n\r\n user = User.objects.raw(\"Select * From auth_user where id=%s\",[request.user.id])\r\n context = {\"user\": user[0]}\r\n return render(request, 'customer_profile.html', context)",
"def edit_account(request, id=None):\n account = id and get_object_or_404(Account, pk=id, user=request.user)\n if request.method == 'POST':\n form = EditAccountForm(instance=account, data=request.POST)\n if form.is_valid():\n account = form.save(commit=False)\n account.user = request.user\n account.save()\n return redirect(account)\n else:\n form = EditAccountForm(instance=account)\n return render(request, 'pages/form.html', {\n 'title': \"{} Account\".format(\"Edit\" if account else \"New\"),\n 'breadcrumbs': [account] if account else [],\n 'form': form,\n })",
"def account_update(request):\r\n params = request.params\r\n json_body = request.json_body\r\n user_acct = request.user\r\n\r\n if 'name' in params and params['name'] is not None:\r\n name = params.get('name')\r\n user_acct.name = name\r\n\r\n if 'name' in json_body and json_body['name'] is not None:\r\n name = json_body.get('name')\r\n user_acct.name = name\r\n\r\n if 'email' in params and params['email'] is not None:\r\n email = params.get('email')\r\n user_acct.email = email.lower()\r\n\r\n if 'email' in json_body and json_body['email'] is not None:\r\n email = json_body.get('email')\r\n user_acct.email = email.lower()\r\n\r\n return _api_response(request, user_acct.safe_data())",
"def funding_update(request, slug, id):\n #verifies if the company exists if not returns a 404 page\n company =get_object_or_404(Company,slug=slug)\n funding_reference = get_object_or_404(Funding, id=id,company=company)\n funding_form = FundingForm(instance=funding_reference)\n\n #verifies the person has access to the company or is an incubator employee\n edit = validate_user_company_access_or_redirect(request,company)\n\n #if the request is GET presents info, \n if request.method == 'GET':\n return render_to_response('funding_form.html',{'form':funding_form, 'info': funding_reference},context_instance=RequestContext(request))\n else:\n funding_form = FundingForm(request.POST, instance=funding_reference)\n #if is POST Validates the form is well filled and save it redirecting to the company page \n if funding_form.is_valid():\n funding_form.save(commit = False)\n\n return HttpResponseRedirect('/company/'+str(slug))\n #if not well filled redirect to the original update page and display error\n else:\n return render_to_response('funding_form.html', \n {'form': funding_form, 'form_errors': funding_form.errors, 'info': funding_reference},\n context_instance=RequestContext(request))",
"def crud_user(request):\n if request.POST['action'] == 'EDIT':\n username = request.POST['username']\n tel = request.POST['tel']\n mobile = request.POST['mobile']\n office = request.POST['office']\n num = request.POST['num']\n user = IMPUser.objects.get(username = username)\n user.tel = tel\n user.mobile = mobile\n user.office = office\n user.num = num\n user.save()\n return redirect(urlresolvers.reverse(\"address_page\"))\n #print(request.POST['tel'])\n #username = request.POST['username']\n #password = request.POST['password']\n #password1 = request.POST['password1']\n #tel = request.POST['tel']\n #try:\n # #if password.equals(password1)\n # User.objects.all().get(username = username) \n # return render(request, \"account/sign_up.html\", context={\"errmsg\":\"Duplicated User!\"})\n #except:\n # print(\"NO USER!\")\n # IMPUser.objects.create_user(username = username, password = password, tel=tel)\n return redirect(urlresolvers.reverse(\"sign_in\"))",
"def update_person(request):\n if not Permissions.can_process_bookswap(request.user):\n request.session['error_message'] = messages.BOOKSWAP_NO_PERM\n return get_previous_page(request, alternate='bookswap:admin_index')\n had_profile = request.session.pop('had_profile', False)\n uniqname = request.session.pop('uniqname', '')\n if had_profile:\n bsp = BookSwapPerson.objects.get(user_profile__uniqname=uniqname)\n form = BookSwapPersonForm(request.POST or None, instance=bsp)\n else:\n initial = {\n 'UMID': request.session.pop('UMID', ''),\n 'uniqname': uniqname,\n 'barcode': request.session.pop('barcode', ''),\n }\n form = BookSwapPersonFormNoProfile(request.POST or None, initial=initial)\n \n if request.method == 'POST':\n if form.is_valid():\n bsp = form.save()\n uniqname = bsp.user_profile.uniqname\n request.session['success_message'] = ('User created/updated.')\n if BookSwapStatus.can_receive(AcademicTerm.get_current_term()):\n return redirect('bookswap:receive_book_start', uniqname=uniqname)\n elif BookSwapStatus.can_sell(AcademicTerm.get_current_term()):\n return redirect('bookswap:sell_book_start', uniqname=uniqname)\n else:\n request.session['info_message'] = ('Book Swap not open for '\n 'receiving or selling')\n return redirect('bookswap:admin_index')\n else:\n request.session['error_message'] = messages.GENERIC_SUBMIT_ERROR\n request.session['had_profile'] = had_profile\n request.session['uniqname'] = uniqname\n else:\n request.session['had_profile'] = had_profile\n request.session['uniqname'] = uniqname\n template = loader.get_template('generic_form.html')\n context_dict = {\n 'form': form,\n 'subnav': 'admin',\n 'has_files': False,\n 'submit_name': 'Create/update user',\n 'form_title': 'Create/update the user information',\n 'help_text': ('Please confirm that the following is correct and '\n 'update as necessary. Note that for sellers an address '\n 'is required.'),\n 'base': 'bookswap/base_bookswap.html',\n }\n context_dict.update(get_permissions(request.user))\n context_dict.update(get_common_context(request))\n context = RequestContext(request, context_dict)\n return HttpResponse(template.render(context))",
"def account_view(request):\n \"\"\"if request.user.is_authenticated:\n form = None\n\n # TODO Objective 3: Create Forms and Handle POST to Update UserInfo / Password\n\n user_info = models.UserInfo.objects.get(user=request.user)\n context = { 'user_info' : user_info,\n 'form' : form }\n return render(request,'account.djhtml',context)\n request.session['failed'] = True\n return redirect('login:login_view')\n \"\"\"\n\n if request.user.is_authenticated:\n form = None\n # TODO Objective 3: Create Forms and Handle POST to Update UserInfo / Password\n existingUserInfo = models.UserInfo.objects.get(user=request.user)\n print(\"existingUserInfo:----------\",existingUserInfo.location)\n if request.method == 'POST':\n formName = request.POST.get('name')\n print(\"-------formName:\" + formName);\n\n if (formName == 'pwdForm'):\n password = request.POST['password']\n if password is not None and password != \"\":\n user = get_user(request)\n user.set_password(password)\n user.save()\n return redirect('login:login_view')\n else:\n request.user.employment = request.POST['employment']\n request.user.location = request.POST['location']\n request.user.birthday = request.POST['birthday']\n request.user.interests = request.POST['interests']\n inter = models.Interest(label=request.POST['interests'])\n inter.save()\n request.user.save()\n\n if request.POST['employment'] != '':\n existingUserInfo.employment = request.user.employment\n\n\n if request.POST['location'] != '':\n existingUserInfo.location = request.user.location\n\n if request.POST['birthday'] != \"\":\n existingUserInfo.birthday = request.user.birthday\n elif existingUserInfo.birthday==None:\n # existingUserInfo.birthday = datetime.strptime(str(existingUserInfo.birthday), '%Y-%m-%d')\n existingUserInfo.birthday = None\n\n if request.POST['interests'] != \"\" and request.POST['interests'] is not None:\n inter = models.Interest(label=request.POST['interests'])\n inter.save()\n existingUserInfo.interests.add(inter)\n\n existingUserInfo.save()\n\n\n context = {'user_info': existingUserInfo,\n 'login_form': form}\n return render(request, 'account.djhtml', context)\n request.session['failed'] = True\n return redirect('login:login_view')",
"def create_account_form(erroneous_form=None):\n form = erroneous_form if erroneous_form else CreateAccountForm()\n form.set_site_choices()\n\n return {'form': form}",
"def customer_update(request, slug, id):\n #verifies if the company exists if not returns a 404 page\n company =get_object_or_404(Company,slug=slug)\n customer_reference = get_object_or_404(Customer, id=id,company=company)\n customer_form = CustomerForm(instance=customer_reference)\n\n #verifies the person has access to the company or is an incubator employee\n edit = validate_user_company_access_or_redirect(request,company)\n\n #if the request is GET presents info, \n if request.method == 'GET':\n return render_to_response('customer_form.html',{'form':customer_form, 'info': customer_reference},context_instance=RequestContext(request))\n else:\n customer_form = CustomerForm(request.POST, instance=customer_reference)\n #if is POST Validates the form is well filled and save it redirecting to the company page \n if customer_form.is_valid():\n customer_form.save()\n\n return HttpResponseRedirect('/company/'+str(slug))\n #if not well filled redirect to the original update page and display error\n else:\n return render_to_response('customer_form.html', \n {'form': customer_form, 'form_errors': customer_form.errors, 'info': customer_reference},\n context_instance=RequestContext(request))",
"def profile(request, info=\"\", error_msg=\"\", messages=\"\"):\r\n try:\r\n user = _validate_and_get_geniuser(request)\r\n except LoggedInButFailedGetGeniUserError:\r\n return _show_failed_get_geniuser_page(request)\r\n\r\n email_form = forms.gen_edit_user_form(instance=user)\r\n affiliation_form = forms.gen_edit_user_form(instance=user)\r\n password_form = forms.EditUserPasswordForm()\r\n\r\n if request.method == 'POST':\r\n if 'affiliation' in request.POST:\r\n affiliation_form = forms.gen_edit_user_form(('affiliation',), request.POST, instance=user)\r\n if affiliation_form.is_valid():\r\n new_affiliation = affiliation_form.cleaned_data['affiliation']\r\n interface.change_user_affiliation(user, new_affiliation)\r\n info =\"Affiliation has been successfully changed to %s.\" % (user.affiliation)\r\n elif 'email' in request.POST:\r\n email_form = forms.gen_edit_user_form(('email',), request.POST, instance=user)\r\n if email_form.is_valid():\r\n new_email = email_form.cleaned_data['email']\r\n interface.change_user_email(user, new_email)\r\n info =\"Email has been successfully changed to %s.\" % (user.email)\r\n elif 'password1' in request.POST:\r\n password_form = forms.EditUserPasswordForm( request.POST, instance=user)\r\n if password_form.is_valid():\r\n new_password = password_form.cleaned_data['password1']\r\n interface.change_user_password(user, new_password)\r\n info =\"Password has been successfully changed\"\r\n\r\n username = user.username\r\n affiliation = user.affiliation\r\n email = user.email\r\n port = user.usable_vessel_port\r\n has_privkey = user.user_privkey != None\r\n #currently not used, needed if editing user port is allowed\r\n #port_range = interface.get_useable_ports()\r\n #port_range_min = port_range[0]\r\n #port_range_max = port_range[-1]\r\n\r\n return render_to_response('control/profile.html',\r\n {'email_form' : email_form,\r\n 'affiliation_form' : affiliation_form,\r\n 'password_form' : password_form,\r\n 'username' : username,\r\n 'affiliation' : affiliation,\r\n 'email' : email,\r\n 'port' : port,\r\n 'api_key' : user.api_key,\r\n 'has_privkey' : has_privkey,\r\n #'port_range_min' : port_range_min,\r\n #'port_range_max' : port_range_max,\r\n 'info' : info,\r\n 'error_msg' : error_msg,\r\n 'messages' : messages},\r\n context_instance=RequestContext(request))",
"def admin_update_account_type():\n session_id = request.args.get('session-id', None)\n user_id = request.args.get('user-id', None)\n user_id_to_update = request.args.get('user-id-to-update', None)\n account_type = request.args.get('account-type', None)\n if check_authentication(session_id, user_id) and is_admin_user(user_id):\n update_account_type(user_id_to_update, account_type)\n users_list = get_users_list()\n return render_template('admin_area.html', user=user_id, session_id=session_id, users_list=users_list)\n else:\n return render_template('home.html', cars_list=get_cars_preview(), news_list=get_news_list(), authjs=False,\n preview_length=get_cars_preview().__len__(), del_session_cookie=True)",
"def open_account():\n print(\"\\n\")\n print(messages.open_account)\n u_id = pyip.inputInt(\"Id: \", greaterThan=0)\n name = pyip.inputCustom(raiseNameError, prompt=\"Name: \")\n address = pyip.inputCustom(raiseAddressError, prompt=\"Address: \")\n email = pyip.inputEmail(\"Email: \")\n balance = pyip.inputInt(\"Balance: \", min=0)\n password = pyip.inputPassword(\"Password: \")\n\n user_data = [u_id, name, address, balance, email, password]\n result = BankOperationsBackend.open_account(user_data)\n\n start_again() if result else BankOperationsUi.open_account()",
"def order_submitted(request, order_id):\n profile_details = ['first_name', 'last_name', 'running_club', 'address_line_1', 'address_line_2', 'address_line_3', 'town_or_city', 'county', 'postcode']\n details_to_update = False\n marketing_opted_in = False\n order_id = order_id\n # registration_form = UserRegistrationForm(request.POST or None, initial={'email': request.session['email']})\n profile_details = {\n 'email' : request.session.get('email', None), \n 'running_club' : request.session.get('running_club', None),\n 'first_name' : request.session.get('first_name', None), \n 'last_name' : request.session.get('last_name', None),\n 'address_line_1' : request.session.get('address_line_1', None),\n 'address_line_2' : request.session.get('address_line_2', None), \n 'address_line_3' : request.session.get('address_line_3', None), \n 'town_or_city' : request.session.get('town_or_city', None), \n 'county' : request.session.get('county', None), \n 'postcode' : request.session.get('postcode', None) \n }\n if request.method == \"POST\":\n registration_form = UserRegistrationForm(request.POST)\n if registration_form.is_valid():\n registration_form.save()\n user = auth.authenticate(username=request.POST['email'],\n password=request.POST['password1']) \n if user: \n auth.login(user=user, request=request)\n user.profile.running_club = profile_details['running_club']\n user.first_name = profile_details['first_name']\n user.last_name = profile_details['last_name']\n user.profile.address_line_1 = profile_details['address_line_1']\n user.profile.address_line_2 = profile_details['address_line_2']\n user.profile.address_line_3 = profile_details['address_line_3']\n user.profile.town_or_city = profile_details['town_or_city']\n user.profile.county = profile_details['county']\n user.profile.postcode = profile_details['postcode']\n user.profile.save()\n messages.success(request, \"You have successfully registered!\")\n else:\n messages.error(request, \"Could not register\")\n return redirect(reverse('index'))\n else:\n messages.error(request, \"Unable to register your account at this time\") \n else:\n registration_form = UserRegistrationForm(request.POST or None, initial={'email': request.session['email']}) \n return render(request, 'order_submitted.html', {\n 'details_to_update': details_to_update, \n 'marketing_opted_in': marketing_opted_in, \n 'registration_form': registration_form,\n \"order_id\": order_id,\n })",
"def office_update(request, slug, id):\n #verifies if the company exists if not returns a 404 page\n company =get_object_or_404(Company,slug=slug)\n office_reference = get_object_or_404(Office, id=id,company=company)\n office_form = OfficeForm(instance=office_reference)\n\n #verifies the person has access to the company or is an incubator employee\n edit = validate_user_company_access_or_redirect(request,company)\n\n #if the request is GET presents info, \n if request.method == 'GET':\n return render_to_response('office_form.html',{'form':office_form, 'info': office_reference},context_instance=RequestContext(request))\n else:\n office_form = OfficeForm(request.POST, instance=office_reference)\n #if is POST Validates the form is well filled and save it redirecting to the company page \n if office_form.is_valid():\n office_form.save(commit = False)\n\n return HttpResponseRedirect('/company/'+str(slug))\n #if not well filled redirect to the original update page and display error\n else:\n return render_to_response('office_form.html', \n {'form': office_form, 'form_errors': office_form.errors, 'info': office_reference},\n context_instance=RequestContext(request))",
"def create_account():\n\n return render_template('account.html')",
"def setup_bank(request):\n if not request.user.userbank.exists():\n return render(request, \"setup_bank.html\", {})\n return HttpResponseRedirect('/home')",
"def profile_edit():\n form = ProfileForm(obj=current_user)\n\n if form.validate_on_submit():\n form.populate_obj(current_user)\n\n try:\n correct = True\n db.session.commit()\n\n flash(_('Profile updated correctly'), 'success')\n\n return render_template('admin/profile/edit.html', form=form)\n\n except IntegrityError:\n # Email already exists\n correct = False\n form.errors.email.append(_('Email is already registered'))\n\n return render_template('admin/profile/edit.html', form=form)\n\n except Exception:\n # Catch anything unknown\n correct = False\n\n flash(_('Failed to update profile, contact an administrator'), 'error')\n\n return render_template('admin/profile/edit.html', form=form)\n\n finally:\n if not correct:\n db.session.rollback()\n\n return render_template('admin/profile/edit.html', form=form)",
"def management_update(request, slug, id):\n #verifies if the company exists if not returns a 404 page\n company =get_object_or_404(Company,slug=slug)\n management_reference = get_object_or_404(Management, id=id,company=company)\n management_form = ManagementForm(instance=management_reference)\n\n #verifies the person has access to the company or is an incubator employee\n edit = validate_user_company_access_or_redirect(request,company)\n\n #if the request is GET presents info, \n if request.method == 'GET':\n return render_to_response('management_form.html',{'form':management_form, 'info': management_reference},context_instance=RequestContext(request))\n else:\n management_form = ManagementForm(request.POST, instance=management_reference)\n #if is POST Validates the form is well filled and save it redirecting to the company page \n if management_form.is_valid():\n management_form.save()\n\n return HttpResponseRedirect('/company/'+str(slug))\n #if not well filled redirect to the original update page and display error\n else:\n return render_to_response('management_form.html', \n {'form': management_form, 'form_errors': management_form.errors, 'info': management_reference},\n context_instance=RequestContext(request))",
"def competitors_update(request, slug,id):\n #verifies if the company exists if not returns a 404 page\n company =get_object_or_404(Company,slug=slug)\n competitors_reference = get_object_or_404(Competitors, id=id,company=company)\n competitors_form = CompetitorsForm(instance=competitors_reference)\n\n #verifies the person has access to the company or is an incubator employee\n edit = validate_user_company_access_or_redirect(request,company)\n\n #if the request is GET presents info, \n if request.method == 'GET':\n return render_to_response('competitors_form.html',{'form':competitors_form, 'info': competitors_reference},context_instance=RequestContext(request))\n else:\n competitors_form = CompetitorsForm(request.POST)\n #if is POST Validates the form is well filled and save it redirecting to the company page \n if competitors_form.is_valid():\n cf= competitors_form.save(commit = False)\n #verify the item is not the same as the company page\n if str(company.name) == str(cf.name):\n \n form_errors = {\"Name - You can't be a competitor of Your own company. \"}\n return render_to_response('competitors_form.html', \n {'form': competitors_form, 'form_errors': form_errors, 'info': competitors_reference},\n context_instance=RequestContext(request))\n #verify if other companies with the same info exists anywhere\n try: \n comparison = Competitors.objects.get(name=cf.name,company= company)\n\n if competitors_reference.id == comparison.id:\n competitors_reference.name = cf.name\n competitors_reference.save()\n else:\n form_errors = {\"Name - The company \" + str(cf.name).capitalize() + \" already exists as a competitor of \" +str(company.name).capitalize() +\".\" }\n return render_to_response('competitors_form.html', \n {'form': competitors_form, 'form_errors': form_errors, 'info': competitors_reference},\n context_instance=RequestContext(request))\n\n except:\n competitors_reference.name = cf.name\n competitors_reference.save()\n\n\n return HttpResponseRedirect('/company/'+str(slug))\n #if not well filled redirect to the original update page and display error\n else:\n return render_to_response('competitors_form.html', \n {'form': competitors_form, 'form_errors': competitors_form.errors, 'info': competitors_reference},\n context_instance=RequestContext(request))",
"def companylink_update(request, slug):\n\n #verifies if the company exists if not returns a 404 page\n company =get_object_or_404(Company,slug=slug)\n companylink_reference = get_object_or_404(CompanyLink, company=company)\n companylink_form = CompanyLinkForm(instance=companylink_reference)\n\n #verifies the person has access to the company or is an incubator employee\n edit = validate_user_company_access_or_redirect(request,company)\n\n #if the request is GET presents info, \n if request.method == 'GET':\n return render_to_response('companylink_form.html',{'form':companylink_form, 'info': companylink_reference},context_instance=RequestContext(request))\n else:\n companylink_form = CompanyLinkForm(request.POST, instance=companylink_reference)\n #if is POST Validates the form is well filled and save it redirecting to the company page \n if companylink_form.is_valid():\n companylink_form.save()\n\n return HttpResponseRedirect('/company/'+str(slug))\n #if not well filled redirect to the original update page and display error\n else:\n return render_to_response('companylink_form.html', \n {'form': companylink_form, 'form_errors': companylink_form.errors, 'info': companylink_reference},\n context_instance=RequestContext(request))",
"def edit_UI_transaction(account):\n\t_day = read_day()\n\t_amount = read_amount()\n\t_type = read_type()\n\ttransaction_at = transaction_exists(_day, _amount, _type, account)\n\tif (transaction_at != -1):\n\t\tprint('Actualizare tranzactie...')\n\t\t_day = read_day()\n\t\t_amount = read_amount()\n\t\t_type = read_type()\n\t\tedit_transaction(transaction_at, _day, _amount, _type, account)\n\t\tprint('Tranzactie actualizata.')\n\telse:\n\t\tprint('Tranzactie inexistenta.')"
] | [
"0.6070687",
"0.6037547",
"0.5988173",
"0.5983497",
"0.5789755",
"0.57439816",
"0.56556976",
"0.563131",
"0.5623569",
"0.5617682",
"0.5516923",
"0.54676425",
"0.5454282",
"0.54209024",
"0.5419233",
"0.5396492",
"0.53896946",
"0.53603184",
"0.5337848",
"0.52935314",
"0.52873415",
"0.5275282",
"0.52707505",
"0.5253319",
"0.52410483",
"0.5237607",
"0.5220519",
"0.5193706",
"0.5178654",
"0.51654017"
] | 0.7438349 | 0 |
`sender` is the subscription instance requiring approval | def do_subscription_approval(sender, **kwargs):
req_payment = sender.get_product_class().get_requires_payment_details()
if not req_payment or has_valid_billing_details(sender.billing_account):
status = 'approved'
else:
status = 'declined'
sender.set_current_approval_status(status)
return status | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def save(self):\n owner = self.context[\"request\"].user\n recipient = self._recipient_email_inst.user\n\n logger.info(\n \"Transferring subscription %r from user %r to user %r\",\n owner.know_me_subscription,\n owner.pk,\n recipient.pk,\n )\n\n with transaction.atomic():\n models.Subscription.objects.filter(user=recipient).delete()\n models.Subscription.objects.filter(user=owner).update(\n user=recipient\n )",
"def subscribe(receiver):",
"def subscribe(receiver):",
"def subscribe(receiver):",
"def awaiting_payment(self):",
"def no_save_individual_subscription(sender, instance, **kwargs):\n try:\n Subscription.objects.get(pk=instance.pk) # looking if the subscription exist, if the case, we assume here is updating active status or email status\n except:\n if instance.user is not None:\n subs_ids = instance.user.groups.values_list('subscription')\n for sub in subs_ids:\n if None not in sub:\n alarm = Subscription.objects.get(id=sub[0]).alarm\n if alarm == instance.alarm:\n raise ValidationError('The user is subscribed to the same alarm for a group')\n\n subs = Subscription.objects.filter(user=instance.user)\n for sub in subs:\n if sub.alarm == instance.alarm:\n raise ValidationError('The user is subscribed to this alarm')",
"def subscribe(self, request):\n email = self.cleaned_data.get('email')\n\n email_name, domain_part = email.rsplit('@', 1)\n domain_name = '@' + domain_part\n email_domain, created = Domain.objects.get_or_create(name=domain_name)\n\n subscriber, created = Subscriber.objects.get_or_create(email=email, mailing_list=self.mailing_list, defaults={\n 'domain': email_domain\n })\n subscriber.status = Status.PENDING\n subscriber.optin_ip_address = get_client_ip(request)\n subscriber.optin_date = timezone.now()\n subscriber.save()\n\n if not created:\n subscriber.tokens.filter(description='confirm_subscription').delete()\n\n token = subscriber.tokens.create(description='confirm_subscription')\n current_site = get_current_site(request)\n protocol = 'https' if request.is_secure() else 'http'\n domain = current_site.domain\n path = reverse('subscribers:confirm_double_optin_token', kwargs={\n 'mailing_list_uuid': self.mailing_list.uuid,\n 'token': token.text\n })\n confirm_link = '%s://%s%s' % (protocol, domain, path)\n\n confirm_email = self.mailing_list.get_confirm_email_template()\n confirm_email.send(subscriber.get_email(), {\n 'confirm_link': confirm_link\n })\n\n return subscriber",
"def sender(self, sender):\n\n self._sender = sender",
"def sender(self, sender):\n\n self._sender = sender",
"def sender(self, sender):\n\n self._sender = sender",
"def sender(self, sender):\n\n self._sender = sender",
"def sender(self, sender):\n\n self._sender = sender",
"def _subscribe(self):\n self.subscribed = True\n self.subscribe_date = now()\n self.unsubscribed = False",
"def test_create_subscription(self):\n pass",
"def subscribe(receiver, catchup):",
"def handle_create(self):\n subscription = self.client().subscription(\n self.properties[self.QUEUE_NAME],\n subscriber=self.properties[self.SUBSCRIBER],\n ttl=self.properties[self.TTL],\n options=self.properties[self.OPTIONS]\n )\n self.resource_id_set(subscription.id)",
"def subscribe(self, subject):\n pass",
"def no_save_subscription_if_dont_have_permissions(sender, instance, **kwargs):\n user = instance.user if instance.user else None\n group = instance.group if instance.group else None\n\n if user:\n if 'can_subscribe' not in get_user_perms(user, instance.alarm):\n raise ValidationError(\"User don't have permissions to subscribe to this alarm\")\n elif group:\n if 'can_subscribe' not in get_group_perms(group, instance.alarm):\n raise ValidationError(\"Group don't have permissions to subscribe to this alarm\")\n else:\n raise ValidationError(\"BAD REQUEST. Check your selections.\")",
"def create(self, validated_data):\n subscription = super().create(validated_data)\n subscription.send_verification_email()\n return subscription",
"def sender(self):\n return self._sender",
"def __init__(self, sender):\r\n\t\tself.sender = sender",
"def _subscribe(self):\n if self.subscribed:\n return False\n return {}",
"def test_issue_subscriptions(self):\n pass",
"def save(self, **kwargs):\n if CustomerModel.objects.filter(user__email=self.cleaned_data['email']).exists():\n logger.info('Subscription from {} dropped, email address exists.'.format(self.cleaned_data['email']))\n return self.instance\n # email is not assigned by the form probably because it is a related user object field\n self.instance.email = self.cleaned_data['email']\n if send_confirmation_email(self.request, self.instance):\n self.instance = super(SubscribeForm, self).save(**kwargs)\n return self.instance",
"def test_get_subscription(self):\n pass",
"def test_subscribe_offer(self):\n pass",
"def _want_subscription() -> bool:\n prompt = (\n 'Would you be willing, once your first certificate is successfully issued, '\n 'to share your email address with the Electronic Frontier Foundation, a '\n \"founding partner of the Let's Encrypt project and the non-profit organization \"\n \"that develops Certbot? We'd like to send you email about our work encrypting \"\n \"the web, EFF news, campaigns, and ways to support digital freedom. \")\n return display_util.yesno(prompt, default=False)",
"def __get_sender_id(self):\n return self.__sender_id",
"def key( self, mess, args):\n user = mess.getFrom()\n if user in self.users:\n return 'You are already subscribed.'\n else:\n self.users[user] = args\n self.log( '%s subscribed to the broadcast.' % user)\n return 'You are now subscribed.'",
"def subscription(bot, update):\n chat_id = update.message.chat_id\n bot.sendMessage(chat_id=chat_id, text=SUBSCRIPTION_MSG, parse_mode='markdown', \n disable_web_page_preview=True)\n \n mp.track(get_user_info(chat_id)['PID'], 'Checked Subscription')"
] | [
"0.64126",
"0.6349764",
"0.6349764",
"0.6349764",
"0.6021129",
"0.6001644",
"0.5986496",
"0.59361017",
"0.59361017",
"0.59361017",
"0.59361017",
"0.59361017",
"0.59173584",
"0.58232635",
"0.58184",
"0.581205",
"0.580477",
"0.58026046",
"0.5777631",
"0.57491696",
"0.5715194",
"0.5714829",
"0.57100326",
"0.56881845",
"0.56478417",
"0.56372833",
"0.5601723",
"0.5589677",
"0.55843604",
"0.5583826"
] | 0.6396265 | 1 |
returns a function to conditionally dispatch a view based on a user's current subscription status If the user is already subscribed to the plan, dispatch the current_subscription_view If the plan requires billing details, and the user doesn't have billing details on file (as reported by the processor), then dispatch the billing_details_view Otherwise (if the plan doesn't require billing details, or the user already has billing details on file), then dispatch the confirmation_view | def subscription_view(
current_subscription_view=CurrentSubscriptionView.as_view(),
billing_details_view=SubscriptionBillingDetailsView.as_view(),
confirmation_view=SubscriptionConfirmationView.as_view(),
):
def dispatch(request, *args, **kwargs):
cur_product_cls = request.user.billing_account.get_current_product_class()
req_product_name = kwargs['product']
try:
req_product_cls = billing.loading.get_product(req_product_name)
except ValueError:
raise Http404
if req_product_cls not in request.user.billing_account.get_visible_products():
raise Http404
if cur_product_cls == req_product_cls:
return current_subscription_view(request, *args, **kwargs)
elif (
req_product_cls.get_requires_payment_details()
and not request.user.billing_account.has_valid_billing_details()
):
return billing_details_view(request, *args, **kwargs)
elif (
not req_product_cls.get_requires_payment_details()
or request.user.billing_account.has_valid_billing_details()
):
return confirmation_view(request, *args, **kwargs)
else:
raise RuntimeError('Error: null condition should never occur')
return dispatch | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def subscription_purchase(request):\n if request.method==\"POST\":\n # POST request means user submitted Stripe card form\n if \"stripeToken\" in request.POST:\n try:\n customer = stripe.Charge.create(\n amount = 60*100,\n currency = \"EUR\",\n description = request.user.email,\n source = request.POST.get('stripeToken'),\n )\n except stripe.error.CardError:\n messages.error(request, \"Your card was declined!\")\n return redirect('subscription_purchase')\n if customer.paid:\n \"\"\" If a subscription already existed, this was a renewal\n if not, new Subscription is created, default expiry calculated\n within the Subscription model \"\"\"\n subscription, created = Subscription.objects.get_or_create(\n user=request.user\n )\n # Each subscription renewal adds credits to user's profile\n profile = request.user.profile\n profile.credits += settings.CREDITS_PER_SUBSCRIPTION\n profile.save()\n if created:\n return render(request, 'subscription_added.html')\n else:\n # For renewals, add 365 days to expiry date\n subscription.expires += timedelta(days=365)\n subscription.save()\n return render(request, 'subscription_added.html')\n else:\n messages.error(request, \"Unable to take payment\")\n return redirect('subscription_purchase')\n else:\n messages.error(request, \"Stripe token was invalid\")\n return redirect('subscription_purchase')\n else:\n # Non-POST request means we render the card form.\n return render(request, \"subscription_checkout.html\", {\n 'publishable': settings.STRIPE_PUBLISHABLE\n })",
"def view(self, user, notificationrequested, *args):\n if user.is_anonymous or user.is_client:\n return False\n\n if user.is_administrator:\n return True\n\n if user.is_manager:\n return False\n\n if user.is_advisor and user.group == notificationrequested.group:\n return True\n\n return self.admin_permission(user, notificationrequested, *args)",
"def change_plan(request):\n\n data = request.data\n\n start_date = datetime.datetime.now().strftime(\"%c\")\n end_date = end_date = (datetime.datetime.now() + datetime.timedelta(30)).strftime(\"%x\")\n \n # print(data[\"subscription_plan\"])\n \n try: \n user = User.objects.get(email=request.user) \n customer = Customer.objects.get(user=user)\n subscription_plan = SubscriptionPlan.objects.get(subscription_plan_name=data[\"subscription_plan\"])\n\n if customer.is_subscribe:\n stripe.Subscription.delete(\n customer.subscription_id,\n ) \n\n plan_id = \"price_1JsHMxSDkRo5FXlkOsq2QHSV\"\n\n if data[\"subscription_plan\"]== \"Globalnet Silver\":\n plan_id = \"price_1JsHOJSDkRo5FXlkQmfEQzhN\"\n \n if data[\"subscription_plan\"]== \"Globalnet Gold\":\n plan_id = \"price_1JsHPFSDkRo5FXlk9VSl41rV\"\n\n # Create new stripe subscription\n subscription = stripe.Subscription.create(\n customer = customer.stripe_id,\n items = [{'plan':plan_id}]\n ) \n \n # Update SubscriptionData \n subscription_user_data = SubscriptionData.objects.filter(subscriber=customer.primary_number) \n for data_subscriber in subscription_user_data:\n if(data_subscriber.subscription_start == customer.start_date):\n data_subscriber.subscription_end = start_date \n data_subscriber.save() \n break \n \n \n # Change subscription plan info\n customer.subscription_plan = subscription_plan\n customer.start_date = start_date\n customer.end_date = end_date\n customer.subscription_id = subscription.id\n customer.is_subscribe = True\n customer.save()\n \n # Create new subscription data \n SubscriptionData.objects.create(\n subscriber = customer.primary_number,\n subscription = subscription_plan.subscription_plan_name,\n subscription_start = start_date,\n subscription_end = end_date \n \n )\n \n serializer= CustomerSerializer(customer,many=False)\n \n return Response(serializer.data)\n \n except Exception as e: \n message = {\"Error\":str(e)}\n return Response(message)",
"def check_internal_api_for_subscription(namespace_user):\n plans = []\n if namespace_user.organization:\n query = organization_skus.get_org_subscriptions(namespace_user.id)\n org_subscriptions = list(query.dicts()) if query is not None else []\n for subscription in org_subscriptions:\n subscription_id = subscription[\"subscription_id\"]\n sku = marketplace_subscriptions.get_subscription_sku(subscription_id)\n plans.append(get_plan_using_rh_sku(sku))\n pass\n else:\n user_account_number = marketplace_users.get_account_number(namespace_user)\n if user_account_number:\n plans = marketplace_subscriptions.get_list_of_subscriptions(\n user_account_number, filter_out_org_bindings=True, convert_to_stripe_plans=True\n )\n return plans",
"def check_account_status(request):\n\n user = request.user\n\n if not user.is_authenticated():\n return {\n 'current_user': user,\n 'check_account_status_url': reverse('check_account_status'),\n }\n\n session = request.session\n\n flag = session.get('show_email_confirmation_dialog', True)\n show = not user.has_activated_account and flag\n session['show_email_confirmation_dialog'] = False\n\n # We don't want so show email confirmation when use is trying to buy a ticket.\n if 'payment-details' in request.path:\n show = False\n\n return {\n 'current_user': user,\n 'show_email_confirmation_dialog': False,\n 'check_account_status_url': reverse('check_account_status'),\n }",
"def get(self):\n cus = None\n user = get_authenticated_user()\n private_repos = model.user.get_private_repo_count(user.username)\n\n if user.stripe_id:\n try:\n cus = billing.Customer.retrieve(user.stripe_id)\n except stripe.error.APIConnectionError as e:\n abort(503, message=\"Cannot contact Stripe\")\n\n if cus.subscription:\n return subscription_view(cus.subscription, private_repos)\n\n return {\n \"hasSubscription\": False,\n \"isExistingCustomer\": cus is not None,\n \"plan\": \"free\",\n \"usedPrivateRepos\": private_repos,\n }",
"def cancel_customer_subscription(request):\n \n user = request.user \n \n try: \n user = User.objects.get(email=user) \n customer = Customer.objects.get(user=user)\n\n if customer.subscription_plan == SubscriptionPlan.objects.get(subscription_plan_name=\"Globalnet Gold\"): \n stripe.Subscription.delete(\n customer.subscription_id,\n )\n customer.subscription_id = \"\"\n customer.is_subscribe = False\n customer.save()\n\n user.is_active = False\n user.save()\n \n return Response({\"message\":\"Your subscription cancel Successfully. Your Number is deactivated.Company has own your Number\"})\n \n return Response({\"message\":\"You Can not Cancel your plan\"})\n \n except Exception as e: \n message = {\"Error\":str(e)}\n \n return Response(message)",
"def view(self, user, action, *args):\n if user.is_anonymous or user.is_client:\n return False\n\n if user.is_administrator:\n return True\n\n if user.is_manager:\n return False\n\n # TODO check groups in request maybe ? dunno\n if user.is_advisor:\n return True\n\n return self.admin_permission(user, action, *args)",
"def can_view(self, user):\n if self.applicant == user:\n return True\n elif user.has_perm('funding.view_all_applications'):\n # Fundihg commitee\n return True\n elif user.has_perm('funding.make_application_decisions'):\n # Fundihg manager - should have the view permissions, but just in case\n return True\n return False",
"def user_plan(request, username):\n\n try:\n user = MiVotiUser.objects.get(username=username)\n except MiVotiUser.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if not user.gdrive_id_json_plan:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n # Obtener el plan\n dict_plan = gdrive_obtener_contenido_plan(user.gdrive_id_json_plan)\n return Response(dict_plan)\n elif request.method == 'POST':\n # Crear un nuevo Plan\n serializer = PlanEstudioUsuarioSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save(user)\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == 'DELETE':\n # Eliminar el plan\n ruta_local = os.path.join('planes_json_cache', user.gdrive_id_json_plan)\n\n if os.path.exists(ruta_local):\n os.remove(ruta_local)\n\n archivo_plan_json = apps.get_app_config('planeador').g_drive.CreateFile(\n {'id': user.gdrive_id_json_plan})\n\n archivo_plan_json.Delete()\n\n user.gdrive_id_json_plan = None\n user.save()\n\n return Response(status=status.HTTP_204_NO_CONTENT)",
"def get_customer_portal_session(self, request):\n customer = self.get_customer()\n\n has_subscription = False\n for subscription in customer.subscriptions.all():\n if subscription.is_valid():\n has_subscription = True\n break\n\n if not has_subscription:\n # At this point it would be good to subscribe the user to the selected product / tier\n # but with out a payment method, using anything other than the free product\n # raises the error 'This customer has no attached payment source or default payment method.'\n price = AccountTier.free_tier().product.prices.first()\n customer.subscribe(price=price)\n\n return stripe.billing_portal.Session.create(\n customer=customer.id,\n return_url=request.build_absolute_uri(\n reverse(\"ui-accounts-plan\", kwargs={\"account\": self.name})\n ),\n )",
"def plan_get(request):\n company = auth_api_key(request)\n plan = get_and_check_plan(request, company)\n return plan",
"def do_subscription_approval(sender, **kwargs):\r\n req_payment = sender.get_product_class().get_requires_payment_details()\r\n if not req_payment or has_valid_billing_details(sender.billing_account):\r\n status = 'approved'\r\n else:\r\n status = 'declined'\r\n sender.set_current_approval_status(status)\r\n return status",
"def post(self):\n request_data = request.get_json()\n plan = request_data[\"plan\"]\n success_url = request_data.get(\"success_url\")\n cancel_url = request_data.get(\"cancel_url\")\n\n if not success_url or not cancel_url:\n raise InvalidRequest()\n\n user = get_authenticated_user()\n if not user.stripe_id:\n try:\n cus = billing.Customer.create(\n email=user.email,\n )\n user.stripe_id = cus.id\n user.save()\n except stripe.error.APIConnectionError as e:\n return connection_response(e)\n\n try:\n price = get_price(plan, False)\n if not price:\n abort(404, message=\"Plan not found\")\n\n checkout_session = stripe.checkout.Session.create(\n line_items=[\n {\n \"price\": price[\"stripeId\"],\n \"quantity\": 1,\n },\n ],\n customer=user.stripe_id,\n subscription_data={\n \"metadata\": {\n \"kind\": \"account_change_plan\",\n \"namespace\": user.username,\n \"performer\": user.username,\n \"ip\": get_request_ip(),\n \"plan\": price[\"stripeId\"],\n }\n },\n mode=\"subscription\",\n success_url=success_url,\n cancel_url=cancel_url,\n )\n return checkout_session\n except stripe.error.APIConnectionError as e:\n abort(503, message=\"Cannot contact Stripe\")\n except Exception as e:\n abort(500, message=str(e))",
"def test_func(self):\n member_to_view = self.get_object()\n is_self = self.request.user.rfid == member_to_view.rfid\n view_others = self.request.user.has_permission(\"core.view_member\")\n return view_others or is_self",
"def customer_registration(request):\n \n data = request.data \n phone_number = generate_phn_number()\n \n try: \n try: \n # Create stripe account\n stripe_customer = stripe.Customer.create(\n email = data['email']\n )\n\n # Set a default card for account\n s_card = stripe.Customer.create_source(\n stripe_customer.id,\n source=\"tok_amex\",\n )\n \n plan_id = \"price_1JsHMxSDkRo5FXlkOsq2QHSV\"\n\n # if data[\"subscription_plan\"]== \"Globalnet Silver\":\n # plan_id = \"price_1JsHOJSDkRo5FXlkQmfEQzhN\"\n \n # if data[\"subscription_plan\"]== \"Globalnet Gold\":\n # plan_id = \"price_1JsHPFSDkRo5FXlk9VSl41rV\"\n\n # Create subscription for customer\n subscription = stripe.Subscription.create(\n customer = stripe_customer.id,\n items = [{'plan':plan_id}]\n )\n \n # Create User account\n user = User.objects.create(\n email = data['email'],\n password = make_password(data['password'] ) \n\n )\n\n start_date = datetime.datetime.now().strftime(\"%c\")\n end_date = (datetime.datetime.now() + datetime.timedelta(30)).strftime(\"%x\")\n\n subscription_plan = SubscriptionPlan.objects.get(subscription_plan_name=\"Globalnet Bronze\")\n \n # Create customer data\n customer_data = Customer.objects.create(\n user = user,\n primary_number = phone_number,\n subscription_plan = subscription_plan,\n stripe_id = stripe_customer.id,\n start_date = start_date,\n end_date = end_date,\n subscription_id = subscription.id\n \n )\n \n # Entry Subscription data\n SubscriptionData.objects.create(\n subscriber = phone_number,\n subscription = subscription_plan.subscription_plan_name,\n subscription_start = start_date,\n subscription_end = end_date \n \n ) \n \n serializer= CustomerSerializer(customer_data,many=False)\n return Response(serializer.data)\n\n except Exception as e:\n # delete user if any functionality fails\n u = User.objects.get(username = data['email'])\n u.delete()\n raise Exception(e)\n \n\n except Exception as e:\n message = {\"detail\":str(e)}\n print(e)\n return Response(message)",
"def verifysubscriptionstatusinaccounttab():\n pass",
"def get(self, request, *args, **kwargs):\n\n # Access will be granted in Complete view if payment_id matches.\n payment_id = self.execute_payment()\n # Check if payment id belongs to a Catalog donation -> product_id is set\n donation = Donation.objects.confirm_by_reference(payment_id)\n\n flow_type = 'one_time'\n url = reverse('become_supporter_complete') + \\\n '?payment_id={}'.format(payment_id)\n if donation.product_id:\n flow_type ='product_support'\n url += '&flow_type={}&product_id={}'.format(flow_type, donation.product_id)\n if donation.sponsored_event_dedication:\n flow_type = 'event_sponsorship'\n url += '&flow_type={}&event_id={}'.format(flow_type, donation.sponsored_event_id)\n\n if flow_type == 'event_sponsorship':\n custom_send_receipt(receipt_type=flow_type,\n amount=donation.amount, user=donation.user,\n dedication=donation.sponsored_event_dedication,\n musician=donation.sponsored_event.leader_string(),\n event_date=donation.sponsored_event.get_date())\n else:\n custom_send_receipt(receipt_type='one_time',\n amount=donation.amount, user=donation.user)\n\n return redirect(url)",
"def documents_required(function=None):\n def _dec(view_func):\n def _view(request, *args, **kwargs):\n _user = request.user\n\n if _user.is_authenticated() and _user.is_worker() and\\\n (not _user.is_application_form_filled):\n return redirect('/profissional/subscription/', permanent=True)\n else:\n return view_func(request, *args, **kwargs)\n\n _view.__name__ = view_func.__name__\n _view.__dict__ = view_func.__dict__\n _view.__doc__ = view_func.__doc__\n\n return _view\n\n if function is None:\n print(\"Funciont is none\")\n return _dec\n else:\n print(\"There is some value for function\")\n return _dec(function)",
"def can_view(self, user):\r\n return True",
"def dispatch(request):\n if request.user.is_admin:\n return redirect(reverse(\"admin-dashboard\"))\n else:\n return redirect(reverse(\"trainee-dashboard\"))",
"def _evaluate_has_auths(self, context, user, partner):\n # User fulfills initial authorization\n fulfills_auth = True\n # Checking if user has agreed to terms and conditions, otherwise\n # they shouldn't be authorized to access the collection\n user_agreed_terms = user.userprofile.terms_of_use\n\n if partner.authorization_method in [Partner.EMAIL, Partner.CODES, Partner.LINK]:\n partner_renew = True\n final_auth = fulfills_auth and user_agreed_terms and partner_renew\n else:\n final_auth = fulfills_auth and user_agreed_terms\n # User has authorizations, link to collection page\n context[\"has_auths\"] = final_auth\n\n return context",
"def get_is_subscribed(self, obj):\n user = self.context['request'].user\n if not user.is_authenticated:\n return None\n # pylint: disable=no-member\n profile = UserProfile.objects.get(user=user)\n return profile in obj.subscribed_users.all()",
"def get_active_development_plan_for_user(request):\n current_employee = Employee.objects.get(user__pk=request.user.pk)\n current_development_plan = DevelopmentPlan.objects.filter(\n employee_relation=current_employee,\n employee_relation__developmentplantoemployeerelation__finished_at__isnull=True).first() # is active !!!\n\n if not current_employee:\n raise PermissionDenied()\n\n if current_development_plan:\n data={}\n development_plan_object_list=[]\n dev_plan={}\n dev_plan[\"id\"] = current_development_plan.id\n dev_plan[\"deleted\"] = current_development_plan.deleted\n if current_development_plan.type:\n dev_plan[\"type\"] = current_development_plan.type.name\n dev_plan[\"finished_at\"] = DevelopmentPlanToEmployeeRelation.objects\\\n .get(employee=current_employee, development_plan = current_development_plan)\\\n .finished_at\n\n dev_plan[\"created_at\"] = current_development_plan.created_at\n dev_plan[\"created_by\"] = current_development_plan.created_by.username\n\n development_plan_object_list.append({\"dev_plan_details\":dev_plan})\n\n# manager_relation\n manager_data={}\n manager_data[\"manager_username\"] = current_development_plan.manager_relation.user.username\n manager_data[\"manager_first_name\"] = current_development_plan.manager_relation.user.first_name\n manager_data[\"manager_last_name\"] = current_development_plan.manager_relation.user.last_name\n development_plan_object_list.append({\"manager_data\":manager_data})\n\n# employee_relation\n employee_data={}\n all_employees = current_development_plan.employee_relation.all()\n if all_employees:\n emp_list=[]\n for emp in all_employees:\n emp_data={}\n emp_data[\"id\"] = emp.user.id\n emp_data[\"username\"] = emp.user.username\n emp_data[\"first_name\"] = emp.user.first_name\n emp_data[\"last_name\"] = emp.user.last_name\n emp_data[\"status_questions\"] = emp.status_questions\n\n employee_role = EmployeeRole.objects.filter(employee=emp).all()\n name_role_list = []\n for obj in employee_role:\n name_role_list.append(obj.role.name)\n emp_data[\"roles\"] = name_role_list\n emp_list.append(emp_data)\n employee_data={\"all_employees\":emp_list}\n else:\n return JsonResponse(data={\"details\":\"Any employee has Development Plan with id={}\"\n .format(current_development_plan.id)}, status=404)\n\n development_plan_object_list.append({\"employee_data\":employee_data})\n\n\n# competence_parts\n all_competence_parts = current_development_plan.competence_parts.all()\n\n competence_list = []\n questions_list = []\n sliders_list = []\n\n if all_competence_parts:\n for comp_part in all_competence_parts:\n\n comp_part_data={}\n competence_d={\"competence_parts\": []}\n\n comp_part_data[\"id\"] = comp_part.id\n comp_part_data[\"title\"] = comp_part.title\n comp_part_data[\"description\"] = comp_part.description\n comp_part_data[\"competence_status\"] = comp_part.competence_status\n\n all_questions = comp_part.question_set.all()\n print all_questions\n if all_questions:\n for question in all_questions:\n question_data = {}\n question_data[\"question_id\"] = question.id\n question_data[\"title\"] = question.title\n question_data[\"competence_part\"] = question.competence_part.id\n\n answer = Answer.objects.filter(question__id = question.id,\n employee=current_employee).first()\n\n if answer:\n question_data[\"answer_id\"] = answer.id\n question_data[\"answer\"] = answer.title\n\n questions_list.append(question_data)\n\n comp_part_data[\"questions\"] = questions_list\n\n all_sliders = comp_part.slider_set.all()\n if all_sliders:\n for slider in all_sliders:\n slider_data = {}\n slider_data[\"slider_id\"] = slider.id\n slider_data[\"scale\"] = slider.scale\n slider_data[\"competence_part\"] = slider.competence_part.id\n\n answer = Answer.objects.filter(slider__id = slider.id,\n employee=current_employee).first()\n\n if slider:\n slider_data[\"answer_id\"] = answer.id\n slider_data[\"answer\"] = answer.slider.scale\n\n sliders_list.append(slider_data)\n\n comp_part_data[\"sliders\"] = sliders_list\n\n comp_part_data[\"created_at\"] = comp_part.created_at\n comp_part_data[\"created_by\"] = comp_part.created_by.username\n comp_part_data[\"updated_at\"] = comp_part.updated_at\n comp_part_data[\"updated_by\"] = comp_part.updated_by.username\n\n competence_keys_list = ['id', 'title', 'description',\n 'language_code', 'status']\n\n if not competence_list:\n get_competence_data(competence_keys_list, comp_part.competence, competence_d,\n comp_part_data, competence_list)\n\n else:\n competence_found = False\n for competence_dict in competence_list:\n if competence_dict['id'] == comp_part.competence.id:\n competence_dict['competence_parts'].append(comp_part_data)\n competence_found = True\n break\n\n if not competence_found:\n get_competence_data(competence_keys_list, comp_part.competence, competence_d,\n comp_part_data, competence_list)\n\n development_plan_object_list.append({\"competences\":competence_list})\n\n else:\n return JsonResponse(data={\"details\":\"Development Plan with id={} doesn't have any Competence Part yet\"\n .format(current_development_plan.id)}, status=404)\n\n data = {\"dev_plan:\": development_plan_object_list}\n return JsonResponse(status=201, data=data)\n\n else:\n return JsonResponse(data={\"details\": \"The user with id={} doesn't have an active Development Plan\"\n .format(current_employee.user.id)}, status=404)",
"def json_turn_display_on_handler(request, clean_data):\n if clean_data['coupon_id'] and clean_data['business_id'] \\\n and check_if_i_own_this_business(request, clean_data['business_id']) \\\n and check_if_i_own_this_coupon(request, clean_data['coupon_id']):\n family_availability_dict = check_available_family_slot(\n business_id=clean_data['business_id'])\n if family_availability_dict['available_parent_slot']:\n coupon = Coupon.objects.get(id=clean_data['coupon_id'])\n this_coupon, expiration_date = get_this_coupon_data(request)[1:3]\n coupon.coupon_type_id = 3\n coupon.save()\n this_coupon['coupon_type_id'] = 3\n request.session.modified = True\n today = datetime.date.today()\n if expiration_date < today:\n # This coupon is expired... Bump the expiration_date up\n # 90 days from today.\n expiration_date = default_expiration_date()\n coupon.expiration_date = expiration_date\n coupon.save()\n this_coupon['expiration_date'] = expiration_date\n slot = publish_business_coupon(family_availability_dict, coupon)\n # Send email to staff that someone just published a coupon.\n send_coupon_published_email.delay(coupon=coupon, just_created=False)\n json_data = {'msg': '%s is now displayed.' % clean_data['headline'],\n 'new_display_id': slot.id,\n 'expiration_date':frmt_expiration_date_for_dsp(expiration_date)}\n else:\n # add_slot_choice of 0 will only add a slot to the products list\n # calculations and create list of products to be purchased.\n set_selected_product(request, 2)\n json_data = {'has_full_family':True}\n else:\n json_data = {'msg': 'You are restricted to do anything with this coupon!'}\n return json_data",
"def get_viewable(self, user):\n if user.get('role') in ('admin', 'manager', 'engineer'):\n return True\n return user['name'] == self.doc.get('customer')",
"def subscription_required(self) -> pulumi.Output[Optional[bool]]:\n return pulumi.get(self, \"subscription_required\")",
"def view_account(request, recurring_payment_id, guid=None,\n template_name=\"recurring_payments/index.html\"):\n rp = get_object_or_404(RecurringPayment, pk=recurring_payment_id)\n\n # only admin or user self can access this page\n if not (request.user.is_authenticated() and\n (request.user.profile.is_superuser\n or request.user.id == rp.user.id) or rp.guid == guid):\n raise Http403\n\n paid_payment_transactions = PaymentTransaction.objects.filter(\n recurring_payment=rp,\n status=True\n )\n if paid_payment_transactions:\n last_paid_payment_transaction = paid_payment_transactions[0]\n else:\n last_paid_payment_transaction = None\n\n failed_payment_transactions = PaymentTransaction.objects.filter(\n recurring_payment=rp,\n status=False\n )\n if failed_payment_transactions:\n last_failed_payment_transaction = failed_payment_transactions[0]\n else:\n last_failed_payment_transaction = None\n\n display_failed_transaction = False\n if last_failed_payment_transaction:\n if not last_paid_payment_transaction or \\\n last_failed_payment_transaction.create_dt \\\n > last_paid_payment_transaction.create_dt:\n display_failed_transaction = True\n\n if not rp.trial_amount:\n rp.trial_amount = 0\n\n # rp_invoices\n rp_invoices = RecurringPaymentInvoice.objects.filter(\n recurring_payment=rp\n ).order_by('-billing_cycle_start_dt')\n\n # payment transactions\n payment_transactions = PaymentTransaction.objects.filter(\n recurring_payment=rp\n ).order_by('-create_dt')\n\n # get ready for the add/update payment method button\n test_mode = get_test_mode()\n is_active = (rp.status_detail == 'active')\n if is_active:\n #rp.populate_payment_profile()\n payment_profiles = PaymentProfile.objects.filter(\n customer_profile_id=rp.customer_profile_id,\n status=True, status_detail='active')\n if payment_profiles:\n payment_profile = payment_profiles[0]\n else:\n payment_profile = None\n\n else:\n payment_profile = None\n\n is_owner = request.user.id == rp.user.id\n\n num_accounts = RecurringPayment.objects.filter(user=rp.user).count()\n\n return render_to_response(template_name, {\n 'rp': rp,\n 'display_failed_transaction': display_failed_transaction,\n 'last_paid_payment_transaction': last_paid_payment_transaction,\n 'last_failed_payment_transaction': last_failed_payment_transaction,\n 'rp_invoices': rp_invoices,\n 'payment_transactions': payment_transactions,\n 'payment_profile': payment_profile,\n 'test_mode': test_mode,\n 'is_active': is_active,\n 'is_owner': is_owner,\n 'num_accounts': num_accounts,\n 'memberships': rp.memberships,\n 'STRIPE_PUBLISHABLE_KEY': getattr(settings, 'STRIPE_PUBLISHABLE_KEY', '')\n },\n context_instance=RequestContext(request))",
"def get_namespace_plan(namespace):\n namespace_user = model.user.get_namespace_user(namespace)\n if namespace_user is None:\n return None\n\n if not namespace_user.stripe_id:\n return None\n\n # Ask Stripe for the subscribed plan.\n # TODO: Can we cache this or make it faster somehow?\n try:\n cus = billing.Customer.retrieve(namespace_user.stripe_id)\n except stripe.error.APIConnectionError:\n abort(503, message=\"Cannot contact Stripe\")\n\n if not cus.subscription:\n return None\n\n return get_plan(cus.subscription.plan.id)",
"def has_view_permission(self, request, obj=None):\n user = request.user\n if obj and type(obj) is Client:\n return obj.is_user_in_sales_contacts_of_client(user) or obj.is_user_in_support_contacts_of_client(user)\n return True"
] | [
"0.5515831",
"0.5395123",
"0.539442",
"0.5309995",
"0.5069644",
"0.50552225",
"0.5021062",
"0.50068426",
"0.49595723",
"0.49220333",
"0.48865813",
"0.48719206",
"0.4826401",
"0.47936228",
"0.47907218",
"0.4754648",
"0.4741204",
"0.47088012",
"0.46711046",
"0.4648662",
"0.4637027",
"0.46299124",
"0.46201944",
"0.46173832",
"0.4609308",
"0.45845243",
"0.45812476",
"0.45796302",
"0.45779774",
"0.45234603"
] | 0.7740026 | 0 |
Takes a Nx9 prediction matrix, and a NxK prediction matrices of a subclassifier the subclassifier classifies only the classes in the subclasses list then, it combines the two predictions, and returns the new prediction matrix copyPred means that the prediction matrix will be copied, which costs more memory by default, the Nx9 prediction matrix is overwritten | def combinePredictions(predictions, subpredictions, subclasses = [2,3], copyPred = False):
assert len(subclasses) == np.shape(subpredictions)[1]
assert np.shape(subpredictions)[1] < np.shape(predictions)[1]
assert np.shape(subpredictions)[0] == np.shape(predictions)[0]
if copyPred:
predictions = np.copy(predictions)
subclasses = [x - 1 for x in subclasses] #fix off-by-one error
subsums = np.sum(predictions[:,subclasses], 1)
predictions[:,subclasses] = np.vstack([subpredictions[:,i]*subsums for i in range(len(subclasses))]).T
return predictions | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def _multiclass_confusion_matrix_update(preds: Tensor, target: Tensor, num_classes: int) ->Tensor:\n unique_mapping = target * num_classes + preds\n bins = _bincount(unique_mapping, minlength=num_classes ** 2)\n return bins.reshape(num_classes, num_classes)",
"def process_predictions(self, predictions, prediction_threshold):\n\n processed_predictions = np.zeros_like(predictions, dtype=np.uint8)\n\n weather_cols = [self.label_map[x] for x in self.weather_labels]\n ground_cols = [self.label_map[x] for x in self.ground_labels]\n\n # Awkward but I've spent too long trying to reduce to something neater so fuggedaboutit\n for out, pred in zip(processed_predictions, predictions):\n\n wc = out[weather_cols]\n wc[np.where(pred[weather_cols] == np.max(pred[weather_cols]))] = 1\n out[weather_cols] = wc\n\n gc = out[ground_cols]\n gc[np.where(pred[ground_cols] > prediction_threshold)] = 1\n out[ground_cols] = gc\n\n return processed_predictions",
"def getSubClassifierData(subclasses = [2,3], train_data = None, true_classes = None):\n if (train_data is None) or (true_classes is None):\n train_data, true_classes, _ = get_training_data() \n \n assert len(true_classes) == np.shape(train_data)[0]\n \n validsample = np.array([x in subclasses for x in true_classes])\n return train_data[validsample,:], true_classes[validsample]",
"def combined_predictions(classifiers, test_attributes):\n all_predictions = list()\n for model in classifiers:\n predictions = model.predict(test_attributes)\n all_predictions.append(predictions)\n comb_predictions = all_predictions[0]\n for i in range(len(all_predictions[0])):\n predicted_labels = list()\n for fold in all_predictions:\n predicted_labels.append(fold[i])\n predicted_labels = np.array(predicted_labels)\n labels, freq = np.unique(predicted_labels, return_counts=True)\n comb_predictions[i] = labels[np.argmax(freq)]\n return comb_predictions",
"def mAP(pred_bboxes,\n pred_classes,\n pred_conf,\n gt_bboxes,\n gt_classes,\n IoU_thr,\n pred_im_size,\n gt_im_size):\n # bbox xyxy\n\n pred_classes, gt_classes, pred_bboxes, gt_bboxes, pred_conf =\\\n utils.to_nparray([pred_classes, gt_classes, pred_bboxes, gt_bboxes, pred_conf])\n # rescale bbox to the same scale\n pred_bboxes = bboxtool.rescale_bbox(pred_bboxes, pred_im_size, gt_im_size)\n\n total_classes = set(pred_classes).union(set(gt_classes))\n recall_step = np.linspace(0,1,11)\n len_recall_step = len(recall_step)\n AP_classes = [0 for _ in range(len(total_classes))]\n for c_cnt, c_id in enumerate(total_classes):\n # get bbox for the current class only\n pred_id = np.where(pred_classes == c_id)[0]\n c_pred_bbox = pred_bboxes[pred_id]\n c_pred_conf = pred_conf[pred_id]\n\n gt_id = np.where(gt_classes == c_id)[0]\n c_gt_bbox = gt_bboxes[gt_id]\n n_gt = len(c_gt_bbox)\n\n # AP is 0 if this class does not in either prediction or gt\n if len(pred_id) == 0 or len(gt_id) == 0:\n AP_classes[c_cnt] = 0\n continue\n\n # get corrent detection based on IoUs between prediction and gt\n # IoU_mat [n_gt, n_pred]\n IoU_mat = bboxtool.bbox_list_IOU(c_gt_bbox, c_pred_bbox, align=False)\n det_gt_list = np.argmax(IoU_mat, axis=0)\n iou_list = IoU_mat[det_gt_list, np.arange(len(det_gt_list))]\n iou_list[np.where(iou_list < IoU_thr)] = 0\n \n # make table of IoU, prediction confidence and detected gt_id for\n # sorting the results based on prediction confidence\n det_table = np.stack((iou_list, c_pred_conf, det_gt_list), axis=-1)\n det_table = det_table[det_table[:, 1].argsort()[::-1]]\n\n # compute recall and precision for each confidence threshold\n recall_list = [0 for _ in range(len(iou_list))]\n precision_list = [0 for _ in range(len(iou_list))]\n prev_precision = 0.\n TP_id = (det_table[:,0] > 0)\n peak_list = []\n for i in range(len(iou_list)):\n recall_list[i] = len(set(det_gt_list[:i+1][TP_id[:i+1]])) / n_gt\n precision_list[i] = sum(det_table[:i+1,0] > 0) / (i + 1)\n if precision_list[i] < prev_precision:\n peak_list.append((prev_precision, recall_list[i - 1]))\n prev_precision = precision_list[i]\n peak_list.append((prev_precision, recall_list[-1]))\n\n # get max precision for each recall level\n max_precision = [0 for _ in range(len_recall_step)]\n peak_p = 0\n max_ = 0\n for idx, recall_ in enumerate(recall_step):\n while peak_p < len(peak_list) and peak_list[peak_p][1] <= recall_:\n max_ = max(max_, peak_list[peak_p][0])\n peak_p += 1\n max_precision[idx] = max_\n if peak_p < len(peak_list):\n max_ = peak_list[peak_p][0]\n max_precision[0] = max(max_precision)\n AP_classes[c_cnt] = np.mean(max_precision)\n\n return np.mean(AP_classes)",
"def _classifier(self, classes):\n # Initialize key variables\n pseudo = np.linalg.pinv(self.data)\n result = np.dot(pseudo, classes)\n return result",
"def test_classify(self):\n classifiers, estimates =\\\n ada_boost.train_dataset(self.larger_matrix,\n self.larger_class_labels,\n 9)\n data_to_classify = [1, 0.5]\n classifications = ada_boost.classify(data_to_classify, classifiers)\n expected = np.mat([-1.])\n self.assertEqual(classifications, expected)",
"def multiclass_toy_data(): \n #dataset = np.zeros((10,5), np.int)\n dataset = np.array([[0,0,0,0,4],\n [0,0,0,0,5],\n [1,3,0,0,0],\n [3,1,0,0,1],\n [0,0,6,2,0],\n [0,0,0,0,0],\n [0,0,1,7,2], \n [0,0,5,1,5],\n [0,0,34,0,0],\n [0,0,3,0,0]])\n Y = np.array([3,3,2,2,1,0,1,1,0,0])\n #for i in range(10):\n #for j in range(5):\n #dataset[i][j] = np.random.randint(0,10) \n dataset = np.column_stack((dataset, Y))\n return (dataset)",
"def _construct_prediction_heads(self, num_classes, num_feature_outputs,\n class_prediction_bias_init,\n unit_height_conv=False):\n prediction_heads = {}\n prediction_heads[OBJECT_CENTER] = self._make_prediction_net_list(\n num_feature_outputs,\n num_classes,\n kernel_sizes=self._center_params.center_head_kernel_sizes,\n num_filters=self._center_params.center_head_num_filters,\n bias_fill=class_prediction_bias_init,\n name='center',\n unit_height_conv=unit_height_conv)\n\n if self._od_params is not None:\n prediction_heads[BOX_SCALE] = self._make_prediction_net_list(\n num_feature_outputs,\n NUM_SIZE_CHANNELS,\n kernel_sizes=self._od_params.scale_head_kernel_sizes,\n num_filters=self._od_params.scale_head_num_filters,\n name='box_scale',\n unit_height_conv=unit_height_conv)\n prediction_heads[BOX_OFFSET] = self._make_prediction_net_list(\n num_feature_outputs,\n NUM_OFFSET_CHANNELS,\n kernel_sizes=self._od_params.offset_head_kernel_sizes,\n num_filters=self._od_params.offset_head_num_filters,\n name='box_offset',\n unit_height_conv=unit_height_conv)\n\n if self._kp_params_dict is not None:\n for task_name, kp_params in self._kp_params_dict.items():\n num_keypoints = len(kp_params.keypoint_indices)\n prediction_heads[get_keypoint_name(\n task_name, KEYPOINT_HEATMAP)] = self._make_prediction_net_list(\n num_feature_outputs,\n num_keypoints,\n kernel_sizes=kp_params.heatmap_head_kernel_sizes,\n num_filters=kp_params.heatmap_head_num_filters,\n bias_fill=kp_params.heatmap_bias_init,\n name='kpt_heatmap',\n unit_height_conv=unit_height_conv)\n prediction_heads[get_keypoint_name(\n task_name, KEYPOINT_REGRESSION)] = self._make_prediction_net_list(\n num_feature_outputs,\n NUM_OFFSET_CHANNELS * num_keypoints,\n kernel_sizes=kp_params.regress_head_kernel_sizes,\n num_filters=kp_params.regress_head_num_filters,\n name='kpt_regress',\n unit_height_conv=unit_height_conv)\n\n if kp_params.per_keypoint_offset:\n prediction_heads[get_keypoint_name(\n task_name, KEYPOINT_OFFSET)] = self._make_prediction_net_list(\n num_feature_outputs,\n NUM_OFFSET_CHANNELS * num_keypoints,\n kernel_sizes=kp_params.offset_head_kernel_sizes,\n num_filters=kp_params.offset_head_num_filters,\n name='kpt_offset',\n unit_height_conv=unit_height_conv)\n else:\n prediction_heads[get_keypoint_name(\n task_name, KEYPOINT_OFFSET)] = self._make_prediction_net_list(\n num_feature_outputs,\n NUM_OFFSET_CHANNELS,\n kernel_sizes=kp_params.offset_head_kernel_sizes,\n num_filters=kp_params.offset_head_num_filters,\n name='kpt_offset',\n unit_height_conv=unit_height_conv)\n\n if kp_params.predict_depth:\n num_depth_channel = (\n num_keypoints if kp_params.per_keypoint_depth else 1)\n prediction_heads[get_keypoint_name(\n task_name, KEYPOINT_DEPTH)] = self._make_prediction_net_list(\n num_feature_outputs, num_depth_channel, name='kpt_depth',\n unit_height_conv=unit_height_conv)\n\n if self._mask_params is not None:\n prediction_heads[SEGMENTATION_HEATMAP] = self._make_prediction_net_list(\n num_feature_outputs,\n num_classes,\n kernel_sizes=self._mask_params.mask_head_kernel_sizes,\n num_filters=self._mask_params.mask_head_num_filters,\n bias_fill=self._mask_params.heatmap_bias_init,\n name='seg_heatmap',\n unit_height_conv=unit_height_conv)\n\n if self._densepose_params is not None:\n prediction_heads[DENSEPOSE_HEATMAP] = self._make_prediction_net_list(\n num_feature_outputs,\n self._densepose_params.num_parts,\n bias_fill=self._densepose_params.heatmap_bias_init,\n name='dense_pose_heatmap',\n unit_height_conv=unit_height_conv)\n prediction_heads[DENSEPOSE_REGRESSION] = self._make_prediction_net_list(\n num_feature_outputs,\n 2 * self._densepose_params.num_parts,\n name='dense_pose_regress',\n unit_height_conv=unit_height_conv)\n\n if self._track_params is not None:\n prediction_heads[TRACK_REID] = self._make_prediction_net_list(\n num_feature_outputs,\n self._track_params.reid_embed_size,\n name='track_reid',\n unit_height_conv=unit_height_conv)\n\n # Creates a classification network to train object embeddings by learning\n # a projection from embedding space to object track ID space.\n self.track_reid_classification_net = tf.keras.Sequential()\n for _ in range(self._track_params.num_fc_layers - 1):\n self.track_reid_classification_net.add(\n tf.keras.layers.Dense(self._track_params.reid_embed_size))\n self.track_reid_classification_net.add(\n tf.keras.layers.BatchNormalization())\n self.track_reid_classification_net.add(tf.keras.layers.ReLU())\n self.track_reid_classification_net.add(\n tf.keras.layers.Dense(self._track_params.num_track_ids))\n if self._temporal_offset_params is not None:\n prediction_heads[TEMPORAL_OFFSET] = self._make_prediction_net_list(\n num_feature_outputs, NUM_OFFSET_CHANNELS, name='temporal_offset',\n unit_height_conv=unit_height_conv)\n return prediction_heads",
"def overall_classification_matrix(self, interpreter):\n return sum([ r.classification_matrix(interpreter) for r in self.results ])",
"def confusionMatrix(actual, predict, truePositiveClass=''):\n classes = list(set(actual + predict))\n if len(truePositiveClass) > 0:\n id0 = classes.index(truePositiveClass)\n classes[id0] = classes[0]\n classes[0] = truePositiveClass\n cMatrix = np.zeros( (len(classes), len(classes)) )\n\n for i in range(0,len(predict)):\n ida = classes.index(actual[i])\n idp = classes.index(predict[i])\n cMatrix[ida][idp] += 1\n return cMatrix",
"def classification(original_training_data):\n\n ''' Storing the dataframe as numpy array '''\n original_training_data_values = original_training_data.values\n\n ''' Storing the values of target attribute for finding out the counts of each recipetype'''\n target_column = original_training_data_values[:, -1]\n\n ''' Recipe_type stores the unique values of target attribute in the form of a list [Muffin Cupcake] \n cupcake_muffin_count stores the count of muffin and cupcakes in the form of a list [451 451]'''\n recipe_type, cupcake_muffin_count = np.unique(target_column, return_counts=True)\n\n ''' cupcake_muffin_count.argmax() returns the index of the highest value. In this case, it will return the index of \n muffin or cupcake count. '''\n majority_class = recipe_type[cupcake_muffin_count.argmax()]\n\n return majority_class",
"def perform_image_classification_by_model(model, input_image, is_image_array = False, top_n_classes=5, show_info=True):\n global CLASS_INDEX\n results = pd.DataFrame.empty\n if show_info is True:\n print(\"Starting process to generate classes probabilities now..\")\n if is_image_array == True:\n preds = model.predict(input_image)\n else:\n input_image_array = imageassist.ImageUtils.convert_image_array(input_image)\n input_image_array = imageassist.ImageUtils.preprocess_image_array(input_image_array)\n preds = model.predict(input_image_array)\n\n if len(preds.shape) != 2:\n print(\"Error: The predictions values are not in the shape of tupple as (1,1000).\")\n return results\n\n if CLASS_INDEX is None:\n fpath = get_file('imagenet_class_index.json',\n IMAGENET_CLASS_JSON,\n cache_subdir='models')\n CLASS_INDEX = json.load(open(fpath))\n\n class_count = len(CLASS_INDEX)\n if class_count == 0:\n print(\"Error: There was some problem reading imagenet classes...\")\n return results\n\n if top_n_classes > class_count:\n top_n_classes=class_count\n\n cols = [\"ClassName\", \"ClassId\", \"Probability\"]\n results = pd.DataFrame(columns=cols, index=range(top_n_classes))\n\n if show_info is True:\n print(\"Classification completed, now generating prediction dataframe ..\")\n for pred in preds:\n # Getting top results in the prediction through index\n top_indices = pred.argsort()[-top_n_classes:][::-1]\n result = [tuple(CLASS_INDEX[str(i)]) + (pred[i],) for i in top_indices]\n result.sort(key=lambda x: x[2], reverse=True)\n for k in range(len(result)):\n results.loc[k].ClassName = result[k][1]\n results.loc[k].ClassId = result[k][0]\n results.loc[k].Probability = result[k][2]\n return results",
"def _predict(self, probabilities):\n child_categories = []\n for i in range(0, self.category_level):\n child_categories.append({})\n for category_label in self.classifiers[i].classes_:\n main_category = self._get_categories(category_label)[0]\n if main_category not in child_categories[i]:\n child_categories[i][main_category] = []\n child_categories[i][main_category].append(category_label)\n\n # find the primary category\n max_score = -1\n primary_category_label = None\n\n for i in range(0, self.category_level):\n for category_label in self.classifiers[i].classes_:\n if probabilities[category_label] < 1e-9:\n continue\n total_score = 0\n main_category = self._get_categories(category_label)[0]\n candidates = child_categories[i][main_category]\n for actual_label in candidates:\n probability = probabilities[actual_label]\n if probability < 1e-9:\n continue\n score = self._cal_score(category_label, None, actual_label, i)\n total_score += score * probability\n if total_score > max_score:\n max_score = total_score\n primary_category_label = category_label\n\n # find the secondary category\n max_score = -1\n secondary_category_label = None\n for i in range(0, self.category_level):\n for category_label in self.classifiers[i].classes_:\n if probabilities[category_label] < 1e-9 and secondary_category_label:\n continue\n if category_label == primary_category_label:\n continue\n total_score = 0\n main_category = self._get_categories(category_label)[0]\n main_category2 = self._get_categories(primary_category_label)[0]\n candidates = list(set(child_categories[i][main_category] + child_categories[i][main_category2]))\n for actual_label in candidates:\n probability = probabilities[actual_label]\n if probability < 1e-9:\n continue\n score = self._cal_score(primary_category_label, category_label, actual_label, i)\n total_score += score * probability\n if total_score > max_score:\n max_score = total_score\n secondary_category_label = category_label\n\n return [self._get_categories(primary_category_label), self._get_categories(secondary_category_label)]",
"def multiclass_metrics(pred, gt):\r\n eps=1e-6\r\n overall = {'precision': -1, 'recall': -1, 'f1': -1}\r\n NP, NR, NC = 0, 0, 0 # num of pred, num of recall, num of correct\r\n for ii in range(pred.shape[0]):\r\n pred_ind = np.array(pred[ii]>0.5, dtype=int)\r\n gt_ind = np.array(gt[ii]>0.5, dtype=int)\r\n inter = pred_ind * gt_ind\r\n # add to overall\r\n NC += np.sum(inter)\r\n NP += np.sum(pred_ind)\r\n NR += np.sum(gt_ind)\r\n if NP > 0:\r\n overall['precision'] = float(NC)/NP\r\n if NR > 0:\r\n overall['recall'] = float(NC)/NR\r\n if NP > 0 and NR > 0:\r\n overall['f1'] = 2*overall['precision']*overall['recall']/(overall['precision']+overall['recall']+eps)\r\n return overall",
"def postprocess(self, prediction_dict):\r\n #三个通道的网络需要全连接层融合\r\n\r\n eyeFace_logits = prediction_dict['eyeFace_logits']\r\n eyeFace_logits = tf.nn.softmax(eyeFace_logits)\r\n logits = eyeFace_logits\r\n classes = tf.argmax(logits, 1)\r\n postprecessed_dict = {'classes': classes}\r\n return postprecessed_dict",
"def _classify_from_probs(predicts_proba):\n def find_majority(dict_probs):\n \"\"\"Find the majority class\"\"\"\n # if there is no majority class, pick the first from the sorted\n max_val = max(dict_probs.values())\n max_keys = [key for key in dict_probs.keys()\n if dict_probs[key] == max_val]\n return sorted(max_keys)[0]\n\n predicts = [find_majority(dict_probs) for dict_probs in predicts_proba]\n return predicts",
"def _np_merge_prediction(prediction):\n prob_map = prediction[0][0]\n prob_map_flipped = np.flip(prediction[1][0], (1)) # (H, W)\n _prob = 0.5 * (prob_map + prob_map_flipped)\n return _prob",
"def base_classifier(traitar_model, phenotype_feature_table, features, phenotype, out, do_normalization, get_misclassified_selected):\n model = pd.read_csv(traitar_model, sep = \"\\t\", index_col = 0)\n sel_feats = model.index\n table = pd.read_csv(phenotype_feature_table, sep = \"\\t\", index_col = 0)\n feats = pd.read_csv(features, sep = \"\\t\", index_col = 0).index\n #target\n pt_notnull = pd.notnull(table.loc[:, phenotype])\n y_p = table.loc[:, phenotype].loc[pt_notnull,]\n y_p[y_p == 0] = -1\n #features\n x_p = table.loc[:, feats].loc[pt_notnull,]\n if do_normalization:\n scaler = preprocessing.StandardScaler(with_mean = True, with_std = True).fit(x_p)\n x_p = pd.DataFrame(data = scaler.transform(x_p), index = x_p.index, columns = x_p.columns)\n #train decision stump\n preds = [tree.DecisionTreeClassifier(max_depth = 1, class_weight = 'balanced').fit(pd.DataFrame(x_p.loc[:, i]), y_p).predict(pd.DataFrame(x_p.loc[:, i])) for i in sel_feats] \n conf_per_feat = pd.DataFrame([nested_cv.nested_cv.confusion_m(y_p, pd.Series(p, index = y_p.index).T) for p in preds ])\n conf_per_feat.index = sel_feats\n conf_per_feat.columns = [\"TN\", \"FP\", \"FN\", \"TP\"]\n #get macro accuracy\n bacc = conf_per_feat.apply(lambda x: nested_cv.nested_cv.bacc(nested_cv.nested_cv.recall_pos_conf(x), nested_cv.nested_cv.recall_neg_conf(x)), axis = 1)\n perf_per_feat = pd.concat([conf_per_feat, bacc], 1)\n perf_per_feat.columns = [\"TN\", \"FP\", \"FN\", \"TP\", \"MACC\"]\n feat_df = pd.concat([model.drop([\"TN\", \"FP\", \"FN\", \"TP\", \"MACC\"], axis = 1, inplace = False), perf_per_feat], axis = 1)\n #feat_df = pd.concat([model.drop(\"cor\", axis = 1, inplace = False), perf_per_feat], axis = 1)\n feat_df.sort(columns = [\"MACC\"], ascending = False).to_csv(out, float_format='%.3f', sep = \"\\t\")\n #get misclassified for a selected marker\n if get_misclassified_selected:\n preds_indexed = pd.DataFrame(preds, index = sel_feats).T\n preds_target = preds_indexed.loc[:, get_misclassified_selected]\n preds_target.index = x_p.index\n gs_target = y_p \n #false positives\n fp = gs_target.loc[(gs_target == -1) & (preds_target == 1)]\n #false negatives\n fn = gs_target.loc[(gs_target == 1) & (preds_target == -1)]\n fn.to_csv(\"%s_false_neg.dat\" % get_misclassified_selected, header = False, sep = \"\\t\")\n fp.to_csv(\"%s_false_pos.dat\" % get_misclassified_selected, header = False, sep = \"\\t\")",
"def results_corr_clsfied_imgs(org_pred_probs_full_data, org_pred_probs_clscorr, perturbed_pred_probs,\n class_index_json_path, y, y_, img_names, root_folder_to_save_images, threshold,\n method_type, experiments_file_path):\n\n original_image_predicted_classes_full_data = []\n\n original_image_predicted_classes = []\n\n perturbed_image_predicted_classes = []\n\n with open(class_index_json_path) as index_class_mapping_file:\n mapping_dictionary = json.load(index_class_mapping_file)\n\n for org_preds, perturbed_preds in zip(org_pred_probs_clscorr, perturbed_pred_probs):\n org_top_predicted_label_index = org_preds.argsort()[-1]\n\n perturbed_top_predicted_label_index = perturbed_preds.argsort()[-1]\n original_image_predicted_classes.append(mapping_dictionary[str(org_top_predicted_label_index)])\n perturbed_image_predicted_classes.append(mapping_dictionary[str(perturbed_top_predicted_label_index)])\n\n for org_preds_full_data in org_pred_probs_full_data:\n top_predicted_label_index = org_preds_full_data.argsort()[-1]\n original_image_predicted_classes_full_data.append(mapping_dictionary[str(top_predicted_label_index)])\n\n with open(os.path.join(root_folder_to_save_images, \"output.csv\"), 'w', newline='') as output_file:\n output_writer = csv.writer(output_file, delimiter=',')\n output_writer.writerow(\n ['IMAGE Name', 'Original Class Name', 'Predictions On Original Images', 'Predictions On Perturbed Images'])\n for i in zip(img_names, y_, original_image_predicted_classes, perturbed_image_predicted_classes):\n output_writer.writerow(i)\n print(\"output.csv has been generated..\")\n\n # Classwise metrics\n\n num_samples_per_class = defaultdict(int)\n for a_label in y:\n num_samples_per_class[a_label] += 1 # Example : { 'classA': 100 , 'classB': 99,...., 'classN': 89 }\n\n num_adv_samples_per_class = defaultdict(int)\n for label in y_:\n num_adv_samples_per_class[label] += 1\n\n # num of adversarial examples found for each class\n # num_of_adv_examples_found = list(num_adv_samples_per_class.values())\n\n unique_labels = list(num_adv_samples_per_class.keys())\n\n # Y_ ==> only labels for classes where correctly classified.Y==>Overall Data.\n # We need report only for correctly classified. Hence 'labels' argument has been assigned with classes where\n # samples have been correctly classified by the model.\n metrics_org_examples = precision_recall_fscore_support(\n y, original_image_predicted_classes_full_data, labels=unique_labels)\n # recall_org_examples = metrics_org_examples[1]\n support_org_examples = metrics_org_examples[3]\n\n # To get true positives on perturbed examples\n conf_matrix_perturbed_imgs = confusion_matrix(y_, perturbed_image_predicted_classes, labels=unique_labels)\n conf_matrix_overall_imgs = confusion_matrix(y, original_image_predicted_classes_full_data, labels=unique_labels)\n\n # Get diagonal elements from the matrix to get true positives\n perturbed_ex_correctly_classified_per_class = []\n for i in range(conf_matrix_perturbed_imgs.shape[0]):\n perturbed_ex_correctly_classified_per_class.append(conf_matrix_perturbed_imgs[i][i])\n\n test_data_correctly_classified_per_class = []\n for j in range(conf_matrix_overall_imgs.shape[0]):\n test_data_correctly_classified_per_class.append(conf_matrix_overall_imgs[j][j])\n\n # perturbed examples correctly classified divided by original number of examples in each class\n percent_of_adv_exmpls_classified_correctly = [j / i for i, j in zip(support_org_examples,\n perturbed_ex_correctly_classified_per_class)]\n # test data examples correctly classified divided by original number of samples in each class\n percent_of_test_data_classified_correctly = [n / m for m, n in zip(support_org_examples,\n test_data_correctly_classified_per_class)]\n\n diff_bool = []\n for m, n in zip(percent_of_test_data_classified_correctly, percent_of_adv_exmpls_classified_correctly):\n if n == 0:\n diff_bool.append('TRUE')\n else:\n diff_bool.append((m - n) > threshold)\n with open(os.path.join(root_folder_to_save_images, 'classmetrics.csv'), 'w', newline='') as classmetrics_file:\n classmetrics_writer = csv.writer(classmetrics_file, delimiter=',')\n classmetrics_writer.writerow(\n ['ClassNames', 'Number Of Examples In Each Class(Overall Test Data)',\n 'Number Of Test Data Correctly Classified(Overall)', 'Perturbed Examples Correctly Classified',\n 'Accuracy-TestData', 'Accuracy-PerturbedExamples', 'Diff-Accuracy'])\n for row in zip(unique_labels, support_org_examples, test_data_correctly_classified_per_class,\n perturbed_ex_correctly_classified_per_class, percent_of_test_data_classified_correctly,\n percent_of_adv_exmpls_classified_correctly, diff_bool):\n classmetrics_writer.writerow(row)\n\n print(\"classwisemetrics.csv has been generated..\")\n\n # Overall Metrics\n # calculate overall true positives\n conf_matrix_full_testdata = confusion_matrix(y, original_image_predicted_classes_full_data, labels=list(set(y)))\n true_positives_overall_testdata = 0\n for d in range(conf_matrix_full_testdata.shape[0]):\n true_positives_overall_testdata += conf_matrix_full_testdata[d][d]\n\n accuracy_overall_testdata = true_positives_overall_testdata / len(y)\n accuracy_perturbed_examples = sum(perturbed_ex_correctly_classified_per_class) / len(y)\n with open(os.path.join(root_folder_to_save_images, 'overallmetrics.csv'), 'w', newline='') as overall_metrics_file:\n overall_metrics_writer = csv.writer(overall_metrics_file, delimiter=',')\n overall_metrics_writer.writerow(['Metrics', 'OnOriginalExamples', 'OnPerturbedExamples', 'Diff-Accuracy'])\n overall_metrics_writer.writerow(['Accuracy', accuracy_overall_testdata, accuracy_perturbed_examples,\n accuracy_overall_testdata - accuracy_perturbed_examples > threshold])\n\n print(\"overallmetrics.csv has been generated..\")\n\n # Generate experiments.csv file.\n generate_experiments(experiments_file_path, method_type)\n\n # Check if the result files have been generated and the return a message\n\n return result_message(root_folder_to_save_images)",
"def fold_prediction_result(x_train, y_train, x_test, y_test, classification_types, basic_classifier):\n metrics_dict = {}\n for metric in METRICS:\n metrics_dict[metric] = {}\n training_time = {}\n test_time = {}\n for classification in classification_types:\n # logger.info(\"*****************************\")\n logger.info(classification)\n if classification in ENCODING_TYPES:\n classifier = EncodedClassifier(basic_classifier, encoding_type=classification)\n elif classification == \"meta_binary_tree_classifier\":\n classifier = MetaBinaryTreeClassifier(basic_classifier)\n elif classification == \"standard-classifier\":\n classifier = basic_classifier\n else:\n raise Exception(\"The Classification Method is not a valid one\")\n start_time = time.time()\n if isinstance(classifier, h2o.estimators.H2OEstimator):\n classifier = fit_h2o(x_train, y_train, classifier)\n else:\n classifier.fit(x_train, y_train)\n train_time = time.time() - start_time\n if isinstance(classifier, h2o.estimators.H2OEstimator):\n column_types = get_h2o_column_types(x_test.columns)\n x_test = H2OFrame(x_test, column_types=column_types)\n prediction = classifier.predict(x_test)\n y_pred = np.concatenate(prediction['predict'].as_data_frame().values)\n else:\n y_pred = classifier.predict(x_test)\n prediction_time = time.time() - train_time - start_time\n # Calculate metrics\n for metric, f in METRICS.items():\n metrics_dict[metric][classification] = f(y_test, y_pred)\n training_time[classification] = train_time\n test_time[classification] = prediction_time\n\n return metrics_dict, training_time, test_time",
"def ReclassifyRasterArray(inputarray, reclassdf):\n arrshape = inputarray.shape\n arrdf = pd.DataFrame(inputarray.reshape(-1), columns=['class'])\n reclassdf['class'] = reclassdf['class'].astype(int)\n arrsuitjoin = arrdf.join(reclassdf.set_index('class'), on='class', how='left')\n return np.array(arrsuitjoin['suit_score']).reshape(arrshape)",
"def as_multiclass_shape(preds, as_probs=False):\n assert preds.ndim <= 2\n\n if preds.ndim == 1:\n preds = preds.unsqueeze(1)\n if preds.shape[1] == 1:\n preds = torch.cat([-preds, preds], dim=1)\n if as_probs:\n preds = torch.sigmoid(preds)\n return preds\n else:\n if as_probs:\n preds = F.softmax(preds, dim=1)\n return preds",
"def eval_metrics_for_multiclass(self, predicted_answers):\n total_correct_in_all = 0\n total_pred_in_all = len(predicted_answers)\n # initial a dict for total correct in topK counting.\n total_correct_in_topK = dict([(i, 0) for i in self.topK_list])\n total_pred_in_topK = dict([(i, 0) for i in self.topK_list])\n max_topK = max(self.topK_list)\n label_pred = []\n label_true = []\n label_weights = []\n digits = 3\n metrics = {}\n\n for e_id, sample in predicted_answers.iteritems():\n # get all correct ids\n correct_label_indices = sample['correct_labels']\n # current case, we only have a majority lable for the correct label\n label_true.append(correct_label_indices[0])\n # counting all correct for each sample\n total_correct_in_all += len(correct_label_indices)\n # select topK\n sorted_probs_max_topK = sorted(sample['pred_probs'], reverse=True, key=lambda x: x['prob'])[:max_topK]\n top1_pred = sorted_probs_max_topK[0]\n label_pred.append(top1_pred['label_index'])\n\n # for all topK predictions\n for i in range(len(sorted_probs_max_topK)):\n pred = sorted_probs_max_topK[i]\n for topK in self.topK_list:\n if i >= topK:\n continue\n else:\n total_pred_in_topK[topK] += 1\n if pred['label_index'] in correct_label_indices:\n total_correct_in_topK[topK] += 1\n\n if total_correct_in_all != 0:\n # recall@K\n recall_at_K = dict([(k, total_correct_in_topK[k] / (total_correct_in_all * 1.0)) for k in self.topK_list])\n # assign recall@K into metrics\n for k, v in recall_at_K.items():\n # Jie\n # 1 means the greater the better.\n # -1 means the smaller the better.\n metrics['R@{}'.format(k)] = (1, v)\n\n self.logger.info('total_correct_in_all = {}, correct_in_topK = {}, recall@K = {}'.format(total_correct_in_all, sorted(total_correct_in_topK.items()), sorted(recall_at_K.items())))\n # here return all the p,r,f for each label, then we compute the micro average later.\n p, r, f1, s = precision_recall_fscore_support(label_true, label_pred, beta=1.0, labels=range(self.num_classes), average=None)\n total_s = np.sum(s)\n p_micro, r_micro, f1_micro, _ = precision_recall_fscore_support(label_true, label_pred, beta=1.0, labels=range(self.num_classes), average='micro')\n last_lines_heading = ['macro / total', 'weighted_mac / total', 'micro / total']\n target_names = self.classes\n name_width = max(len(cn) for cn in target_names)\n width = max(name_width, max([len(x) for x in last_lines_heading]), digits)\n\n headers = [\"precision\", \"recall\", \"f1-score\", \"support\"]\n head_fmt = u'{:>{width}s} ' + u' {:>9}' * len(headers)\n report = head_fmt.format(u'', *headers, width=width)\n report += u'\\n\\n'\n row_fmt = u'{:>{width}s} ' + u' {:>9.{digits}f}' * 3 + u' {:>9}\\n'\n rows = zip(target_names, p, r, f1, s)\n for row in rows:\n label_weights.append(row[4])\n report += row_fmt.format(*row, width=width, digits=digits)\n metrics['P_{}'.format(row[0])] = (1, row[1])\n metrics['R_{}'.format(row[0])] = (1, row[2])\n metrics['F1_{}'.format(row[0])] = (1, row[3])\n report += u'\\n'\n\n # compute macro averages\n p_macro = np.average(p, weights = None)\n r_macro = np.average(r, weights = None)\n f1_macro = np.average(f1, weights = None)\n metrics['P_{}'.format(\"macro\")] = (1, p_macro)\n metrics['R_{}'.format(\"macro\")] = (1, r_macro)\n metrics['F1_{}'.format(\"macro\")] = (1, f1_macro)\n report += row_fmt.format(last_lines_heading[0],\n p_macro,\n r_macro,\n f1_macro,\n total_s,\n width=width, digits=digits)\n\n # compute weighted macro average\n label_weights = map(lambda x : x/(total_s * 1.0), label_weights)\n p_weighted_average = np.average(p, weights = label_weights)\n r_weighted_average = np.average(r, weights = label_weights)\n f1_weighted_average = np.average(f1, weights = label_weights)\n metrics['P_{}'.format(\"weighted_macro\")] = (1, p_weighted_average)\n metrics['R_{}'.format(\"weighted_macro\")] = (1, r_weighted_average)\n metrics['F1_{}'.format(\"weighted_macro\")] = (1, f1_weighted_average)\n report += row_fmt.format(last_lines_heading[1],\n p_weighted_average,\n r_weighted_average,\n f1_weighted_average,\n total_s,\n width=width, digits=digits)\n # micro average\n metrics['P_{}'.format(\"micro\")] = (1, p_micro)\n metrics['R_{}'.format(\"micro\")] = (1, r_micro)\n metrics['F1_{}'.format(\"micro\")] = (1, f1_micro)\n report += row_fmt.format(last_lines_heading[2],\n p_micro,\n r_micro,\n f1_micro,\n total_s,\n width=width, digits=digits)\n\n self.logger.info(\"P,R,F1 report as follows:\\n {}\".format(report))\n # only plot it at dev and test time, not during training.\n if self.gen_confusing_matrix:\n\n self.logger.info(\"Generate confusing matrix photo.\")\n # Compute confusion matrix\n conf_matrix = confusion_matrix(label_true, label_pred)\n np.set_printoptions(precision=2)\n\n # Plot non-normalized confusion matrix\n plt.figure()\n self.plot_confusion_matrix(conf_matrix, classes=self.brief_classes, ori_fmt='d',\n title='Confusion matrix, without normalization')\n wo_norm_fig_path = os.path.join(self.result_dir, '{}_wo_norm.png'.format(self.result_prefix))\n plt.savefig(wo_norm_fig_path)\n\n # Plot normalized confusion matrix\n plt.figure()\n self.plot_confusion_matrix(conf_matrix, classes=self.brief_classes, ori_fmt='d', normalize=True,\n title='Normalized confusion matrix')\n\n norm_fig_path = os.path.join(self.result_dir, '{}_w_norm.png'.format(self.result_prefix))\n plt.savefig(norm_fig_path)\n\n else:\n self.logger.warn('invalid total_correct_in_all')\n\n return metrics",
"def map_objects_classifier_evaluation(self):\n df = self.results[(self.results['iou'] > 0.7)]\n y_true = df['true_class']\n y_pred = df['pred_class']\n print(classification_report(y_true, y_pred))\n matrix = confusion_matrix(y_true, y_pred)\n matrix = matrix.astype('float') / matrix.sum(axis=1)[:, np.newaxis]\n import seaborn as sns\n\n plt.figure(figsize=(10, 7))\n sns.set(font_scale=2.4)\n sns.heatmap(matrix, annot=True, annot_kws={'size': 25},\n cmap=plt.cm.Reds)\n # Add labels to the plot\n class_names = ['background', 'building', 'water']\n tick_marks = np.arange(len(class_names))\n tick_marks2 = tick_marks + 0.28\n tick_marks2[0] = tick_marks2[0] - 0.2\n tick_marks = tick_marks + 0.5\n plt.xticks(tick_marks, class_names, rotation=0)\n plt.yticks(tick_marks2, class_names, rotation=90)\n plt.xlabel('Predicted label', labelpad=13)\n plt.ylabel('True label', labelpad=13)\n plt.show()",
"def _postprocess_keypoints_multi_class(self, prediction_dict, classes,\n y_indices, x_indices, boxes,\n num_detections):\n total_num_keypoints = sum(len(kp_dict.keypoint_indices) for kp_dict\n in self._kp_params_dict.values())\n batch_size, max_detections = _get_shape(classes, 2)\n kpt_coords_for_example_list = []\n kpt_scores_for_example_list = []\n for ex_ind in range(batch_size):\n # The tensors that host the keypoint coordinates and scores for all\n # instances and all keypoints. They will be updated by scatter_nd_add for\n # each keypoint tasks.\n kpt_coords_for_example_all_det = tf.zeros(\n [max_detections, total_num_keypoints, 2])\n kpt_scores_for_example_all_det = tf.zeros(\n [max_detections, total_num_keypoints])\n for task_name, kp_params in self._kp_params_dict.items():\n keypoint_heatmap = prediction_dict[\n get_keypoint_name(task_name, KEYPOINT_HEATMAP)][-1]\n keypoint_offsets = prediction_dict[\n get_keypoint_name(task_name, KEYPOINT_OFFSET)][-1]\n keypoint_regression = prediction_dict[\n get_keypoint_name(task_name, KEYPOINT_REGRESSION)][-1]\n instance_inds = self._get_instance_indices(\n classes, num_detections, ex_ind, kp_params.class_id)\n\n # Gather the feature map locations corresponding to the object class.\n y_indices_for_kpt_class = tf.gather(y_indices, instance_inds, axis=1)\n x_indices_for_kpt_class = tf.gather(x_indices, instance_inds, axis=1)\n if boxes is None:\n boxes_for_kpt_class = None\n else:\n boxes_for_kpt_class = tf.gather(boxes, instance_inds, axis=1)\n\n # Postprocess keypoints and scores for class and single image. Shapes\n # are [1, num_instances_i, num_keypoints_i, 2] and\n # [1, num_instances_i, num_keypoints_i], respectively. Note that\n # num_instances_i and num_keypoints_i refers to the number of\n # instances and keypoints for class i, respectively.\n (kpt_coords_for_class, kpt_scores_for_class, _) = (\n self._postprocess_keypoints_for_class_and_image(\n keypoint_heatmap,\n keypoint_offsets,\n keypoint_regression,\n classes,\n y_indices_for_kpt_class,\n x_indices_for_kpt_class,\n boxes_for_kpt_class,\n ex_ind,\n kp_params,\n ))\n\n # Prepare the indices for scatter_nd. The resulting combined_inds has\n # the shape of [num_instances_i * num_keypoints_i, 2], where the first\n # column corresponds to the instance IDs and the second column\n # corresponds to the keypoint IDs.\n kpt_inds = tf.constant(kp_params.keypoint_indices, dtype=tf.int32)\n kpt_inds = tf.expand_dims(kpt_inds, axis=0)\n instance_inds_expand = tf.expand_dims(instance_inds, axis=-1)\n kpt_inds_expand = kpt_inds * tf.ones_like(instance_inds_expand)\n instance_inds_expand = instance_inds_expand * tf.ones_like(kpt_inds)\n combined_inds = tf.stack(\n [instance_inds_expand, kpt_inds_expand], axis=2)\n combined_inds = tf.reshape(combined_inds, [-1, 2])\n\n # Reshape the keypoint coordinates/scores to [num_instances_i *\n # num_keypoints_i, 2]/[num_instances_i * num_keypoints_i] to be used\n # by scatter_nd_add.\n kpt_coords_for_class = tf.reshape(kpt_coords_for_class, [-1, 2])\n kpt_scores_for_class = tf.reshape(kpt_scores_for_class, [-1])\n kpt_coords_for_example_all_det = tf.tensor_scatter_nd_add(\n kpt_coords_for_example_all_det,\n combined_inds, kpt_coords_for_class)\n kpt_scores_for_example_all_det = tf.tensor_scatter_nd_add(\n kpt_scores_for_example_all_det,\n combined_inds, kpt_scores_for_class)\n\n kpt_coords_for_example_list.append(\n tf.expand_dims(kpt_coords_for_example_all_det, axis=0))\n kpt_scores_for_example_list.append(\n tf.expand_dims(kpt_scores_for_example_all_det, axis=0))\n\n # Concatenate all keypoints and scores from all examples in the batch.\n # Shapes are [batch_size, max_detections, num_total_keypoints, 2] and\n # [batch_size, max_detections, num_total_keypoints], respectively.\n keypoints = tf.concat(kpt_coords_for_example_list, axis=0)\n keypoint_scores = tf.concat(kpt_scores_for_example_list, axis=0)\n\n return keypoints, keypoint_scores",
"def prediction_processing(predictions, labels, threshold, step_nb):\n new_labels = []\n new_predictions = []\n number_sequences = step_nb//50\n\n for k in range(len(labels)//number_sequences):\n total_prediction = 0\n isLabelTrue = labels[number_sequences*k]\n for i in range(number_sequences):\n total_prediction += (1/predictions[number_sequences*k+i])\n if not(isLabelTrue == (labels[number_sequences*k+i])):\n logger.error('Problem.')\n if total_prediction > threshold:\n total_prediction = False\n else:\n total_prediction = True\n new_labels.append(isLabelTrue)\n new_predictions.append(total_prediction)\n\n recall_1 = recall_score(new_labels, new_predictions)\n recall_0 = recall_score(new_labels, new_predictions, pos_label=0)\n precision_1 = precision_score(new_labels, new_predictions)\n precision_0 = precision_score(new_labels, new_predictions, pos_label=0)\n return((recall_1, recall_0, precision_1, precision_0), new_predictions, new_labels)",
"def prepareSplitClassifier(df, models, choice):\n\n\n def classificationOutput(clf, X, Y):\n \"\"\"\n Fit the model and print the classification results\n - confusion_matrix\n - avg scores etc\n \"\"\"\n n_samples = 36\n\n print \"\\n\\nClassifier: \\n %s\" % (clf)\n print \"#\" * 79\n # classifier_gnb = naive_bayes.GaussianNB() # initiating the classifier\n\n clf.fit(X[:n_samples], Y[:n_samples]) # train on first n_samples and test on last 10\n\n expected = Y[n_samples:]\n predicted = clf.predict(X[n_samples:])\n print(\"Classification report:\\n%s\\n\" % (metrics.classification_report(expected, predicted)))\n print(\"\\nConfusion matrix:\\n%s\" % metrics.confusion_matrix(expected, predicted))\n\n\n\n\n def splitclassify(cDf):\n \"\"\"\n Given the dataframe combined with equal fair and unfair apps,\n classify them\n \"\"\"\n cDf = cDf.reindex(np.random.permutation(cDf.index)) # shuffle the dataframe\n featCols = set(cDf.columns)\n featCols.remove('appLabel')\n\n features = cDf[list(featCols)].astype('float')\n\n ## Scale the features to a common range\n min_max_scaler = preprocessing.MinMaxScaler()\n X = min_max_scaler.fit_transform(features.values)\n\n Y = cDf['appLabel'].values\n\n\n if choice == 'all':\n for key in models:\n classifier = models[key]\n classificationOutput(classifier, X, Y)\n else:\n if choice in models:\n classifier = models[choice]\n classificationOutput(classifier, X, Y)\n else:\n print \"Incorrect Choice\"\n\n\n\n fairDf = df[df['appLabel'] == False]\n unfairDf = df[df['appLabel'] == True]\n\n\n # calculate total possible splits of fair data frame relatie to\n # size of unfair dataframe\n splits = len(fairDf) // len(unfairDf)\n\n for i in range(splits):\n clDf = fairDf[i : i+len(unfairDf)].append(unfairDf)\n\n # print fairDf.values, unfairDf.values\n print \"Classifying %d th split of fair apps with unfair app\" % (i)\n print \"-\" * 79\n splitclassify(clDf)\n print \"\\n\\n\"",
"def tile_predict(self, img, input_size=[713, 713]):\n \n setattr(self, 'input_size', input_size)\n\n def _pad_img(img):\n if img.shape[1] < self.input_size[0]:\n pad_h = self.input_size[0] - img.shape[1]\n img = np.pad(img, ((0, 0), (0, pad_h), (0, 0)), 'constant')\n else:\n pad_h = 0\n if img.shape[2] < self.input_size[1]:\n pad_w = self.input_size[1] - img.shape[2]\n img = np.pad(img, ((0, 0), (0, 0), (0, pad_w)), 'constant')\n else:\n pad_w = 0\n return img, pad_h, pad_w\n\n\n ori_rows, ori_cols = img.shape[1:]\n long_size = max(ori_rows, ori_cols)\n \n if long_size > max(self.input_size):\n count = np.zeros((ori_rows, ori_cols))\n pred = np.zeros((1, self.n_classes, ori_rows, ori_cols))\n stride_rate = 2 / 3.\n stride = (int(ceil(self.input_size[0] * stride_rate)),\n int(ceil(self.input_size[1] * stride_rate)))\n hh = int(ceil((ori_rows - self.input_size[0]) / stride[0])) + 1\n ww = int(ceil((ori_cols - self.input_size[1]) / stride[1])) + 1\n for yy in range(hh):\n for xx in range(ww):\n sy, sx = yy * stride[0], xx * stride[1]\n ey, ex = sy + self.input_size[0], sx + self.input_size[1]\n img_sub = img[:, sy:ey, sx:ex]\n img_sub, pad_h, pad_w = _pad_img(img_sub)\n img_sub_flp = np.copy(img_sub[:, :, ::-1])\n\n inp = Variable(torch.unsqueeze(torch.from_numpy(img_sub).float(), 0).cuda(), volatile=True)\n flp = Variable(torch.unsqueeze(torch.from_numpy(img_sub_flp).float(), 0).cuda(), volatile=True)\n psub1 = F.softmax(self.forward(inp), dim=1).data.cpu().numpy()\n psub2 = F.softmax(self.forward(flp), dim=1).data.cpu().numpy()\n\n psub = (psub1 + psub2[:, :, :, ::-1]) / 2.0\n\n if sy + self.input_size[0] > ori_rows:\n psub = psub[:, :, :-pad_h, :]\n if sx + self.input_size[1] > ori_cols:\n psub = psub[:, :, :, :-pad_w]\n pred[:, :, sy:ey, sx:ex] = psub\n count[sy:ey, sx:ex] += 1\n score = (pred / count[None, None, ...]+0.0001).astype(np.float32)\n else:\n img, pad_h, pad_w = _pad_img(img)\n inp = Variable(torch.unsqueeze(torch.from_numpy(img), 0).cuda(), volatile=True)\n pred1 = F.softmax(self.forward(inp), dim=1).data.cpu().numpy()\n pred2 = F.softmax(self.forward(inp[:, :, :, ::-1]), dim=1).data.cpu().numpy()\n pred = (pred1 + pred2[:, :, :, ::-1]) / 2.0\n score = pred[:, :, :self.input_size[0] - pad_h, :self.input_size[1] - pad_w]\n \n tscore = F.upsample(torch.from_numpy(score), size=(ori_rows, ori_cols), mode='bilinear')\n score = tscore[0].data.numpy()\n return score / score.sum(axis=0)",
"def mask_classes(outputs: torch.Tensor, dataset: ContinualDataset, k: int) -> None:\n outputs[:, 0:k * dataset.N_CLASSES_PER_TASK] = -float('inf')\n outputs[:, (k + 1) * dataset.N_CLASSES_PER_TASK:\n dataset.N_TASKS * dataset.N_CLASSES_PER_TASK] = -float('inf')"
] | [
"0.6202629",
"0.56319284",
"0.55949056",
"0.5581213",
"0.55317783",
"0.55251276",
"0.55228347",
"0.5518485",
"0.55066335",
"0.5490606",
"0.5483566",
"0.5453201",
"0.54506636",
"0.5432664",
"0.5418056",
"0.54165256",
"0.5387387",
"0.53693783",
"0.5364137",
"0.53587484",
"0.53543705",
"0.53343534",
"0.53305066",
"0.5320869",
"0.53041303",
"0.5290496",
"0.52738756",
"0.52661616",
"0.5264177",
"0.524813"
] | 0.76767987 | 0 |
Gets training data for classification, from only the given classes Either filter existing data, or load the default training data, and filter that. If either train_data or true_classes is None, the data will be loaded using get_training_data() from utils.loading | def getSubClassifierData(subclasses = [2,3], train_data = None, true_classes = None):
if (train_data is None) or (true_classes is None):
train_data, true_classes, _ = get_training_data()
assert len(true_classes) == np.shape(train_data)[0]
validsample = np.array([x in subclasses for x in true_classes])
return train_data[validsample,:], true_classes[validsample] | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def load_training_data(\n self,\n train_data_file=\"datasets/train_data.json\",\n test_data_file=\"datasets/test_data.json\",\n ):\n train_data = pd.read_json(train_data_file)\n test_data = pd.read_json(test_data_file)\n return train_data, test_data",
"def train(self):\r\n for class_ in set(self.train_classes):\r\n data = map(lambda (ind, datum): datum, filter(lambda (ind, datum): self.train_classes[ind] == class_, enumerate(self.train_data)))\r\n self.distribution.index_data(data, class_)",
"def load_data_preprocess(self):\n\n print(\"Loading the dataset ...\")\n # load the data\n c_util = CarUtils()\n train_x, train_y, test_x, test_y, classes = c_util.load_data()\n\n # set the image ordering\n K.set_image_dim_ordering(\"th\")\n\n print(\"Pre-processing the dataset ...\")\n # pre-process the data\n train_x = train_x.astype('float32')\n test_x = test_x.astype('float32')\n\n train_x = train_x / 255\n test_x = test_x / 255\n\n print(train_x.shape[0], ' train samples')\n print(test_x.shape[0], ' test samples')\n\n train_y = np_utils.to_categorical(train_y, CarsClassifierModel._nb_classes)\n test_y = np_utils.to_categorical(test_y, CarsClassifierModel._nb_classes)\n\n return train_x, train_y, test_x, test_y",
"def train(cls, features=None, classes=None):\n classifier = CSClassifier()\n if classes is None or features is None:\n features, classes = cls.get_prepared_data()\n X = tuple(features)\n Y = tuple(classes)\n classifier = classifier.fit(X, Y)\n return classifier",
"def train_naive_bayes_soy(train_set, classes):\n\n print('[ INFO ]: Training soy data with Naive Bayes Classifier...')\n\n class_probabilities = {}\n class_feature_probs = {}\n\n for soy_class in classes:\n\n feature_true_probs = {}\n feature_false_probs = {}\n\n # Find the probability that each class is in the training set\n class_probabilities[soy_class] = len(train_set[(train_set[soy_class] == 1)]) / len(train_set)\n\n # Compute the conditional feature probabilities based on the class probabilities\n # where the class is present\n class_true = train_set[(train_set[soy_class] == 1)]\n for col in class_true.columns:\n if col not in classes:\n try:\n true_true = len(class_true[(class_true[col] == 1)]) / len(class_true)\n except:\n true_true = 0\n feature_true_probs[col] = true_true\n\n # Compute the conditional feature probabilities based on the class probabilities\n # where the class is not present\n class_false = train_set[(train_set[soy_class] == 0)]\n for col in class_false.columns:\n if col not in classes:\n try:\n false_false = len(class_false[(class_false[col] == 0)]) / len(class_false)\n except:\n false_false = 0\n feature_false_probs[col] = false_false\n\n class_feature_probs[soy_class] = [feature_true_probs, feature_false_probs]\n\n return class_probabilities, class_feature_probs",
"def get_classification_training_data() -> Iterable[Tuple[str, Dict[str, Any]]]:\n return (_create_training_entry(*pair) for pair in TRAINING_DATA) # type: ignore",
"def load_training_data(self) -> Tuple[List[np.ndarray], np.ndarray]:\n return self._load_set(config.TRAIN_DIR, True)",
"def preprocess_with_train_data(self,\n data_dir: Path,\n output_processed_data_dir: Path,\n ) -> NoReturn:\n pass",
"def split_data(train_split, src_dir, train_dir, test_dir, classes):\n for cls in classes:\n # get all dat files of this class\n data = get_instances_of_class(cls, src_dir)\n \n # how many of the data points are for training?\n train_count = round(len(data) * train_split / 100)\n \n # randomly choose indexes\n train_indexes = set()\n while len(train_indexes) < train_count:\n train_indexes.add(random.randrange(len(data)))\n \n # move all train_indexes to train_dir, others to test_dir\n COPY = lambda src, dst, filename:\\\n shutil.copy2(\n \"{}/{}\".format(src, data[i]),\n \"{}/{}\".format(dst, data[i])\n )\n \n for i in range(len(data)):\n if i in train_indexes:\n COPY(src_dir, train_dir, data[i])\n else:\n COPY(src_dir, test_dir, data[i])",
"def train(self, batch_training=False):\n raise NotImplementedError",
"def get_data_loader(target_classes, batch_size):\n classes = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n ########################################################################\n # The output of torchvision datasets are PILImage images of range [0, 1].\n # We transform them to Tensors of normalized range [-1, 1].\n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n trainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\n # Get the list of indices to sample from\n relevant_train_indices = get_relevant_indices(\n trainset,\n classes,\n target_classes)\n # Split into train and validation\n np.random.seed(1000) # Fixed numpy random seed for reproducible shuffling\n np.random.shuffle(relevant_train_indices)\n split = int(len(relevant_train_indices) * 0.8)\n relevant_train_indices, relevant_val_indices = relevant_train_indices[:split], relevant_train_indices[split:]\n train_sampler = SubsetRandomSampler(relevant_train_indices)\n train_loader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,\n num_workers=0, sampler=train_sampler)\n val_sampler = SubsetRandomSampler(relevant_val_indices)\n val_loader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,\n num_workers=0, sampler=val_sampler)\n testset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\n relevant_test_indices = get_relevant_indices(testset, classes, target_classes)\n test_sampler = SubsetRandomSampler(relevant_test_indices)\n test_loader = torch.utils.data.DataLoader(testset, batch_size=batch_size,\n num_workers=0, sampler=test_sampler)\n return train_loader, val_loader, test_loader, classes",
"def train(self, train_data, train_labels):\n\n # Apply filtering\n if len(self.preprocessing) > 0:\n print('Applying', len(self.preprocessing), 'filter(s) to training data')\n for filter in self.preprocessing:\n for i in range(len(train_data)):\n train_data[i] = filter(train_data[i])\n\n # Apply feature extraction\n if len(self.features) > 0:\n print('Extracting', len(self.features), 'feature(s) from training data')\n scaler = MinMaxScaler(feature_range=(0, 1))\n for i in range(len(train_data)):\n features = []\n for feature in self.features:\n features.append(feature(train_data[i]))\n train_data[i] = np.hstack(features)\n train_data = scaler.fit_transform(train_data)\n else:\n # Flatten images (not necessary when using feature extraction)\n train_data = np.array(train_data).reshape((len(train_data), -1))\n\n # Fit model\n print('Fitting RF model on', len(train_labels), 'images')\n self.classifier.fit(train_data, train_labels)",
"def train_knn(training_data):\n return knnclassifier(training_data, keys, 3)",
"def train(self, training_data):\n pass",
"def train_classifier(self, epochs):\n import copy\n\n # Prepare data for Classifier\n clas_data = CatClasDataIter(self.clas_samples_list)\n eval_clas_data = CatClasDataIter(self.train_samples_list)\n\n max_acc = 0\n best_clas = None\n for epoch in range(epochs):\n c_loss, c_acc = self.train_dis_epoch(self.clas, clas_data.loader, self.clas_criterion,\n self.clas_opt)\n _, eval_acc = self.eval_dis(self.clas, eval_clas_data.loader, self.clas_criterion)\n if eval_acc > max_acc:\n best_clas = copy.deepcopy(self.clas.state_dict()) # save the best classifier\n max_acc = eval_acc\n self.log.info('[PRE-CLAS] epoch %d: c_loss = %.4f, c_acc = %.4f, eval_acc = %.4f, max_eval_acc = %.4f',\n epoch, c_loss, c_acc, eval_acc, max_acc)\n self.clas.load_state_dict(copy.deepcopy(best_clas)) # Reload the best classifier",
"def train_on_raw_data(data_alice, data_bob):\n raw_test_data = pd.concat([data_alice[1], data_bob[1]])\n x = raw_test_data.drop('Class', axis=1)\n y = raw_test_data['Class']\n\n return fit_rf_classifier(x, y)",
"def load_training_data(config):\n # Load data\n LOGGER.info(\"Loading training data.\")\n train_x = load_data(config['data_source'], config['train_x_filename'])\n train_y = load_data(config['data_source'], config['train_y_filename'])\n val_x = load_data(config['data_source'], config['val_x_filename'])\n val_y = load_data(config['data_source'], config['val_y_filename'])\n LOGGER.info(\"Training data size: %d\", len(train_x))\n LOGGER.info(\"Validation data size: %d\", len(val_x))\n\n # Build datasets and create iterators\n LOGGER.info(\"Building dataset.\")\n train_dataset = get_dataset(\n train_x, train_y, config['batch_size'], config['data_shape'],\n config['n_classes'], True)\n val_dataset = get_dataset(\n val_x, val_y, config['batch_size'], config['data_shape'],\n config['n_classes'])\n\n return train_dataset, val_dataset, len(val_x)",
"def get_training_data() -> GraphDataset:\n _load_data_if_needed()\n return training_data",
"def train(\n self, training_data: Dataset, validation_data: Optional[Dataset] = None\n ) -> Predictor:\n raise NotImplementedError",
"def get_train(self, preprocess=False):\n return self._dataset(self._directory, 'images_background_small1', preprocess)",
"def train(self, training_data, cfg, **kwargs):\n pass",
"def train(self, trainingData, trainingLabels, validationData, validationLabels):\t \n\t \n\t# might be useful in your code later...\n\t# this is a list of all features in the training set.\n\tself.features = list(set([ f for datum in trainingData for f in datum.keys() ]));\n\t\n\tif (self.automaticTuning):\n\t\tkgrid = [0.001, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 20, 50]\n\telse:\n\t\tkgrid = [self.k]\n\t\t\n\tself.trainAndTune(trainingData, trainingLabels, validationData, validationLabels, kgrid)",
"def train(self, trainingData, trainingLabels, validationData, validationLabels):\n\n self.features = trainingData[0].keys() # this could be useful for your code later...\n\n if (self.automaticTuning):\n kgrid = [0.001, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 20, 50]\n else:\n kgrid = [self.k]\n\n self.trainAndTune(trainingData, trainingLabels, validationData, validationLabels, kgrid)",
"def load_dataset(self, testPrefix = 'cv9', root = 'datasets', classes = [ 'pos', 'neg' ]):\n\n\t\tfor senti_class in classes:\n\n\t\t\tdirname = os.path.join(root, senti_class)\n\n\t\t\tfor filename in os.listdir(dirname):\n\n\t\t\t\twith open(os.path.join(dirname, filename)) as file:\n\n\t\t\t\t\tcontent = file.read()\n\n\t\t\t\t\tif filename.startswith(testPrefix):\n\t\t\t\t\t\t# Testing data\n\t\t\t\t\t\tself.testing_set.append(content)\n\t\t\t\t\t\tself.testing_labels.append(senti_class)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# Training data\n\t\t\t\t\t\tself.training_set.append(content)\n\t\t\t\t\t\tself.training_labels.append(senti_class)\n\n\t\tself._vectorize(self.vectorizer)",
"def setClassFilter(self, includeClasses):\n self.__datasets = [d for d in self.__datasetsAll if d[-1] in includeClasses]\n self.__scaled_datasets = None\n self.activeClasses = includeClasses\n self.dataChanged.emit()",
"def train(self, trainingData, trainingLabels, testData, testLabels, validate): \n\t\t \n\t\tself.features = trainingData[0].keys() # this could be useful for your code later...\n\n\t\tif (self.automaticTuning):\n\t\t\tCgrid = [0.001, 0.002, 0.003, 0.004, 0.005]\n\t\telse:\n\t\t\tCgrid = [self.C]\n\t\t\t\n\t\treturn self.trainAndTune(trainingData, trainingLabels, testData, testLabels, Cgrid, validate)",
"def train(self, training_data, training_labels, validation_data, validation_labels):\n abstract",
"def train(self):\n for data_tier in self.data_tiers:\n fd = open(self.data_path + '/training_data_' + data_tier + '.json', 'r')\n self.preprocessed_data[data_tier] = json.load(fd)\n fd.close()\n tot = len(self.preprocessed_data[data_tier]['features'])\n p = int(math.ceil(tot*0.8))\n training_features = np.array(self.preprocessed_data[data_tier]['features'][:p])\n trend_training_classifications = np.array(self.preprocessed_data[data_tier]['trend_classifications'][:p])\n avg_training_classifications = np.array(self.preprocessed_data[data_tier]['avg_classifications'][:p])\n t1 = datetime.datetime.utcnow()\n self.clf_trend[data_tier].fit(training_features, trend_training_classifications)\n self.clf_avg[data_tier].fit(training_features, avg_training_classifications)\n t2 = datetime.datetime.utcnow()\n td = t2 - t1\n self.logger.info('Training %s for data tier %s took %s', self.name, data_tier, str(td))\n joblib.dump(self.clf_trend[data_tier], self.data_path + '/' + self.name + '_trend_' + data_tier + '.pkl')\n joblib.dump(self.clf_avg[data_tier], self.data_path + '/' + self.name + '_avg_' + data_tier + '.pkl')",
"def pre_train(self, dataset, **kwargs):\n\n pass",
"def train(self, trainingData, trainingLabels, validationData, validationLabels): \n \n # might be useful in your code later...\n # this is a list of all features in the training set.\n self.features = list(set([ f for datum in trainingData for f in datum.keys() ]));\n \n if (self.automaticTuning):\n kgrid = [0.001, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 20, 50]\n else:\n kgrid = [self.k]\n \n self.trainAndTune(trainingData, trainingLabels, validationData, validationLabels, kgrid)"
] | [
"0.6166976",
"0.60436237",
"0.59472346",
"0.59368724",
"0.5928723",
"0.59101176",
"0.5907316",
"0.58968824",
"0.58936644",
"0.5892785",
"0.5844393",
"0.5816411",
"0.5815247",
"0.5812829",
"0.5800985",
"0.57745534",
"0.5773249",
"0.575504",
"0.57530016",
"0.5745181",
"0.57328063",
"0.57251954",
"0.57183015",
"0.57141745",
"0.5713416",
"0.5705712",
"0.57022077",
"0.569641",
"0.5642544",
"0.5642033"
] | 0.64171195 | 0 |
Get an existing UserGpgKey resource's state with the given name, id, and optional extra properties used to qualify the lookup. | def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
created_at: Optional[pulumi.Input[str]] = None,
key: Optional[pulumi.Input[str]] = None,
key_id: Optional[pulumi.Input[int]] = None,
user_id: Optional[pulumi.Input[int]] = None) -> 'UserGpgKey':
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _UserGpgKeyState.__new__(_UserGpgKeyState)
__props__.__dict__["created_at"] = created_at
__props__.__dict__["key"] = key
__props__.__dict__["key_id"] = key_id
__props__.__dict__["user_id"] = user_id
return UserGpgKey(resource_name, opts=opts, __props__=__props__) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_state_by_id(state_id):\n for key, value in storage.all(\"State\").items():\n if state_id == value.id:\n return jsonify(value.to_dict())\n abort(404)",
"def get_state_by_id(state_id):\n my_state = storage.get('State', state_id)\n if my_state is None:\n abort(404)\n return jsonify(my_state.to_dict())",
"def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n access_string: Optional[pulumi.Input[str]] = None,\n arn: Optional[pulumi.Input[str]] = None,\n authentication_mode: Optional[pulumi.Input[pulumi.InputType['UserAuthenticationModeArgs']]] = None,\n engine: Optional[pulumi.Input[str]] = None,\n no_password_required: Optional[pulumi.Input[bool]] = None,\n passwords: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,\n tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,\n tags_all: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,\n user_id: Optional[pulumi.Input[str]] = None,\n user_name: Optional[pulumi.Input[str]] = None) -> 'User':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _UserState.__new__(_UserState)\n\n __props__.__dict__[\"access_string\"] = access_string\n __props__.__dict__[\"arn\"] = arn\n __props__.__dict__[\"authentication_mode\"] = authentication_mode\n __props__.__dict__[\"engine\"] = engine\n __props__.__dict__[\"no_password_required\"] = no_password_required\n __props__.__dict__[\"passwords\"] = passwords\n __props__.__dict__[\"tags\"] = tags\n __props__.__dict__[\"tags_all\"] = tags_all\n __props__.__dict__[\"user_id\"] = user_id\n __props__.__dict__[\"user_name\"] = user_name\n return User(resource_name, opts=opts, __props__=__props__)",
"def get_key(self, state):\n pass",
"def get_state_by_id(state_id):\n state = storage.get(State, state_id)\n if not state:\n abort(404)\n return jsonify(state.to_dict()), 200",
"def get_by_id(self, model, key_name):\n return model.get_by_id(key_name)",
"def state_by_id(state_id):\n state = storage.get(State, state_id)\n if state is None:\n abort(404)\n return jsonify(state.to_dict())",
"def get_state_by_name(exploration_id, state_name, strict=True):\n exploration = get_exploration_by_id(exploration_id)\n assert state_name\n\n # TODO(sll): This is too slow; improve it.\n state = None\n for candidate_state in exploration.states:\n if candidate_state.name == state_name:\n state = candidate_state\n break\n\n if strict and not state:\n raise Exception('State %s not found' % state_name)\n return state",
"def state_by_id(state_id):\n states_values = storage.all(\"State\").values()\n for obj in states_values:\n if obj.id == state_id:\n return jsonify(obj.to_dict())\n abort(404)",
"def get_state(state_id):\n try:\n ''' Check that state_id exists '''\n query = State.select().where(State.id == state_id)\n if not query.exists():\n raise LookupError('state_id')\n\n state = State.get(State.id == state_id)\n return state.to_dict(), 200\n except LookupError as e:\n abort(404)\n except Exception as e:\n abort(500)",
"def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n disabled: Optional[pulumi.Input[bool]] = None,\n email: Optional[pulumi.Input[str]] = None,\n name: Optional[pulumi.Input[str]] = None,\n roles: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,\n send_user_invitation: Optional[pulumi.Input[bool]] = None,\n user_invitation_id: Optional[pulumi.Input[str]] = None,\n verified: Optional[pulumi.Input[bool]] = None) -> 'User':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _UserState.__new__(_UserState)\n\n __props__.__dict__[\"disabled\"] = disabled\n __props__.__dict__[\"email\"] = email\n __props__.__dict__[\"name\"] = name\n __props__.__dict__[\"roles\"] = roles\n __props__.__dict__[\"send_user_invitation\"] = send_user_invitation\n __props__.__dict__[\"user_invitation_id\"] = user_invitation_id\n __props__.__dict__[\"verified\"] = verified\n return User(resource_name, opts=opts, __props__=__props__)",
"def a_state(id):\n state = storage.get(State, id)\n if state is not None:\n return jsonify(state.to_dict())\n abort(404)",
"def get_state(state_id):\n try:\n state = jsonify(storage.get(State, state_id).to_dict())\n return state\n except:\n abort(404)",
"def state_id(state_id):\n state = storage.get(State, state_id)\n if state is None:\n abort(404)\n else:\n return jsonify(state.to_dict())",
"def get_state(state_id):\n state = storage.get(State, state_id)\n if state is None:\n abort(404)\n return jsonify(state.to_dict())",
"def a_states_id(state_id):\n i = storage.get(\"State\", state_id)\n if i:\n return jsonify(i.to_dict())\n else:\n return (jsonify({\"error\": \"Not found\"}), 404)",
"def get_id(\n name=None,\n tags=None,\n region=None,\n key=None,\n keyid=None,\n profile=None,\n in_states=None,\n filters=None,\n):\n instance_ids = find_instances(\n name=name,\n tags=tags,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile,\n in_states=in_states,\n filters=filters,\n )\n if instance_ids:\n log.info(\"Instance ids: %s\", \" \".join(instance_ids))\n if len(instance_ids) == 1:\n return instance_ids[0]\n else:\n raise CommandExecutionError(\n \"Found more than one instance matching the criteria.\"\n )\n else:\n log.warning(\"Could not find instance.\")\n return None",
"def get_state(state_id):\n state = storage.get(\"State\", state_id)\n if state:\n return jsonify(state.to_dict())\n abort(404)",
"def lookup(self, user_id):\n raise NotImplementedError",
"def get_one_state(state_id):\n state = storage.get('State', state_id)\n if state is None:\n abort(404)\n if request.method == 'DELETE':\n storage.delete(state)\n storage.save()\n return jsonify({}), 200\n elif request.method == 'PUT':\n try:\n res_dict = request.get_json()\n res_dict['id'] = state.id\n res_dict['created_at'] = state.created_at\n state.__init__(**res_dict)\n state.save()\n return jsonify(state.to_dict()), 200\n except:\n abort(400, description='Not a JSON')\n return jsonify(state.to_dict())",
"def lookup(job_id: str) -> JobState:\n job = JobState(job_id)\n job.update()\n return job",
"def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None) -> 'CryptoKey':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = CryptoKeyArgs.__new__(CryptoKeyArgs)\n\n __props__.__dict__[\"create_time\"] = None\n __props__.__dict__[\"crypto_key_backend\"] = None\n __props__.__dict__[\"crypto_key_id\"] = None\n __props__.__dict__[\"destroy_scheduled_duration\"] = None\n __props__.__dict__[\"import_only\"] = None\n __props__.__dict__[\"key_ring_id\"] = None\n __props__.__dict__[\"labels\"] = None\n __props__.__dict__[\"location\"] = None\n __props__.__dict__[\"name\"] = None\n __props__.__dict__[\"next_rotation_time\"] = None\n __props__.__dict__[\"primary\"] = None\n __props__.__dict__[\"project\"] = None\n __props__.__dict__[\"purpose\"] = None\n __props__.__dict__[\"rotation_period\"] = None\n __props__.__dict__[\"skip_initial_version_creation\"] = None\n __props__.__dict__[\"version_template\"] = None\n return CryptoKey(resource_name, opts=opts, __props__=__props__)",
"def read(self, user_id):\n if not user_id in self.user_ids:\n raise KeyError(\"Invalid user ID. Check the read-only property \" \\\n \"user_ids for a list of valid IDs.\")\n user_load = self._store[\"id_\" + str(user_id)]\n self._loads[user_id] = user_load\n return user_load",
"def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n add_on: Optional[pulumi.Input[pulumi.InputType['InstanceAddOnArgs']]] = None,\n arn: Optional[pulumi.Input[str]] = None,\n availability_zone: Optional[pulumi.Input[str]] = None,\n blueprint_id: Optional[pulumi.Input[str]] = None,\n bundle_id: Optional[pulumi.Input[str]] = None,\n cpu_count: Optional[pulumi.Input[int]] = None,\n created_at: Optional[pulumi.Input[str]] = None,\n ip_address_type: Optional[pulumi.Input[str]] = None,\n ipv6_address: Optional[pulumi.Input[str]] = None,\n ipv6_addresses: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,\n is_static_ip: Optional[pulumi.Input[bool]] = None,\n key_pair_name: Optional[pulumi.Input[str]] = None,\n name: Optional[pulumi.Input[str]] = None,\n private_ip_address: Optional[pulumi.Input[str]] = None,\n public_ip_address: Optional[pulumi.Input[str]] = None,\n ram_size: Optional[pulumi.Input[float]] = None,\n tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,\n tags_all: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,\n user_data: Optional[pulumi.Input[str]] = None,\n username: Optional[pulumi.Input[str]] = None) -> 'Instance':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _InstanceState.__new__(_InstanceState)\n\n __props__.__dict__[\"add_on\"] = add_on\n __props__.__dict__[\"arn\"] = arn\n __props__.__dict__[\"availability_zone\"] = availability_zone\n __props__.__dict__[\"blueprint_id\"] = blueprint_id\n __props__.__dict__[\"bundle_id\"] = bundle_id\n __props__.__dict__[\"cpu_count\"] = cpu_count\n __props__.__dict__[\"created_at\"] = created_at\n __props__.__dict__[\"ip_address_type\"] = ip_address_type\n __props__.__dict__[\"ipv6_address\"] = ipv6_address\n __props__.__dict__[\"ipv6_addresses\"] = ipv6_addresses\n __props__.__dict__[\"is_static_ip\"] = is_static_ip\n __props__.__dict__[\"key_pair_name\"] = key_pair_name\n __props__.__dict__[\"name\"] = name\n __props__.__dict__[\"private_ip_address\"] = private_ip_address\n __props__.__dict__[\"public_ip_address\"] = public_ip_address\n __props__.__dict__[\"ram_size\"] = ram_size\n __props__.__dict__[\"tags\"] = tags\n __props__.__dict__[\"tags_all\"] = tags_all\n __props__.__dict__[\"user_data\"] = user_data\n __props__.__dict__[\"username\"] = username\n return Instance(resource_name, opts=opts, __props__=__props__)",
"def get_key (self, name):\n return self + name",
"def get_state_by_id(exploration_id, state_id, strict=True):\n # TODO(sll): Generalize this to handle multiple state_ids at a time.\n state_memcache_key = _get_state_memcache_key(exploration_id, state_id)\n memcached_state = memcache_services.get_multi(\n [state_memcache_key]).get(state_memcache_key)\n\n if memcached_state is not None:\n return memcached_state\n else:\n state_model = exp_models.StateModel.get(\n exploration_id, state_id, strict=strict)\n if state_model:\n state = exp_domain.State.from_dict(state_id, state_model.value)\n memcache_services.set_multi({state_memcache_key: state})\n return state\n else:\n return None",
"def from_key(cls, id):\n return super().from_key(id)",
"def user_key(user_name=DEFAULT_USER_NAME):\n return ndb.Key('User', user_name)",
"def get(model_class, id):\n key = build_key(model_class, id)\n user = cache.get(key)\n if user is None: # Not in cache\n logger.info(\" CACHE MISS key=%s\", key)\n user = User.objects.filter(id=id).first()\n if user is not None: # Found in DB\n logger.info(\" CACHE POPULATE key=%s\", key)\n cache.set(key, user) # Add to cache\n else:\n logger.info(\" CACHE HIT key=%s\", key)\n return user",
"def getUserFromKey(key):\n\t\t#get(Key(key))\n\t\t#return None if no user found"
] | [
"0.5549637",
"0.55430037",
"0.5496678",
"0.543263",
"0.5378798",
"0.53005373",
"0.5287543",
"0.5244176",
"0.51912683",
"0.51762015",
"0.51510936",
"0.5111083",
"0.51086766",
"0.5092615",
"0.50612205",
"0.5041373",
"0.50369424",
"0.5009481",
"0.50084484",
"0.49910453",
"0.49833947",
"0.49605182",
"0.4945019",
"0.48765257",
"0.4873606",
"0.48535886",
"0.48236656",
"0.4821282",
"0.4813178",
"0.47992682"
] | 0.7061528 | 0 |
The ID of the GPG key. | def key_id(self) -> pulumi.Output[int]:
return pulumi.get(self, "key_id") | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def key_id(self):\n return self._key_id",
"def crypto_key_id(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"crypto_key_id\")",
"def key(self):\n return str(self._id)",
"def get_pgp_key_id(raw_key: bytes) -> str:\n # Flush stdout and stderr to prevent interleaving messages from a subprocess\n sys.stdout.flush()\n sys.stderr.flush()\n with tempfile.TemporaryDirectory(prefix=\"gnupghome\") as tmpdir:\n # Create an empty public keyring to avoid a GnuPG message\n with (Path(tmpdir) / \"pubring.kbx\").open(\"wb\"):\n pass\n output = subprocess.check_output(\n (\"gpg\", \"--list-packets\"),\n input=raw_key,\n env={\n \"GNUPGHOME\": tmpdir,\n \"HOME\": tmpdir,\n },\n )\n keyid_index = output.index(b\"keyid: \") + 7\n keyid_end_index = output.index(b\"\\n\", keyid_index)\n key_id = output[keyid_index:keyid_end_index].decode(\"ascii\")\n assert len(key_id) == 16\n assert all(c in \"0123456789ABCDEF\" for c in key_id)\n return key_id",
"def get_id_from_keyring(self):\n return keyring.get_password(self.keyring_service_name, \"connection_id\")",
"def get_key_id(self):",
"def id(self):\n\n return sha256(self.pub.export()).digest()",
"def key_id(self) -> Optional[pulumi.Input[int]]:\n return pulumi.get(self, \"key_id\")",
"def key(self):\n return self._key.decode('utf-8')",
"def crypto_key_id(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"crypto_key_id\")",
"def key(self) -> str:\n return self._key",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")",
"def key(self) -> str:\n return pulumi.get(self, \"key\")"
] | [
"0.76533425",
"0.73216677",
"0.7293038",
"0.72849256",
"0.7156193",
"0.71369255",
"0.7129503",
"0.7083336",
"0.70065194",
"0.6963701",
"0.69266695",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049",
"0.6895049"
] | 0.7478572 | 1 |
Create python configuration file for the projection script | def createCfg_project(self, jobOptions):
last_line = '%s %s %s %s' % (jobOptions['projection_module'], self.era, jobOptions['histName'], jobOptions['outputFile'])
if self.projection_module != 'puHist':
last_line += ' %.6e' % jobOptions['ref_genWeight']
lines = jobOptions['inputFiles'] + [ '', last_line ]
assert(len(lines) >= 3)
createFile(jobOptions['cfgFile_path'], lines, nofNewLines = 1) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def create_configuration(self, context):\n context.cfg_path = path = os.path.join(context.env_dir, 'pyvenv.cfg')\n with open(path, 'w', encoding='utf-8') as f:\n f.write('home = %s\\n' % context.python_dir)\n if self.system_site_packages:\n incl = 'true'\n else:\n incl = 'false'\n f.write('include-system-site-packages = %s\\n' % incl)\n f.write('version = %d.%d.%d\\n' % sys.version_info[:3])\n if self.prompt is not None:\n f.write(f'prompt = {self.prompt!r}\\n')",
"def make_config(config):\n config.set(\"dxr\", \"source_folder\", os.path.expanduser(\"~/dxr\"))",
"def config():\n file_path = None # path to the input file\n db_path = None # path to the output db\n atomic_properties = (\n \"Properties=species:S:1:pos:R:3\"\n ) # atomic properties of the input file\n molecular_properties = [\"energy\"] # molecular properties of the input file\n overwrite = False",
"def configuration(config):\n create_str_dir(config)\n add_skymap(config)\n save_configuration(config)",
"def create_config(self) -> None:\n pass",
"def create_config(self) -> None:\n pass",
"def generate_config(args):\n default_config = resource_string('webrpg', 'scripts/templates/default_config.txt').decode('utf-8')\n if args.sqla_connection_string:\n default_config = default_config.replace('%(sqlalchemy_url)s', args.sqla_connection_string)\n else:\n default_config = default_config.replace('%(sqlalchemy_url)s', get_user_parameter('SQL Alchemy Connection String', 'sqlite:///%(here)s/pyire_test.db'))\n\n with open(args.filename, 'w') as out_f:\n out_f.write(default_config)",
"def createPPSConfig(ppsConfigFilePath, keyDict):\n out = csv.OutFileBuffer(ppsConfigFilePath)\n out.writeText(\n \"\"\"#######################################################################\n#configuration file (PPS+ GENERATED !!!)\n#please make sure that there is no space before or after \":\"\n#lines starting with character \"#\" are treated as comments\n#please provide complete paths instead of only file or directory names\n#######################################################################\n#directory where processed NCBI data is stored, provide empty directory to create new\n#REUSABLE\\n\"\"\")\n out.writeText('NCBI_PROCESSED_DIR:%s\\n' % keyDict.get('NCBI_PROCESSED_DIR', ''))\n out.writeText(\n \"\"\"#Directory containing NCBI taxonomy in SQlite3 format with file name \"ncbitax_sqlite.db\"\n#provide empty directory to create new database\n#REUSABLE\\n\"\"\")\n out.writeText('NCBI_TAX_DIR:%s\\n' % keyDict.get('NCBI_TAX_DIR', ''))\n out.writeText('#project directory, the directory must be empty\\n')\n out.writeText('PROJECT_DIR:%s\\n' % keyDict.get('PROJECT_DIR', ''))\n out.writeText(\n \"\"\"#############################\n#!!!FOLLOWING ARE OPTIONAL!!!\n#############################\n###### Output space options #####\n#a file containing a tree in newick format (see restrictions in INSTALL.txt)\n#OR a file with ncbi taxon ids (one id per line) to create a tree from\\n\"\"\")\n out.writeText('TREE_FILE:%s\\n' % keyDict.get('TREE_FILE', ''))\n out.writeText(\n \"\"\"#Taxonomic ranks (comma separated, no space) starting at the lowest rank. \\\nPlease make sure that \"root\" is there at the end.\nTAXONOMY_RANKS:species,genus,family,order,class,phylum,superkingdom,root\n#number of minimum genomes a clade must contain to be included in generic model\n#effective only if tree file is not provided\nN_MIN_GENOMES_GENERIC:3\n#action on loss 0:disabled, 1:invert\nLOSS_ACTION:0\n###### Input space options #####\n#a directory with sample specific fasta files (file names must start with appropriate organism/species \\\nncbi taxonomic id)\n#leave empty if you don't have any\\n\"\"\")\n out.writeText('SAMPLE_SPECIFIC_DIR:%s\\n' % keyDict.get('SAMPLE_SPECIFIC_DIR', ''))\n out.writeText(\n \"\"\"#kmer feature space for multiple kmers use kmer_min-kmer_max\nKMER:4-6\n#Fragment lengths for different models (comma separated, no space)\nFRAGMENT_LEN:1000,3000,5000,10000,15000,50000\n#kmer feature\n#use reverse complement for computing kmer features?\nREV_COMPLEMENT:1\n#remove reverse complement features?\nRM_REV_COMPLEMENT:1\n#0:disabled, 1:sequence length, 2:sequence_length-k+1, 3:embedded monomer frequency\nKMER_NORMALIZATION:1\n#Number of examples per training file\nNUMBER_EXAMPLES:10000\n#step size for sample specific data; either a single number (for all fragment lengths) or an array separated with \",\"\nSAMPLE_SPECIFIC_STEP:1000,300,500,1000,1500,5000\n###### Training options #####\n#C values for SVM, if single value is given then models will be build with that value.\n#If comma separated (no space) values are given then cross-validation will be performed.\n#If a single value is provided, all models will be built with it. Our experience shows that in general\n#values less than 1 (e.g. 0.01 and 0.1) do not provide good models.\nC_GRID:1000\n#clean-up the data (sampled_fasta and train_data directories) created after training? TRUE/FALSE\nCLEAN_UP_TRAIN:FALSE\n#kernel type 0:linear, 1:polynomial, 2:rbf (on-linear kernels are computationally expensive)\nKERNEL:0\n##polynomial kernel degree\nKERNEL_POLYNOMIAL_DEGREE:2\n##rbf kernel gamma\nKERNEL_RBF_GAMMA:1\n##polynomial kernel s\nKERNEL_POLYNOMIAL_S:1\n###### Predictions options #####\n#number of classifiers to use, keep this odd to avoid ties\nN_CLASSIFIERS:3\n#Create Pie charts for every taxonomic rank TRUE/FALSE (in prediction)\n#slice colors are determined automatically so no color consistency is guaranteed\nPIE_CHARTS:FALSE\n###### Misc options #####\n#should the models be built in parallel (please make sure that you have enough number of\nprocessors and main memory)\\n\"\"\")\n out.writeText('PARALLEL_MODELS:%s\\n' % keyDict.get('PARALLEL_MODELS', 'FALSE'))\n out.writeText(\n \"\"\"#allowed file extensions\nEXTENSIONS:\n#genomes to exclude: file containing one ncbi tax_id per line\\n\"\"\")\n out.writeText('GENOMES_EXCLUDE:%s\\n' % keyDict.get('GENOMES_EXCLUDE', ''))\n out.writeText(\n \"\"\"#if the training data is already there then just build models (TRUE/FALSE)\nONLY_MODELS:FALSE\\n\"\"\")\n out.close()",
"def _CreateCfgFile():\n default_cfg = \"\"\"\nproject: \"fake_project\"\nzone: \"fake_zone\"\nstorage_bucket_name: \"fake_bucket\"\nclient_id: \"fake_client_id\"\nclient_secret: \"fake_client_secret\"\n\"\"\"\n return default_cfg",
"def write_configuration(creator, creator_version, default_values, required_values, filename=None):\n default_config, required_config = get_default_configuration()\n default_config.update(default_values)\n required_config.update(required_values)\n printdict = {\"prog\":creator, \"version\": creator_version}\n printdict.update(default_config)\n printdict.update(required_config)\n configuration = \"\"\"\n# Sample configuration file for {prog} version {version}\n# SVN revision $Rev: 1186 $\n# Last updated $Date: 2016-07-18 11:13:39 +0530 (Mon, 18 Jul 2016) $\n# Comment lines starting with # are ignored\n# Do not add extra spaces!\n#\n#\n[Config]\n#------------------------------------------------------------------------\n# Event-specific configuration\n#\n# Event name (for plots etc)\nname:{name}\n#\n# Level2 file for reprocessing\nl2file:{l2file}\n# Input file for analysis\ninfile:{infile}\n#\n# MKF file for getting rotation\nmkffile:{mkffile}\n#\n# Energy (keV)\nenergy:{energy}\n# Trigger time in czti seconds\n# Seconds since 1/1/2010, 00:00:00 UTC\ntrigtime:{trigtime}\n#\n# Start and end time for data to use for localisation\ntranstart:{transtart}\ntranend:{tranend}\n#\n# Define two windows for estimating background to subtract for localisation\nbkg1start:{bkg1start}\nbkg1end:{bkg1end}\nbkg2start:{bkg2start}\nbkg2end:{bkg2end}\n# \n# Transient location in decimal degrees\n# Set auto:True if search is to be centered on spacecraft pointing\nauto:{auto}\nra:{ra:0.2f} ; Ignored if auto=True\ndec:{dec:0.2f} ; Ignored if auto=True\n# \n# Transient search radius (degrees) and approximate resolution (degrees)\nradius:{radius:0.2f}\nresolution:{resolution:0.2f}\n# actual resolution is the nearest healpix resolution available\n# Some of the supported values are 7.33, 3.66, 1.83, 0.92, 0.46, 0.23, 0.11\n# ANY value is allowed, the closest supported value will actually be used\n#\n#------------------------------------------------------------------------\n# Generic configuration parameters\n#\n# Grouping pixels: group n x n pixels into a \"superpixel\"\n# May be 1, 2, 4, 8, 16\npixsize:{pixsize}\n#\n# Use fitting for calculating resposnse, or just scale?\n# If True, best-fit \"flux\" is calculated for image = background + flux * source\n# If False, \"flux\" is simply (np.sum(source_image) - np.sum(bkg_image)) / np.sum(response)\ndo_fit:True\n#\n# Codes for calculating responses, and theta_x, theta_y from ra,dec\n# Must be executable\nrespcode:{respcode}\ntxycode:{txycode}\n#\n# Location of response files\nresppath:{resppath}\n#\n# Output plot pdf path\nplotfile:{plotfile}\n# \n# Give verbose output: True / False\nverbose:{verbose}\n\"\"\".format(**printdict)\n if filename is not None:\n with open(filename, 'w') as thefile:\n thefile.write(configuration)\n else:\n print configuration",
"def create_config():\n check_config()\n\n cprint(\"%sWriting python executable to %s\" % (OUT_PRFX, PYWS_DIR_BIN), OUT_STD_COLOR)\n fs.write(\"%s/python\" % PYWS_DIR_BIN, \"#! /usr/bin/python\\nimport novenv\\nnovenv.python()\")\n fs.chmod(\"%s/python\" % PYWS_DIR_BIN, stat.S_IEXEC)\n\n cprint(\"%sWriting python3 executable to %s\" % (OUT_PRFX, PYWS_DIR_BIN), OUT_STD_COLOR)\n fs.write(\"%s/python3\" % PYWS_DIR_BIN, \"#! /usr/bin/python\\nimport novenv\\nnovenv.python(version=3)\")\n fs.chmod(\"%s/python3\" % PYWS_DIR_BIN, stat.S_IEXEC)\n \n cprint(\"%sWriting pip executable to %s\" % (OUT_PRFX, PYWS_DIR_BIN), OUT_STD_COLOR)\n fs.write(\"%s/pip\" % PYWS_DIR_BIN, \"#! /usr/bin/python\\nimport novenv\\nnovenv.pip()\")\n fs.chmod(\"%s/pip\" % PYWS_DIR_BIN, stat.S_IEXEC)\n\n cprint(\"%sWriting pip3 executable to %s\" % (OUT_PRFX, PYWS_DIR_BIN), OUT_STD_COLOR)\n fs.write(\"%s/pip3\" % PYWS_DIR_BIN, \"#! /usr/bin/python\\nimport novenv\\nnovenv.pip(version=3)\")\n fs.chmod(\"%s/pip3\" % PYWS_DIR_BIN, stat.S_IEXEC)\n\n cprint(\"%sPlease add the %s directory to your path\" % (OUT_PRFX, PYWS_DIR_BIN), OUT_CMD_COLOR)\n cprint(\"%sexport PATH=/home/ckoerner/%s/bin:$PATH\" % (OUT_PRFX_VERBOSE, VENV_DIR), OUT_CMD_COLOR)\n\n cprint(\"%sCheck current python executable with\" % (OUT_PRFX), OUT_CMD_COLOR)\n cprint(\"%swhich python\" % (OUT_PRFX_VERBOSE), OUT_CMD_COLOR)",
"def generateConfig(run,subrun,conditions):\n \n configname = (conditions.numcdir + \"/\" + str(run) + \"/\" + str(subrun)\n + \"/numc_config_\" + str(run) + \"_\" + str(subrun) + \".cfg\")\n \n configContents = \"\"\n \n configContents += \"[software]\\n\"\n if conditions.oldneut:\n configContents += \"neut_setup_script = /project/t/tanaka/T2K/neut/branches/5.1.4.2_nd280_ROOTv5r34p09n01/src/neutgeom/setup.sh\\n\"\n elif conditions.newoldneut:\n configContents += \"neut_setup_script = /project/t/tanaka/T2K/neut/branches/5.1.4.3_nd280/src/neutgeom/setup.sh\\n\"\n else:\n #configContents += \"neut_setup_script = /project/t/tanaka/T2K/neut/branches/5.3.1_nd280/src/neutgeom/setup.sh\\n\"\n #configContents += \"neut_setup_script = /project/t/tanaka/T2K/neut/branches/5.3.1_nd280_wBBBA05/src/neutgeom/setup.sh\\n\"\n configContents += \"neut_setup_script = /project/t/tanaka/T2K/neut/branches/5.3.2_nd280/src/neutgeom/setup.sh\\n\"\n \n configContents += \"[geometry]\\n\"\n\n configContents += \"baseline = \" + conditions.geometry +\"\\n\"\n if conditions.waterair == \"water\":\n configContents += \"p0d_water_fill = 1\\n\"\n else:\n configContents += \"p0d_water_fill = 0\\n\"\n \n configContents += \"\"\"\n \n[configuration]\nmodule_list = neutMC\n\n[filenaming]\n\"\"\"\n configContents += \"comment = \" + conditions.comment + \"\\n\"\n configContents += \"run_number = \" + str(run) +\"\\n\"\n configContents += \"subrun = \" + str(subrun) + \"\\n\"\n\n if conditions.oldneut:\n configContents += \"\"\" \n\n[neutrino]\nneut_card = /project/t/tanaka/T2K/neut/branches/5.1.4.2_nd280_ROOTv5r34p09n01/src/neutgeom/neut.card\n\"\"\"\n elif conditions.newoldneut:\n configContents += \"\"\" \n\n[neutrino]\nneut_card = /project/t/tanaka/T2K/neut/branches/5.1.4.3_nd280/src/neutgeom/neut.card\n\"\"\"\n else:\n configContents += \"\"\" \n\n[neutrino]\nneut_card = /project/t/tanaka/T2K/neut/branches/5.3.2_nd280/src/neutgeom/neut.card\n\"\"\"\n\n configContents += \"flux_file = \" + conditions.ram_disk + \"/\" + conditions.flux_base + \"\\n\"\n\n#flux_file = flux_file\n#\"\"\"\n\n# configContents += \"flux_file_path = \" + conditions.ram_disk + \"/\" + conditions.flux_base\n\n# configContents += \"\"\" \n#flux_file_start = 1\n#flux_file_stop = 300\n#\"\"\"\n\n configContents += \"maxint_file = \" + conditions.maxint_file_local + \"\\n\"\n\n# default: 5e17 but for basket MC special production higher\n configContents += \"\"\" \npot = 5.0e17\nneutrino_type = beam\n\"\"\"\n if conditions.baskmagn == \"basket\":\n configContents += \"\"\" \nflux_region = basket\nmaster_volume = Basket \nrandom_start = 1\n\"\"\"\n elif conditions.baskmagn == \"magnet\":\n configContents += \"\"\" \nflux_region = magnet\nmaster_volume = Magnet \nrandom_start = 1\n\"\"\"\n else:\n print \"Unknown basket/magnet condition\"\n \n\n configContents += \"random_seed = \" + str(getRandom()) +\"\\n\"\n configContents += \"neut_seed1 = \" + str(getRandom())+\"\\n\" \n configContents += \"neut_seed2 = \" + str(getRandom())+\"\\n\" \n configContents += \"neut_seed3 = \" + str(getRandom())+\"\\n\" \n\n configContents += \"\\n\"\n configContents += \"[nd280mc]\\n\"\n configContents += \"mc_type=Neut_RooTracker \\n\"\n\n #print configContents\n\n try:\n macFile = open(configname,\"w\")\n macFile.write(configContents)\n \n except:\n print \"can't write config file\" \n \n\n return configname",
"def generate_config_template():\n lines = ['# Lines starting with # will be skipped.']\n lines.append('# Only one argument on each line.')\n lines.append('#-s This option is always assumed to be true.')\n lines.append('#-p')\n lines.append('#-m')\n lines.append('#-o')\n lines.append('#-c')\n lines.append('-l')\n lines.append('#-a')\n lines.append('#-d')\n\n with open('export_config.txt', 'wb') as f_new:\n f_new.write('\\r\\n'.join(lines))\n print 'Template generated. Edit this file as you please and call this script '\\\n 'with the -f option enabled.'",
"def createConfig():\n\twith open(configPath, 'w', encoding='utf-8') as file:\n\t\tjson.dump(default_config, file, indent=3)",
"def export_configurations():\n pass",
"def generate_config(self):\n\n cfgmgr = ConfigManager()\n\n script_dir = os.path.join(cfgmgr.getRoot(), 'rules')\n\n if not os.path.exists(script_dir):\n print('Creating rules directory \\\"{0}\\\"'.format(script_dir))\n\n os.makedirs(script_dir)\n else:\n if not self.getArgs().force:\n sys.stderr.write('Script directory \\\"{0}\\\" already exists.\\n'\n 'Use --force to overwrite current'\n ' scripts\\n'.format(script_dir))\n\n sys.exit(1)\n\n print('Overwriting any scripts in directory \\\"{0}\\\"'.format(\n script_dir))\n\n # Determine UGE cell directory from environment\n if not os.getenv('SGE_ROOT') or not os.getenv('SGE_CELL'):\n print('Error: UGE environment is not sourced', file=sys.stderr)\n\n sys.exit(1)\n\n cell_dir = os.path.join(os.getenv('SGE_ROOT'), os.getenv('SGE_CELL'))\n\n template_vars = {\n 'tortuga_root': cfgmgr.getRoot(),\n 'uge_cell_dir': cell_dir,\n 'script_dir': script_dir,\n 'burst_swprofile': self.getArgs().software_profile,\n 'burst_hwprofile': self.getArgs().hardware_profile,\n 'burst_queue': 'burst.q',\n 'polling_interval': self.getArgs().polling_interval,\n 'slots_per_host': self.getArgs().slots_per_host,\n }\n\n env = Environment(loader=FileSystemLoader('templates'),\n undefined=StrictUndefined)\n\n for filename in glob.glob('templates/*.j2'):\n# print('Processing template {0}'.format(\n# os.path.basename(filename)))\n\n template = env.get_template(os.path.basename(filename))\n\n dstfile = os.path.join(\n script_dir,\n os.path.splitext(os.path.basename(filename))[0])\n\n print(' - writing {0}'.format(os.path.basename(dstfile)))\n\n with open(dstfile, 'w') as outfp:\n template.stream(template_vars).dump(outfp)",
"def _createConfigFile(self):\n configFile = self._configFile()\n try:\n with open(configFile) as fh:\n pass\n except IOError:\n try:\n with open(configFile, 'w') as fh:\n fh.write(\"[settings]\\n\")\n fh.write(\"debug = false\\n\")\n fh.write(\"hidefilenames = false\\n\")\n except IOError:\n pass",
"def setup_configuration_file(self):\n\n with open(self.config_path, \"w+\") as f_config:\n\n f_config.write(get_configuration_file_form())",
"def configuration():",
"def create_config():\n config = configparser.ConfigParser()\n section = 'Settings'\n config.add_section(section)\n config.set(section, 'font', 'Courier')\n config.set(section, 'font_size', '10')\n config.set(section, 'font_style', 'normal')\n # Interpolation\n config.set(section, 'font_info', \"You are using %(font)s at %(font_size)s pt\")\n\n with open(path, 'w') as config_file:\n config.write(config_file)",
"def create_settings_file():\n with open('./cfg/settings.cfg'.replace(\"/\", os.path.sep), 'w') as cfg:\n cfg.write('[report]\\nlogo = ./cfg/logo.png\\ncompany =\\nrecord =\\nunit =\\nexaminer =\\nnotes =\\n\\n[auth]\\ngmail = [email protected]\\npassw = yourpassword\\ndevid = 1234567887654321\\ncelnumbr = BackupPhoneNunmber\\n\\n[app]\\npkg = com.whatsapp\\nsig = 38a0f7d505fe18fec64fbf343ecaaaf310dbd799\\n\\n[client]\\npkg = com.google.android.gms\\nsig = 38918a453d07199354f8b19af05ec6562ced5788\\nver = 9877000'.replace(\"/\", os.path.sep))",
"def _make_cfg_file(self, **kwargs) -> Path:\n\n # Update times\n model_start = get_time(self.forcing.start_time)\n model_end = get_time(self.forcing.end_time)\n if \"start_time\" in kwargs:\n start = get_time(kwargs[\"start_time\"])\n if (\n get_time(self.forcing.start_time)\n <= start\n <= get_time(self.forcing.end_time)\n ):\n model_start = start\n else:\n raise ValueError(\"start_time outside forcing time range\")\n if \"end_time\" in kwargs:\n end = get_time(kwargs[\"end_time\"])\n if (\n get_time(self.forcing.start_time)\n <= end\n <= get_time(self.forcing.end_time)\n ):\n model_end = end\n else:\n raise ValueError(\"end_time outside forcing time range\")\n\n settings = {\n \"CalendarDayStart\": model_start.strftime(\"%d/%m/%Y 00:00\"),\n \"StepStart\": \"1\",\n \"StepEnd\": str((model_end - model_start).days),\n \"PathRoot\": str(self.parameter_set.directory),\n \"PathMeteo\": str(self.forcing.directory),\n \"PathOut\": str(self._cfg_dir),\n }\n\n if \"IrrigationEfficiency\" in kwargs:\n settings[\"IrrigationEfficiency\"] = kwargs[\"IrrigationEfficiency\"]\n\n if \"MaskMap\" in kwargs:\n mask_map = to_absolute_path(input_path=kwargs[\"MaskMap\"])\n settings[\"MaskMap\"] = str(mask_map.with_suffix(\"\"))\n try:\n mask_map.relative_to(self.parameter_set.directory)\n except ValueError:\n # If not relative add dir\n self._additional_input_dirs.append(str(mask_map.parent))\n\n for textvar in self._config.config.iter(\"textvar\"):\n textvar_name = textvar.attrib[\"name\"]\n\n # general settings\n for key, value in settings.items():\n if key in textvar_name:\n textvar.set(\"value\", value)\n\n # input for lisflood\n if \"PrefixPrecipitation\" in textvar_name:\n textvar.set(\"value\", Path(self.forcing.PrefixPrecipitation).stem)\n if \"PrefixTavg\" in textvar_name:\n textvar.set(\"value\", Path(self.forcing.PrefixTavg).stem)\n\n # maps_prefixes dictionary contains lisvap filenames in lisflood config\n maps_prefixes = {\n \"E0Maps\": {\n \"name\": \"PrefixE0\",\n \"value\": Path(self.forcing.PrefixE0).stem,\n },\n \"ES0Maps\": {\n \"name\": \"PrefixES0\",\n \"value\": Path(self.forcing.PrefixES0).stem,\n },\n \"ET0Maps\": {\n \"name\": \"PrefixET0\",\n \"value\": Path(self.forcing.PrefixET0).stem,\n },\n }\n # output of lisvap\n for map_var, prefix in maps_prefixes.items():\n if prefix[\"name\"] in textvar_name:\n textvar.set(\"value\", prefix[\"value\"])\n if map_var in textvar_name:\n textvar.set(\"value\", f\"$(PathMeteo)/$({prefix['name']})\")\n\n # Write to new setting file\n lisflood_file = self._cfg_dir / \"lisflood_setting.xml\"\n self._config.save(str(lisflood_file))\n return lisflood_file",
"def createConfiguration(self, input):\n resolvedInputName = envString.resolve(input)\n if self.opts.verbose:\n print(\"creating configuration using \", resolvedInputName)\n template = TemplateWriter()\n substitutes = self.defaults.copy()\n for key in self.commandLineDefaults:\n val = self.commandLineDefaults[key]\n if val is not None:\n substitutes[key] = self.commandLineDefaults[key]\n\n substitutes[\"CTRL_EXECUTE_SETUP_PACKAGES\"] = self.getSetupPackages()\n\n configDir = os.path.join(substitutes[\"LOCAL_SCRATCH\"], \"configs\")\n if not os.path.exists(configDir):\n os.mkdir(configDir)\n self.outputFileName = os.path.join(configDir, \"%s.config\" % (self.runid))\n if self.opts.verbose:\n print(\"writing new configuration to \", self.outputFileName)\n template.rewrite(resolvedInputName, self.outputFileName, substitutes)\n return self.outputFileName",
"def create_config_file():\n working_dir = get_working_dir()\n with open('config.txt', 'w') as config_file:\n config_file.write(working_dir + os.sep + 'LevelProgress.xlsx')",
"def create_configfile():\n config = ConfigParser.ConfigParser()\n config.add_section('Common')\n config.set('Common', 'renewal days', 20)\n config.set('Common', 'delayed installation days', 5)\n config.set('Common', 'include chain', True)\n config.set('Common', 'account key', './config/key.pem')\n config.add_section('Load Balancer')\n config.set('Load Balancer', 'cluster', True)\n config.set('Load Balancer', 'Host 1', 'lb1.example.com')\n config.set('Load Balancer', 'Host 2', 'lb2.example.com')\n config.set('Load Balancer', 'username', 'admin')\n config.set('Load Balancer', 'password', 'password01')\n config.set('Load Balancer', 'datagroup', 'acme_responses_dg')\n config.set('Load Balancer', 'datagroup partition', 'Common')\n config.add_section('Certificate Authority')\n config.set('Certificate Authority', 'Directory URL',\n 'https://acme-v01.api.letsencrypt.org/directory')\n config.set('Certificate Authority', 'use proxy', False)\n config.set('Certificate Authority', 'proxy',\n 'http://proxy.example.com:8080')\n\n # As the config file contains password, we should be careful with permissions\n with os.fdopen(os.open(CONFIG_FILE, os.O_WRONLY | os.O_CREAT, 0o660), 'w') as config_file:\n config.write(config_file)",
"def config():",
"def config():",
"def __writeConfig(self):\n page = None\n\n #TODO: get values of configurations here\n particles = \"#f\" if not base.particleMgrEnabled else \"#t\"\n volume = str(round(base.musicManager.getVolume(), 2))\n mute = \"#f\" if base.AppHasAudioFocus else \"#t\"\n #TODO: add any configuration variable name that you have added\n customConfigVariables = [\n \"\", \"particles-enabled\", \"audio-mute\", \"audio-volume\"]\n if os.path.exists(prcFile):\n # open the config file and change values according to current\n # application settings\n page = loadPrcFile(Filename.fromOsSpecific(prcFile))\n removeDecls = []\n for dec in range(page.getNumDeclarations()):\n # Check if our variables are given.\n # NOTE: This check has to be done to not loose our base or other\n # manual config changes by the user\n if page.getVariableName(dec) in customConfigVariables:\n decl = page.modifyDeclaration(dec)\n removeDecls.append(decl)\n for dec in removeDecls:\n page.deleteDeclaration(dec)\n # NOTE: particles-enabled and audio-mute are custom variables and\n # have to be loaded by hand at startup\n # Particles\n page.makeDeclaration(\"particles-enabled\", particles)\n # audio\n page.makeDeclaration(\"audio-volume\", volume)\n page.makeDeclaration(\"audio-mute\", mute)\n else:\n # Create a config file and set default values\n cpMgr = ConfigPageManager.getGlobalPtr()\n page = cpMgr.makeExplicitPage(\"%s Pandaconfig\"%appName)\n # set OpenGL to be the default\n page.makeDeclaration(\"load-display\", \"pandagl\")\n # get the displays width and height\n w = self.pipe.getDisplayWidth()\n h = self.pipe.getDisplayHeight()\n # set the window size in the config file\n page.makeDeclaration(\"win-size\", \"%d %d\"%(w, h))\n # set the default to fullscreen in the config file\n page.makeDeclaration(\"fullscreen\", \"1\")\n # particles\n page.makeDeclaration(\"particles-enabled\", \"#t\")\n # audio\n page.makeDeclaration(\"audio-volume\", volume)\n page.makeDeclaration(\"audio-mute\", \"#f\")\n # create a stream to the specified config file\n configfile = OFileStream(prcFile)\n # and now write it out\n page.write(configfile)\n # close the stream\n configfile.close()",
"def make_config(config, out_dir=None, pism_root=pism_root):\n\n # ensure that config is a list\n if type(config) is str:\n config = [config]\n\n # initialize netCDF dataset\n nc_path = os.path.join(out_dir, 'config.nc')\n nc = Dataset(nc_path, 'w')\n var = nc.createVariable('pism_overrides', 'i1')\n\n # loop on config files\n for c in config:\n c_path = '%s/config/%s.txt' % (pism_root, c)\n\n # fill in pism overrides\n with open(c_path) as f:\n for line in f:\n\n # ignore what follows '//'\n line = line.split('//', 1)[0].strip()\n\n # parse non-empty lines and overwrite existing values\n if line:\n k, v = line.split(':', 1)\n k = k.strip()\n v = v.strip().strip('\"')\n try:\n v = float(v)\n except ValueError:\n pass\n var.setncattr(k, v)\n\n # close and return path to output file\n nc.close()\n return nc_path",
"def create_config_file(name):\n config = {}\n config['name'] = name\n to_dir = os.getcwd() + '/' + name\n with open(os.path.join(to_dir, 'configuration.json'), 'w') as config_file:\n json.dump(config, config_file)"
] | [
"0.66401374",
"0.66170925",
"0.66152537",
"0.65990126",
"0.656565",
"0.656565",
"0.64811194",
"0.64493716",
"0.64300835",
"0.6417359",
"0.64147276",
"0.6409965",
"0.6381156",
"0.63435024",
"0.6338197",
"0.6330227",
"0.62982994",
"0.6296114",
"0.6284715",
"0.62806594",
"0.6273481",
"0.62647456",
"0.6245572",
"0.622836",
"0.6214249",
"0.6213469",
"0.6213469",
"0.6191291",
"0.61834836",
"0.61757094"
] | 0.67666286 | 0 |
Controller is allow user to change their password if they have valid username and password. It will generate the new password hash and write into the database. If username not exist, or wrong password, controller will not allow user change password. | def change_my_password():
form = ChangePassword()
if request.method == 'GET':
return render_template('changemypassword.html', form=form)
if request.method == 'POST' and form.validate_on_submit():
username = form.username.data
old_password = form.password.data
new_password_hash = generate_password_hash(form.password1.data)
account = db.check_item("username", username)
if account is not None:
if check_password_hash(str(account['password_hash']), old_password):
db.update_password_username(username, new_password_hash)
flash('Your password has been changed')
return redirect(url_for('login'))
else:
flash('Invalid username or password')
return redirect(url_for('change_my_password'))
else:
flash('Invalid username or password')
return redirect(url_for('change_my_password'))
else:
return render_template('changemypassword.html', form=form) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def changepassword():\n if request.method == \"POST\":\n\n # Ensure password was submitted\n if not request.form.get(\"newpassword\"):\n return apology(\"must provide password\", 400)\n # Ensure passwords match\n elif request.form.get(\"newpassword\") != request.form.get(\"confirmation\"):\n return apology(\"passwords do not match\", 400)\n elif request.form.get(\"newpassword\").isalpha() == True:\n return apology(\"password must contain at least one numeric symbol\")\n\n # encrypt new password\n hash = generate_password_hash(request.form.get(\"newpassword\"))\n print(hash)\n # update user's password in database\n result = db.execute(\"UPDATE users SET hash = :hash WHERE id = :id\", hash=hash, id = session[\"user_id\"])\n\n if not result:\n return apology(\"password not available\", 400)\n\n # Redirect user to home page\n return redirect(\"/\")\n\n # User reached route via GET (as by clicking a link or via redirect)\n else:\n return render_template(\"changepass.html\")",
"def updatepassword():\n if request.method == \"POST\":\n\n password = request.form.get(\"password\")\n password2 = request.form.get(\"confirmation\")\n\n if not password:\n return apology(\"must provide password\", 400)\n\n elif not (password == password2):\n return apology(\"passwords must match\", 400)\n\n elif not password2:\n return apology(\"must confirm password\", 400)\n\n rows = db.execute(\n \"SELECT password FROM users WHERE id = ?\", (session_get_int(\"user_id\"), )).fetchall()\n\n if (check_password_hash(rows[0][\"password\"], password)):\n return apology(\"password cannot be the same as existing password\", 400)\n\n else:\n db.execute(\"UPDATE users SET password = ? WHERE id = ?\",\n (generate_password_hash(password), session_get_int(\"user_id\")))\n con.commit()\n\n return redirect(\"/profile\")\n else:\n return redirect(\"/profile\")",
"def password():\n\n if request.method == 'POST':\n print 'Changing password'\n # query for user's hash of password\n pw_hash = datastore.get_user_by_user_id(engine, session['user_id'])['hash']\n\n # check all boxes filled, old password is correct, new and confirmation match\n if not request.form.get('old') or not check_password_hash(pw_hash, request.form.get('old')):\n flash('Incorrect old password!', 'danger')\n return render_template('password.html')\n elif not request.form.get('new') or not request.form.get('confirmation'):\n flash('Must confirm new password!', 'danger')\n return render_template('password.html')\n elif not request.form.get('new') == request.form.get('confirmation'):\n flash('New passwords don\\'t match!', 'danger')\n return render_template('password.html')\n\n # update hash in database\n datastore.update_password_hash(engine, session['user_id'], generate_password_hash(request.form.get('new')))\n\n # redirect to portfolio\n flash('Password changed!', 'info')\n print 'Password changed!'\n return redirect(url_for('index'))\n\n else:\n print 'Loading change password page'\n return render_template('password.html')",
"def change_password():\n\n if request.method == \"POST\":\n\n # Ensure current password is not empty\n if not request.form.get(\"current_password\"):\n return apology(\"must provide current password\", 400)\n\n # Query database for user_id\n rows = db.execute(\"SELECT hash FROM users WHERE id = :user_id\", user_id=session[\"user_id\"])\n\n # Ensure current password is correct\n if len(rows) != 1 or not check_password_hash(rows[0][\"hash\"], request.form.get(\"current_password\")):\n return apology(\"invalid password\", 400)\n\n # Ensure new password is not empty\n if not request.form.get(\"new_password\"):\n return apology(\"must provide new password\", 400)\n\n # Ensure new password confirmation is not empty\n elif not request.form.get(\"new_password_confirmation\"):\n return apology(\"must provide new password confirmation\", 400)\n\n # Ensure new password and confirmation match\n elif request.form.get(\"new_password\") != request.form.get(\"new_password_confirmation\"):\n return apology(\"new password and confirmation must match\", 400)\n\n # Update database\n hash = generate_password_hash(request.form.get(\"new_password\"))\n rows = db.execute(\"UPDATE users SET hash = :hash WHERE id = :user_id\", user_id=session[\"user_id\"], hash=hash)\n\n # Show flash\n flash(\"Password Changed!\")\n return redirect(\"/\")\n\n return render_template(\"change_password.html\")",
"def change_password_user():\n\n form = ChangePasswordForm(request.form)\n\n if form.validate_on_submit():\n\n if not request.form['old_password'] or request.form['old_password'] == '' :\n flash(\"No null or empty values are allowed.\",\"warn\")\n return render_template('user/change_password_user.html', title='Change Password', form=form)\n\n if not request.form['password'] or request.form['password'] == '' :\n flash(\"No null or empty values are allowed.\",\"warn\")\n return render_template('user/change_password_user.html', title='Change Password', form=form)\n\n if request.form['password'] != request.form['retype_password']:\n flash(\"Passwords are not the same!\",\"warn\")\n return render_template('user/change_password_user.html', title='Change Password', form=form)\n\n\n hashed_password = user_manager.hash_password(request.form['password'])\n\n # Modificamos el password del usuario\n current_user.password = hashed_password\n\n try:\n correct = True\n db.session.commit()\n except Exception as e:\n # Catch anything unknown\n print(e)\n correct = False\n finally:\n if not correct:\n # Cleanup and show error\n db.session.rollback()\n flash('Error modifying password of user, make sure username and email are unique','error')\n return render_template('user/change_password_user.html', title='Change Password', form=form)\n else:\n flash('Congratulations, update your password!','success')\n return redirect(url_for('user_ksat.show_user'))\n\n\n return render_template('user/change_password_user.html', title='Change Password', form=form)",
"def password():\n\n # User reached route via POST\n if request.method == 'POST':\n\n # Ensure passwords that were submitted\n if not request.form.get('password'):\n return apology('must provide password', 400)\n\n elif not request.form.get('new_password') or not request.form.get('confirmation'):\n return apology('must provide a new password', 400)\n\n elif request.form.get('new_password') != request.form.get('confirmation'):\n return apology(\"passwords doesn't match\")\n\n user = db.execute('SELECT * FROM users WHERE id = :id', id=session['user_id'])\n\n # Ensure username exists and password is correct\n if len(user) != 1 or not check_password_hash(user[0]['hash'], request.form.get('password')):\n return apology('invalid username and/or password', 400)\n\n db.execute('UPDATE users SET hash = :hash WHERE id = :id',\n hash=generate_password_hash(request.form.get('new_password')),\n id=session['user_id']\n )\n\n return redirect('/logout')\n else:\n return render_template('password.html')",
"def change_password():\n\n from .forms import ChangeCredentialsForm\n\n username = current_user.get_id()\n form = ChangeCredentialsForm(request.form)\n\n if form.validate_on_submit():\n logger.info(username + \" wants to change something.\")\n if request.form['username'] != username:\n logger.info(\"User \" + username + \" wants to change the username.\")\n app.rename_user(username, request.form['username'],\n request.form['newPassword1'])\n else:\n logger.info(\"Changing password of user \" + username + \".\")\n app.add_user_and_password(request.form['username'],\n request.form['newPassword1'])\n\n logger.info(\"Successfully changed credentials of \"\n + username + '.')\n return redirect(url_for('home'))\n\n else:\n return render_template('change-credentials.html',\n form=form,\n username=username)",
"def changepassword():\n try:\n if request.method == 'POST':\n # Makes sure the passwords match and that it meets complexity\n validate = check_pass(\n request.form['newpass'], request.form['connewpass'])\n if validate == \"Passed\":\n data = [request.form['newpass'], session[\n 'username'], request.form['oldpass']]\n with Database() as database:\n database.updateUserPassword(data)\n return redirect(url_for('profile', username=session['username']))\n else:\n flash(validate)\n return render_template('changepass.html')\n\n else:\n return render_template('changepass.html')\n\n except Exception as e:\n flash(\"Oops, something went wrong... Try again.\")\n return render_template('changepass.html')",
"def changePassword():\n\n if request.method == \"GET\":\n\n #Query for the current user that is logged in.\n user = db.execute(\"SELECT username from users WHERE id = :id\", id=session['user_id'])\n\n\n return render_template(\"changePassword.html\", user=user)\n\n if request.method == \"POST\":\n\n #Query for the current user that is logged in and get the hash.\n new_pass = db.execute(\"SELECT username, hash from users WHERE id = :id\", id=session['user_id'])\n\n old_password = request.form.get(\"old_password\")\n password = request.form.get(\"password\")\n confirmation = request.form.get(\"confirmation\")\n\n #Check if the user entered an input\n if not password:\n return apology(\"Please enter a password\", 400)\n if not confirmation:\n return apology(\"Please enter a password confirmation\", 400)\n\n #Check if the password and the confirmation password is the same.\n if password==confirmation:\n hashpw = generate_password_hash(password)\n\n else:\n return apology(\"Password doesn't match\", 400)\n\n #Check if the entered old password is correct.\n if check_password_hash(new_pass[0]['hash'], old_password)==True:\n db.execute(\"UPDATE users SET hash = :hashpw WHERE id = :id\", hashpw=hashpw, id=session['user_id'])\n flash('You successfully changed your password!')\n else:\n return apology (\"Hash doesn't match\", 400)\n\n return redirect (\"/\")",
"def change_Password(): \r\n try:\r\n\r\n UserName=request.args.get(\"UserName\")\r\n validate_otp=request.args.get(\"OTP\") \r\n NewPassword=request.args.get(\"NewPassword\")\r\n hashed_Password = hashlib.md5(NewPassword.encode()).hexdigest() \r\n user_details=otp_access(UserName)\r\n otp=user_details[0]['otp']\r\n with open('api.key', 'r') as apikey:\r\n key=apikey.read().replace('\\n', '')\r\n if request.headers.get('API_KEY') == key:\r\n if str(otp)==str(validate_otp):\r\n msg=update_Password(UserName,hashed_Password)\r\n #This function calling makes the user use OTP until Password gets changed after that validity of OTP will be expired.\r\n new_otp=randint(10000,100000)\r\n # This will checks the new generated OTP and old OTP\r\n if str(otp)==str(new_otp):\r\n new_otp=randint(10000,100000)\r\n update_otp(UserName,new_otp)\r\n else:\r\n update_otp(UserName,new_otp)\r\n else:\r\n msg=\"Something went wrong check the OTP or UserName!!!!\"\r\n else:\r\n msg=\"Enter correct API KEY for Authentication.\"\r\n except IndexError:\r\n msg=f\"{UserName} does not exist , kindly enter correct UserName.\"\r\n return msg",
"def change_user_password():\n session_id = request.args.get('session-id', None)\n user_id = request.args.get('user-id', None)\n user = get_user_by_id(user_id)\n if request.method == 'POST':\n old_password = request.form['old-password']\n new_password = request.form['new-password']\n confirm_password = request.form['confirm-password']\n today = datetime.date.today()\n reservations_list = get_user_reservations_list(user_id)\n cars_reservations_list = get_cars_user_reservations_list(reservations_list)\n reservations_status_list = get_reservations_status_list(reservations_list)\n if check_authentication(session_id, user_id):\n is_password_updated = update_user_password(user_id, old_password, new_password, confirm_password)\n else:\n return render_template('home.html', cars_list=get_cars_preview(), news_list=get_news_list(), authjs=False,\n preview_length=get_cars_preview().__len__(), del_session_cookie=True)\n if is_password_updated == \"OK\":\n return render_template('user_area.html', user=user.id, session_id=session_id, edit_mode=False,\n surname=user.surname, name=user.name, birthdate=user.birthdate,\n feedback_msg=\"Password successfully updated!\", today=today,\n reservations_list=reservations_list, cars_reservations_list=cars_reservations_list,\n reservations_status_list=reservations_status_list)\n else:\n return render_template('user_area.html', user=user.id, session_id=session_id, edit_mode=False,\n surname=user.surname, name=user.name, birthdate=user.birthdate,\n feedback_msg=is_password_updated, today=today,\n reservations_list=reservations_list, cars_reservations_list=cars_reservations_list,\n reservations_status_list=reservations_status_list)",
"def update_password(): \n \n form = PasswordForm()\n if request.method == 'POST':\n if form.validate_on_submit():\n \n hashed_pw = bcrypt.hashpw(form.new_password.data.encode('utf-8'), bcrypt.gensalt())\n user = mongo.db.user.find_one({'username': session['username']})\n \n if bcrypt.checkpw(request.form['password'].encode('utf-8'), user['hashed_password']):\n mongo.db.user.find_one_and_update({'username': session['username']}, {'$set':{'hashed_password':hashed_pw}})\n \n flash(f'Password reset was successful, please login again.','success')\n return redirect(url_for('login'))\n \n return render_template('pages/settings.html', \n title='Password', \n form=form\n )",
"def view_update_user(self, user, new_pw, old_pw):\r\n user.realm._checker.passwd(user.userID, new_pw, old_pw)",
"def update_password(self, username, password): #WORKS\n password_hash = generate_password_hash(password)\n try:\n self.cur.execute(\"UPDATE users SET password = \\\"{}\\\" WHERE username = \\\"{}\\\"\".format(password_hash, username))\n self.db.commit()\n except:\n self.db.rollback()",
"def change_password(username, current_password, new_password):\n\n if current_password == \"\": # nosec (not a hardcoded password)\n current_password = getpass.getpass()\n\n is_password_ok = authenticate_user(username, current_password)\n if not is_password_ok:\n return False\n\n if new_password == \"\": # nosec (not a hardcoded password)\n new_password = getpass.getpass()\n\n global db\n if db is None:\n init_db()\n user_model = Query()\n user = db.search(user_model.username == username)[0]\n\n salt = user['salt']\n password = hash_password(new_password, salt)\n api_key = gen_api_key(username)\n\n user_id = db.update({'password': password, 'api_key': api_key}, doc_ids=[user.doc_id])\n\n return {\n 'result': 'success',\n 'eid': user_id,\n 'user_created': user,\n 'api_key': api_key\n }",
"def change_password():\n\n if request.method == 'POST':\n current_password = request.form['current_password']\n new_password = request.form['new_password']\n\n # If current password is correct, update and store the new hash\n if current_user.check_password_hash(current_password):\n current_user.generate_password_hash(new_password)\n else:\n return 'Current password you entered is wrong! Please try again!'\n\n # Commit the changes we made in the object to the database\n success, reason = commit_transaction()\n if not success:\n return f'Error occurred while changing your password - {reason}!'\n\n log(f'<code>{current_user.name}</code> has updated their password!</code>')\n\n # Log the user out, and redirect to login page\n logout_user()\n return redirect(url_for('login'))\n return render_template('change_password.html')",
"def change_password(self):\n self.test_user.set_password(self.create_user_data()['password1'])\n self.test_user.save()",
"def change_user():\n _ = db.change_password(auth.username(), generate_password_hash(request.json['password']))\n return str(_)",
"def testEditPassword(self):\n self._login_user('eschoppik','secret')\n response = self.client.post('/users/1/edit_password?_method=PATCH',\n data=dict(new_password='newpass', confirm_password='newpass',\n old_password='secret'), follow_redirects=True)\n user = User.query.filter_by(username='eschoppik').first()\n self.assertEqual(response.status_code, 200)\n self.assertEqual(bcrypt.check_password_hash(user.password, 'newpass'),True)",
"def updateWebAppUserPwd( self, username, password ):\n try:\n crypt_pass = crypt(password, username)\n con = self.getMetadataDatabaseConnection()\n user_data = con.cursor()\n con.cursor().callproc('update_web_app_user_password', [username, crypt_pass])\n except Exception, e:\n print 'Exception caught: %s.\\nThe error is: %s' % (type(e), e)\n return False",
"def set_password(self, request, pk=None):\n user = User.objects.get(id=pk)\n serializer = PasswordSerializer(data=request.data)\n\n if serializer.is_valid():\n if not user.check_password(serializer.data.get('old_password')):\n return Response({'old_password': ['Wrong password.']},\n status=status.HTTP_400_BAD_REQUEST)\n # set_password also hashes the password that the user will get\n user.set_password(serializer.data.get('new_password'))\n user.save()\n return Response({'status': 'password set'}, status=status.HTTP_200_OK)\n\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)",
"def put_password():\n # pylint: disable=too-many-branches\n\n # get user\n user = g.user\n\n # prep regex\n re_password = re.compile(AdministratorAdminSchema.re_password)\n\n # validate data\n errors = {}\n if ('previous_password' not in request.json or\n not request.json['previous_password']):\n if 'previous_password' not in errors:\n errors['previous_password'] = []\n errors['previous_password'].append(\"Missing data for required field.\")\n elif ('previous_password' in request.json and\n not user.check_password(request.json['previous_password'])):\n if 'previous_password' not in errors:\n errors['previous_password'] = []\n errors['previous_password'].append(\"Incorrect password.\")\n\n if 'password1' not in request.json or not request.json['password1']:\n if 'password1' not in errors:\n errors['password1'] = []\n errors['password1'].append(\"Missing data for required field.\")\n if ('password1' in request.json and\n not re_password.match(request.json['password1'])):\n if 'password1' not in errors:\n errors['password1'] = []\n errors['password1'].append(\"Please choose a more complex password.\")\n\n if 'password2' not in request.json or not request.json['password2']:\n if 'password2' not in errors:\n errors['password2'] = []\n errors['password2'].append(\"Missing data for required field.\")\n if 'password1' in request.json and 'password2' in request.json:\n if request.json['password1'] != request.json['password2']:\n if 'password2' not in errors:\n errors['password2'] = []\n errors['password2'].append(\"New passwords must match.\")\n\n if errors:\n return jsonify({\"error\": errors}), 400\n\n # check previous passwords\n if user.roles[0].password_policy and user.roles[0].password_reuse_history:\n prev_passwords = AdministratorPasswordHistory.query.\\\n filter(AdministratorPasswordHistory.administrator_id == user.id).\\\n order_by(AdministratorPasswordHistory.set_date.desc()).\\\n limit(user.roles[0].password_reuse_history)\n for record in prev_passwords:\n print(\"TEST \", record.password)\n if bcrypt.checkpw(request.json.get('password1').encode('utf-8'),\n record.password.encode('utf-8')):\n errors['password1'] = [\"This password has recently been used.\"]\n break\n\n if errors:\n return jsonify({\"error\": errors}), 400\n\n # save user and password history\n user.password = request.json.get('password1')\n pass_history = AdministratorPasswordHistory(administrator=user,\n password=user.password,\n set_date=datetime.now())\n db.session.add(pass_history)\n db.session.commit()\n\n # response\n return jsonify({'success': 'true'}), 200",
"def view_update_user(self, user, username, password):\r\n user.realm._checker.passwd(username, password, True)",
"def set_password(username, new_password):\n if not validate_password(new_password):\n return \"salasana on väärää muotoa\"\n new_password_hash = generate_password_hash(new_password)\n sql = \"UPDATE users \" \\\n \"SET password=:new_pw \" \\\n \"WHERE username=:username\"\n db.session.execute(sql, {\"new_pw\": new_password_hash, \"username\": username})\n db.session.commit()\n return \"ok\"",
"def change_password(self, request, **kwargs):\n self.method_check(request, allowed=['post'])\n self.throttle_check(request)\n\n data = json.loads(request.body)\n\n username = None\n old_password = None\n new_password = None\n\n if \"username\" in data:\n username = data[\"username\"]\n print username\n else:\n if \"email\" in data:\n username = data[\"email\"]\n else:\n BadRequest(INVALID_PARAMS)\n\n if \"old_password\" in data:\n old_password = data[\"old_password\"]\n else:\n BadRequest(INVALID_PARAMS)\n\n if \"new_password\" in data:\n new_password = data[\"new_password\"]\n else:\n BadRequest(INVALID_PARAMS)\n\n if (old_password is not None and new_password is not None and\n username is not None):\n member = authenticate(username=username, password=old_password)\n\n if member is not None:\n member.set_password(new_password)\n member.save()\n return self.create_response(request, {})",
"def ChangePassword(self):\n \n username = self.username.get().lstrip().rstrip()\n if not username:\n messagebox.showerror('Error', 'No username entered.')\n return False\n \n if not self.PasswordMatch():\n messagebox.showerror('Error', 'Password fields do not match.')\n return False\n password = self.password.get().lstrip().rstrip()\n \n for user in self.user_db:\n if user['User'] == username:\n if user['Password'] == password:\n messagebox.showerror('Error',\n 'New password unchanged from the ' \\\n 'old password.')\n return False\n user['Password'] = password\n messagebox.showinfo('Success!', 'Password updated!')\n return True\n \n messagebox.showerror('Error', f'{username} not found in database.')\n return False",
"async def user_change_password(\n form: ChangePasswordRequest,\n db: Session = Depends(db_session)):\n token: AccessToken = find_ot_access_token(db, form.token)\n if not token:\n return {\"success\": False, \"msg\": \"Token was not found\"}\n\n token.user.hashed_password = PWD_CONTEXT.hash(form.password)\n db.delete(token)\n db.commit()\n return {\"success\": True}",
"def save_model(self, request, obj, form, change):\n if change:\n obj.save()\n else:\n obj.set_password(obj.password)\n obj.save()",
"def change_password():\n if request.method == \"POST\":\n error = None\n if \"username\" in session:\n username = session[\"username\"]\n old_password = request.form[\"old_password\"]\n new_password1 = request.form[\"new_password1\"]\n new_password2 = request.form[\"new_password2\"]\n\n error = change_password_tests(new_password1, new_password2)\n\n if not is_valid_login(username, old_password):\n error = \"Incorrect old password\"\n\n if error:\n flash(error)\n else:\n with open(PASSFILE, \"r\") as passfile, open(TEMPFILE, \"a\") as tempfile:\n for record in passfile:\n try:\n r_username, r_salt_hash = record.split()\n\n # same_username & same_password exist to\n # avoid the linter's 'Line too long' flag\n same_username = username == r_username\n same_password = sha256_crypt.verify(old_password, r_salt_hash)\n\n if same_username and same_password:\n t_salt_hash = sha256_crypt.hash(new_password1)\n tempfile.write(username + \" \" + t_salt_hash + \"\\n\")\n else:\n tempfile.write(r_username + \" \" + r_salt_hash + \"\\n\")\n except ValueError:\n pass\n\n # remove the password backup file that *may* have been previously created\n # fail silently if the file does not exist\n try:\n os.remove(PASSFILE + \".bak\")\n except OSError:\n pass\n\n # this keeps a backup of the previous passfile\n os.rename(PASSFILE, PASSFILE + \".bak\")\n os.rename(TEMPFILE, PASSFILE)\n flash(\"Password changed\")\n return render_template(\"index.html\")\n else:\n flash(\"Must be logged in to change password.\")\n return redirect(url_for(\"login\"))\n\n return render_template(\"changepassword.html\")",
"def post(self, request):\n if 'password' in self.request.POST and 'user_id' in self.request.POST:\n if User.objects.filter(id=self.request.POST['user_id']).exists():\n user = User.objects.get(id=self.request.POST['user_id'])\n user.set_password(self.request.POST['password'])\n user.save()\n return Response({'status': True})\n return Response({'status': False})"
] | [
"0.7494749",
"0.74338984",
"0.7425156",
"0.739893",
"0.73911446",
"0.73620486",
"0.73605317",
"0.73569167",
"0.7258721",
"0.72027224",
"0.71904075",
"0.71764475",
"0.7162846",
"0.71621287",
"0.7122842",
"0.71223277",
"0.70606965",
"0.70595974",
"0.70385784",
"0.70318645",
"0.7009277",
"0.6993962",
"0.6992526",
"0.69889176",
"0.6986303",
"0.6971039",
"0.6940622",
"0.69314504",
"0.6927525",
"0.69006985"
] | 0.74420726 | 1 |
Controller that display the reset_password page. Only user_email is needed to be input. Controller will validate the email in database and generate a new password 10lenghtrandom string. Then it will try to send a email with new password to user's mailbox by gmail. Email template is email.txt | def reset_password():
form = ResetPassword()
if form.validate_on_submit():
user_email = form.email.data
mail_exist = db.check_email(user_email)
if mail_exist is not None:
new_password = generate_password()
new_password_hash = generate_password_hash(new_password)
username = mail_exist['username']
db.update_password_username(username, new_password_hash)
flash('Your new password has been sent to your mailbox')
redirect('login')
# send_password_reset_email(user_email, new_password)
return redirect(url_for('login'))
else:
flash('This email address is not registered')
return redirect('reset_password')
return render_template('resetpassword.html', form=form) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def password_reset(request):\n\n\tcontext_dict = {}\n\tif request.method == 'POST':\n\t\temail = request.POST.get('email')\n\t\tif email:\n\t\t\tuser = models.Teacher.objects.get(\n\t\t\t\tsoft_delete=False, user__email=email\n\t\t\t)\n\t\t\tif not user:\n\t\t\t\tcontext_dict[\"message\"] = \"Email ID does'nt exist, Enter Correct details\"\n\t\t\tmail = {\n\t\t\t\t'email': email,\n\t\t\t\t'domain': request.META['HTTP_HOST'],\n\t\t\t\t'site_name': 'Placement Portal',\n\t\t\t\t'uid': urlsafe_base64_encode(force_bytes(user.pk)),\n\t\t\t\t'user': user,\n\t\t\t\t'token': ''.join([random.choice(ascii_letters+digits) for i in range (128)]),\n\t\t\t\t'protocol': 'http',\n\t\t\t}\n\t\t\ttry:\n\t\t\t\treset_token = models.PasswordReset(\n\t\t\t\t\tuser=user,\n\t\t\t\t\ttoken=mail['token'],\n\t\t\t\t\ttoken_consumed=False,\n\t\t\t\t)\n\t\t\t\treset_token.save()\n\t\t\texcept Exception as e:\n\t\t\t\tprint (e)\n\t\t\tsubject_template_name = 'password_reset_email_subject.txt'\n\t\t\temail_template_name = 'password_reset_email.html'\n\t\t\tsubject = loader.render_to_string(subject_template_name, mail)\n\t\t\tsubject = ''.join(subject.splitlines())\n\t\t\temail_data = loader.render_to_string(email_template_name, mail)\n\t\t\tsend_mail(subject, email_data, DEFAULT_FROM_EMAIL, [email], fail_silently=False)\n\t\t\tcontext_dict[\"message\"] = \"Email has been sent to your registered Email ID with instructions.\"\n\treturn render(request, \"password_reset_form.html\", context_dict)",
"def forgot_password():\r\n form = ForgotPasswordForm(request.form)\r\n if form.validate_on_submit():\r\n user = model.user.User.query\\\r\n .filter_by(email_addr=form.email_addr.data)\\\r\n .first()\r\n if user and user.email_addr:\r\n msg = Message(subject='Account Recovery',\r\n recipients=[user.email_addr])\r\n if user.twitter_user_id:\r\n msg.body = render_template(\r\n '/account/email/forgot_password_openid.md',\r\n user=user, account_name='Twitter')\r\n elif user.facebook_user_id:\r\n msg.body = render_template(\r\n '/account/email/forgot_password_openid.md',\r\n user=user, account_name='Facebook')\r\n elif user.google_user_id:\r\n msg.body = render_template(\r\n '/account/email/forgot_password_openid.md',\r\n user=user, account_name='Google')\r\n else:\r\n userdict = {'user': user.name, 'password': user.passwd_hash}\r\n key = signer.signer.dumps(userdict, salt='password-reset')\r\n recovery_url = url_for('.reset_password',\r\n key=key, _external=True)\r\n msg.body = render_template(\r\n '/account/email/forgot_password.md',\r\n user=user, recovery_url=recovery_url)\r\n msg.html = markdown(msg.body)\r\n mail.send(msg)\r\n flash(gettext(\"We've send you email with account \"\r\n \"recovery instructions!\"),\r\n 'success')\r\n else:\r\n flash(gettext(\"We don't have this email in our records. \"\r\n \"You may have signed up with a different \"\r\n \"email or used Twitter, Facebook, or \"\r\n \"Google to sign-in\"), 'error')\r\n if request.method == 'POST' and not form.validate():\r\n flash(gettext('Something went wrong, please correct the errors on the '\r\n 'form'), 'error')\r\n return render_template('/account/password_forgot.html', form=form)",
"def forgotPassword():\n if request.method == 'POST':\n if emailform():\n email = request.form['email1']\n\n #Confirm the user exist\n if hl.confirmUser(email):\n user = hl.getUser(\"Email\",email)\n refLink = \"http://\"+request.headers['Host']+hl.genUrl(user[\"Name\"],\"Password\")\n #Send email\n msg = \"\"\"\n Dear {},\n\n You are receiving this email because you have requested your password be reset. \n Use the following link to reset your password:\n\n {}\n\n If you did not request that your password be changed, please reply to this email immediately.\n\n Regards,\n Onegroup Admin Team\n \"\"\".format(user[\"Name\"],refLink)\n\n emailMessage(\"Password Reset\", [user[\"Email\"]], msg)\n return redirect(url_for('confirm', confirmed = 'Password reset email has been sent.'))\n else:\n flash(\"User doesn't exists\")\n else:\n flash(\"Emails don't match\")\n \n return render_template('emailsend.html')",
"def reset_password():\n if current_user.is_authenticated:\n return redirect(url_for('main.home'))\n\n form = RequestResetForm()\n\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n send_reset_email(user) # located in utils.py\n flash('An email has been sent with instruction to reset your password', 'info')\n return redirect(url_for('users.login'))\n\n return render_template('reset_password_request.html', form=form)",
"def forgot_password():\n url = 'http://localhost:8080/' + 'user/reset/'\n body = request.get_json()\n email = body.get('email')\n if not email:\n return jsonify(msg.MISSING_PARAMETER), 400\n user_email = views.UserManagement().exists(email=email)\n\n if not user_email:\n return jsonify(msg.NO_DATA), 404\n expires = datetime.timedelta(hours=24)\n reset_token = create_access_token(identity=email, expires_delta=expires)\n\n send_email('[Shodita] Reset Your Password', sender='[email protected]', recipients=[email],\n text_body=render_template('email/reset_password.txt', url=url + reset_token),\n html_body=render_template('email/reset_password.html', url=url + reset_token))\n\n return jsonify(msg.SUCCESS), 200",
"def forgot_password():\n if request.method == 'POST':\n if 'username' in request.form:\n username = request.form['username']\n user = Users.query.get(username)\n if user:\n reset_slug = utils.encrypt(username)\n reset_url = request.host_url + 'reset_password' + '/' + reset_slug\n from_email = ('[email protected]', 'TSG Bot')\n to_email = [(user.email, user.name)]\n subject = 'Password reset for Hades account'\n content = f\"Hello {user.name}, please click <a href=\\\"{reset_url}\\\">here</a> to reset your password!\"\n utils.send_mail(from_email, to_email, subject, content)\n return redirect(url_for('login'))\n return render_template('forgot_password.html')",
"def send_password_reset_email(user):\n\n token = user.get_password_token()\n reset_time=datetime.now()\n send_email('[SiteSurveyApp] Account password reset',\n recipients=[user.email],\n sender=app.config['MAIL_DEFAULT_SENDER'],\n text_body=render_template('auth/emails/reset_password.txt',\n user=user, token=token, reset_time=reset_time),\n html_body=render_template('auth/emails/reset_password.html',\n user=user, token=token, reset_time=reset_time))",
"def post(self):\n try:\n url = request.host_url + 'reset/password/'\n body = request.get_json()\n base_url = request.url_root\n email = body.get('email')\n\n if not email:\n raise SchemaValidationError\n\n user = User.objects.get(email=email)\n if not user:\n raise EmailDoesNotExistsError\n\n expires = datetime.timedelta(minutes=60)\n payload = {\"user_id\": str(user.id)}\n reset_token = create_access_token(payload, expires_delta=expires)\n\n return send_email('[Unboxit] Reset Your Password',\n sender='[email protected]',\n recipients=[user.email],\n text_body=render_template(\n 'components/reset_password.txt',\n url=url + reset_token),\n html_body=render_template(\n 'components/reset_password.html',\n url=url + reset_token,\n first_name=user.first_name,\n base_url=base_url))\n except SchemaValidationError:\n raise SchemaValidationError\n except DoesNotExist:\n raise EmailDoesNotExistsError\n except Exception as e:\n raise InternalServerError",
"def forgot_password():\n\n if not current_user.is_anonymous():\n return redirect(url_for(\"forum.index\"))\n\n form = ForgotPasswordForm()\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n\n if user:\n token = user.make_reset_token()\n send_reset_token(user, token=token)\n\n flash((\"E-Mail sent! Please check your inbox.\"), \"info\")\n return redirect(url_for(\"auth.forgot_password\"))\n else:\n flash((\"You have entered an username or email that is not linked \\\n with your account\"), \"danger\")\n return render_template(\"auth/forgot_password.html\", form=form)",
"def reset_password_request():\n form = ResetPasswordRequestForm()\n if form.validate_on_submit():\n try:\n user = User.query.filter_by(email=form.email.data).first_or_404()\n except Exception:\n flash('This Email ID is Not Registered', 'error')\n return render_template('password_reset_request.html',\n form=form), 400\n\n if user:\n send_password_reset_email(user)\n flash('Please check your email for a password reset link.',\n 'success')\n return render_template('post_pass_reset_request.html',\n title=\"Reset Password\")\n else:\n flash(\n 'Your email address must be confirmed \\\n before attempting a password reset.',\n 'error')\n return redirect(url_for('auth.login'))\n\n return render_template('password_reset_request.html', form=form), 400",
"def post(self):\n args = password_reset.parse_args()\n email = args.get('email')\n new_password = password_generator()\n\n validation_email = email_validation(email)\n if validation_email:\n return validation_email\n\n user = User.query.filter_by(email=email).first()\n if user:\n user.password = new_password\n user.save()\n response = {\n \"message\": \"Password has been reset\",\n \"status\": \"Reset password succesful!\",\n \"new_password\": new_password\n }\n return response, 200\n else:\n response = {\n 'message': 'User email does not exist, Please try again',\n 'status': 'Reset password failed!'\n }\n return response, 400",
"def post(self):\n data = request.get_json()\n user = actions.get_user_by_email(data['email'])\n html = '<p>To reset your password </p>'\n subject = 'Request for changing password, ' + user['username']\n actions.send_email(data['email'], user['username'], user['password'], subject,\n '/reset_password/', html, False)\n pass",
"def forgot_password():\n \n if 'username' in session: \n flash('You are already logged in, you can reset your password here.', 'info')\n return redirect(url_for('dashboard'))\n \n form = ForgotPasswordForm()\n \n if request.method == 'POST':\n if form.validate_on_submit(): \n user = mongo.db.user.find_one({'email':form.email.data})\n\n if user:\n flash('Please enter your security passphrase and create a new password', 'info')\n return redirect(url_for('reset_password')) \n \n flash('Email address not found!', 'danger')\n return render_template('pages/forgot.html', \n title='Forgot Password', \n form=form\n )\n \n return render_template('pages/forgot.html', title='Forgot Password', form=form)",
"def send_password_reset(user):\n _log('++ sending password reset email for: {} {}'.format(user.first_name, user.last_name))\n secret_string = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(20))\n\n # if local set the domain to localhost\n if ENV_DICT['ENVIRON'] == 'LOCAL':\n secret_link = 'http://localhost:8080/reset/{}/'.format(secret_string)\n # otherwise use the subdomain of the tenancy\n else:\n secret_link = 'http://{}.cpisearch.io/reset/{}/'.format(user.tenancy, secret_string)\n\n reset_link_object = PasswordResetLink(\n user_id=user.user_id,\n secret_link=secret_string,\n tenancy=user.tenancy,\n )\n db.session.add(reset_link_object)\n db.session.commit()\n send_email(\n to_email=user.email,\n subject='SuccessKit Password Reset',\n template_path='emails/password_reset_email.html',\n template_vars={\n 'user': user,\n 'secret_link': secret_link\n }\n )",
"def handle_emails():\n email = request.data['email'].strip()\n user = User.query.filter_by(email=email).first()\n option = \\\n request.data['option'].strip() # have a <select> in the frontend\n token = s.dumps(email, salt='email-confirm')\n\n msg = Message('Reset password', sender=app.config['ADMINS'][0],\n recipients=[email])\n link = 'http://localhost:3000/confirm_email/{}/{}'\\\n .format(option, token)\n if user:\n msg.body = 'Your link is {}'.format(link)\n else:\n msg.body = 'You attempted to reset your password but you do not \\\n have an account with us. Please Sign Up and Log in. {}'\\\n .format('http://localhost:3000/register')\n\n mail.send(msg)\n return jsonify({\"message\":\"Please confirm your email.\"}), 201",
"def send_password_reset_email():\n aaa.send_password_reset_email(\n username=post_get('username'),\n email_addr=post_get('email_address')\n )\n return 'Please check your mailbox.'",
"def user_password_reset(self, request):\n reset_password_form = ResetPasswordForm(request.form)\n\n if request.method == \"POST\":\n if reset_password_form.validate_on_submit():\n if check_password_hash(current_user.password, reset_password_form.old_password.data):\n new_hashed_password = generate_password_hash(reset_password_form.password.data)\n\n temp = current_user.get_id()\n (role, email) = temp.split(\":\")\n\n # if first element is `sysadmin` instead of a scheme_id\n # call function to reset `sysadmin` pass\n if role == \"sysadmin\":\n self._scheme_handler.update_hash_password(email, new_hashed_password)\n else:\n # regular user reset\n self._student_handler.update_hash_password(current_user.scheme_id, current_user.k_number, new_hashed_password)\n\n flash(\"Password successfully updated\")\n else:\n flash(\"Old password incorrect\")\n else:\n flash(\"Please double check your new password is valid.\")\n \n return render_template(\"user/reset_password.html\", reset_password_form=reset_password_form)",
"def forgot_passwd(request):\n dc_settings = request.dc.settings\n\n return password_reset(\n request,\n template_name='gui/accounts/forgot.html',\n email_template_name='gui/accounts/forgot_email.txt',\n subject_template_name='gui/accounts/forgot_subject.txt',\n password_reset_form=partial(ForgotForm, request),\n post_reset_redirect=reverse('forgot_done'),\n from_email=dc_settings.DEFAULT_FROM_EMAIL,\n current_app='gui',\n extra_context={\n 'e_site_name': dc_settings.SITE_NAME,\n 'e_site_link': dc_settings.SITE_LINK,\n })",
"def get(self, request, email=None):\n\n user = User.objects.filter(email=request.GET.get('email'))\n\n if user.count() == 1 and user.first() is not None:\n user = user.first()\n\n random_password = User.objects.make_random_password()\n user.set_password(random_password)\n user.save()\n\n message = \"\"\"Olá,\\nSua senha foi resetada, acesse a plataforma\n no link http://127.0.0.1/user/password e troque a\n senha\\nSua nova senha é:\\n {}\\nAtenciosamente,\n \\nEquipe Dream Rich.\"\"\".format(random_password)\n\n email = EmailMessage('Password reset',\n message, to=[user.email])\n email.send()\n\n return Response(dumps({'detail': 'email sent'}), status=200)\n\n return Response(dumps({'detail': 'user not found'}), status=404)",
"def reset_password():\n json_data = request.get_json()\n user_email = json_data.get('email') or None\n\n if user_email is None:\n raise BadRequest(description=INCORRECT_RESET_PARAMS_MSG)\n\n user_account = db.session.query(UserAccount).filter(\n UserAccount.email == user_email).first()\n if user_account is None:\n raise BadRequest(description=INCORRECT_RESET_PARAMS_MSG)\n\n # Generate password hash\n temp_password = str(random.randint(10000,99999))\n update_user = {'password_hashed': get_hashed_password(temp_password)}\n user_account.update(**update_user)\n user_account.save()\n\n email.send('reset_password', user_email, temp_password)\n\n return {'status_code': 200, 'message': 'Password reset success!'}",
"def login_resetrequest():\n if request.method == \"GET\":\n # In browser request that user wants to reset the password\n return flask.render_template('reset-request.html', message=\"Please reset the password\")\n\n if request.method == \"POST\":\n # Create a token\n email = flask.request.form[\"email\"]\n\n # Find if an account with that name exists\n conn.register([model.User])\n admindb = conn[current_app.config[\"CONFIGDB\"]]\n\n userdoc = admindb[\"users\"].User.find_one({\"name\" : email, \"type\" : \"passwd\"})\n if userdoc == None:\n # user not found\n return flask.Response('{\"error\" : \"User not found\"}')\n\n # First reset the password\n name = userdoc[\"label\"]\n emailto = userdoc[\"name\"]\n\n # Create accout and a random tocken\n userdoc[\"token\"] = bson.ObjectId()\n userdoc[\"password_status\"] = \"reset-request\"\n\n # May only be useful for some\n if \"password_ready\" in userdoc:\n del userdoc[\"password_ready\"]\n\n userdoc.validate()\n userdoc.save()\n\n # Create email\n emailfrom = current_app.config[\"EMAIL_FROM\"] \n\n body = \"Hello \" + name + \",\\n\\n\"\n body = body + \"You recently requested a password reset for your account at https://slide-atlas.org.\"\n body = body + \"\\n To complete the request operation please follow the link below- \\n\"\n body = body + \"\\n \" + url_for('.login_confirm', _external=True) + \"?token=\" + str(userdoc[\"token\"]) + \" \\n\"\n body = body + \"\\nIf clicking on the link doesn't work, try copying and pasting it into your browser.\\n\"\n body = body + \"\\nThis link will work only once, and will let you create a new password. \\n\"\n body = body + \"\\nIf you did not request password reset, please disregard this message.\\n\"\n body = body + \"\\nThank you,\\nThe SlideAtlas Administration Team\\n\"\n\n # Create a text/plain message\n msg = MIMEText(body)\n\n # me == the sender's email address\n # you == the recipient's email address\n msg['Subject'] = 'Password reset confirmation for slide-atlas.org'\n msg['From'] = emailfrom\n msg['To'] = emailto\n print msg\n s = smtplib.SMTP(current_app.config[\"SMTP\"])\n try:\n out = s.sendmail(emailfrom, [emailto], msg.as_string())\n except:\n return flask.Response(\"{\\\"error\\\" : \\\"Error sending email\\\"}\")\n\n s.quit()\n return flask.Response(\"{\\\"success\\\" : \\\"\" + str(out) + \"\\\"}\")",
"def create(self,request):\n try:\n print(request.data)\n user = models.UserProfile.objects.get(email=request.data['email'])\n current_site=get_current_site(request)\n email_subject='Reset Password'\n message=render_to_string('reset_password.html',{\n 'user':user,\n 'domain':current_site.domain,\n 'uid':urlsafe_base64_encode(force_bytes(user.id)),\n 'token':account_activation_token.make_token(user),\n })\n to_email= user.email\n email= EmailMessage(email_subject,message,to=[to_email])\n email.send()\n return Response(\n {\n \"status\":\"The Reset password email has been sent.\"\n }\n )\n except(TypeError, ValueError, KeyError, OverflowError, models.UserProfile.DoesNotExist):\n user = None\n return Response(\n {\n \"status\":\"No matching account found.\"\n }\n )",
"def reset_password_email(request):\n if request.method == 'POST' :\n try:\n print(request.POST)\n user = models.UserProfile.objects.get(email=request.POST.get('email',''))\n current_site=get_current_site(request)\n email_subject='Password Reset'\n message=render_to_string('reset_password.html',{\n 'user':user,\n 'domain':current_site.domain,\n 'uid':urlsafe_base64_encode(force_bytes(user.id)),\n 'token':account_activation_token.make_token(user),\n })\n to_email= user.email\n email= EmailMessage(email_subject,message,to=[to_email])\n email.send()\n return JsonResponse(\n {\n \"status\":\"The Reset password email has been sent.\"\n }\n )\n except(TypeError, ValueError, OverflowError, models.UserProfile.DoesNotExist):\n user = None\n return JsonResponse(\n {\n \"status\":\"No matching account found\"\n }\n )\n else :\n return JsonResponse(\n {\n \"status\":\"only post method is available\"\n }\n )",
"def forgotpassword(request):\n if request.method == 'GET':\n return render(request, 'app/other/forgot_password.html', {'title':'Forgot Password?',})\n elif request.method == 'POST':\n username = request.POST['username']\n\n if User.objects.filter(username = username).exists():\n user = User.objects.get(username = username)\n if Referee.objects.filter(user = user).exists():\n referee = Referee.objects.get(user = user)\n # generate token\n passwordResetTokenGenerator = PasswordResetTokenGenerator()\n token = PasswordResetTokenGenerator.generate_token(passwordResetTokenGenerator, str(user.id))\n token = str(token.decode('utf-8'))\n # email to referee\n subject = \"[Password Reset Link]\"\n message = 'http:////localhost:8000//reset//token=//' + token\n content = \"<br>Dear sir,</br><br></br><br></br>Link is: \"+message+'. Please click on the link to change the credentials.'+\"<br></br><br></br>Regards,<br></br>PhDPortal.\"\n email = []\n receiver = referee.user\n email.append(receiver.email)\n send_email_task.delay(email, subject, content)\n # redirect to same page with status to check your mail and click on activation link\n \n dict = {'status' : 'Done', 'message' : 'An Activation link has been sent to your mail-id'}\n return HttpResponse(json.dumps(dict), content_type = 'application/json')\n else: # given username is not valid to use this feature\n dict = {'status': 'Error', 'message' : 'You are not Authorized to change password'}\n return HttpResponse(json.dumps(dict), content_type = 'application/json')\n else: # given username is not valid to use this feature\n dict = {'status': 'Error', 'message' : 'Invalid Username, Try Again!'}\n return HttpResponse(json.dumps(dict), content_type = 'application/json')\n else:\n return redirect(reverse(URL_BAD_REQUEST))",
"def reset_password(email):\n user = AuthUser.query.filter_by(email=email).first()\n if user is None:\n return False\n # Generate email with unique link\n msg = Message(\n \"Password Reset Link\",\n recipients=[user.email] \n )\n msg.body = \"Click on this link and following the instructions to reset your \"\n \"password\\n\\n%s%s?uid=%s-%s\" % (\n app.config['SITE_URI'],\n \"/reset/password/\",\n user.id,\n user.get_uid()\n )\n mail.send(msg)\n return True",
"def send_pw_reset_email(user):\n token = user.get_token()\n message = Message(\n 'Reset Your Password',\n sender='[email protected]',\n recipients=[user.email])\n message.body = f\"To verify reset your password, click the link \" \\\n f\"below:\\n\\n\" \\\n f\"{url_for('users.reset_password', token=token, _external=True)}\"\n mail.send(message)",
"def save(self, domain_override=None,\n subject_template_name='registration/password_reset_subject.txt',\n email_template_name='registration/password_reset_email.html',\n use_https=False, token_generator=default_token_generator,\n from_email=None, request=None,\n html_email_template_name=None):\n email = self.cleaned_data[\"email\"]\n User = get_user_model()\n active_users = User.objects.filter(email__iexact=email, is_active=True)\n for user in active_users:\n subject = _('Flisol - Restore your password')\n # send_email(\n # subject,\n # [user.email],\n # email_template_name,\n # {\n # 'email': user.email,\n # 'uid': urlsafe_base64_encode(force_bytes(user.pk)),\n # 'user': user,\n # 'token': token_generator.make_token(user),\n # 'protocol': settings.PROTOCOL,\n # },\n # )",
"def forgot():\n form = ForgotForm()\n\n if form.validate_on_submit():\n db.session.add(form.pw_reset)\n db.session.commit()\n\n form.pw_reset.send()\n flash('A password reset link has been sent to your email', 'alert-success')\n return redirect(url_for('default.home'))\n else:\n flash_form_errors(form)\n return render_template('forgot.html', form=form)",
"def password_reset(request):\n try:\n with transaction.atomic():\n try:\n data = request.data\n data = validations_utils.email_validation(data) # Validates email id, it returns lower-cased email in data.\n user = validations_utils.user_validation_with_email(data['email'])\n except ValidationException as e: # Generic exception\n return Response(e.errors, status=e.status)\n current_site = get_current_site(request)\n domain = current_site.domain\n key = utils.create_reset_password_key(user.email)\n utils.send_reset_password_mail(user, key, domain) # Sends an email for resetting the password.\n return Response(messages.PASSWORD_RESET_LINK_SENT, status=status.HTTP_200_OK)\n except IntegrityError:\n return Response(messages.CAN_NOT_RESET_PASSWORD, status=status.HTTP_500_INTERNAL_SERVER_ERROR)",
"def send_recovery_password_email(token: str, email: str) -> None:\n\n # TODO ...\n # Load html templates and get the content from it.\n # html_content = ...\n\n # You must have to send this as a anchor\n # to my-domain.com/reset-password?token=ad5a....\n link = f\"{SERVER_HOST}/reset-password?token={token}\"\n content = f\"\"\"\n <h1>Reset your password</h1>\n <p></p>\n <a href=\"{link}\" target=\"_blank\" rel=\"noopener noreferrer\">Press here</a>\n \"\"\"\n email = sender.create_email(\n to_list=[email],\n subject=f\"Recovery Password\",\n html_content=content,\n )\n sender.send_email(email_to_send=email)"
] | [
"0.78898954",
"0.7747274",
"0.76886064",
"0.7638217",
"0.7600962",
"0.7510319",
"0.7439754",
"0.7414105",
"0.7399373",
"0.7390694",
"0.73104703",
"0.7239809",
"0.72272164",
"0.71323067",
"0.7128626",
"0.7115529",
"0.7113557",
"0.70996207",
"0.70738316",
"0.70691335",
"0.70593417",
"0.7026405",
"0.70098263",
"0.7009005",
"0.6987448",
"0.6968326",
"0.6967094",
"0.6964926",
"0.6930718",
"0.690959"
] | 0.7804686 | 1 |
Background Cloud Function to be triggered by Cloud Storage. This generic function logs relevant data when a file is changed. | def hello_gcs_generic(data, context):
print('Event ID: {}'.format(context.event_id))
print('Event type: {}'.format(context.event_type))
print('Bucket: {}'.format(data['bucket']))
print('File: {}'.format(data['name']))
print('Metageneration: {}'.format(data['metageneration']))
print('Created: {}'.format(data['timeCreated']))
print('Updated: {}'.format(data['updated']))
bucket_name = data['bucket']
file_name = data['name']
path = os.path.join(bucket_name,file_name)
from google.cloud import storage
import os
import tempfile
client = storage.Client()
_, temp_local_filename = tempfile.mkstemp()
bucket = client.get_bucket(bucket_name)
# bucket = google.cloud.storage.bucket.Bucket
blob = bucket.blob(file_name)
dst_bucket = client.bucket("apps-script-jpos-cache")
new_blob = bucket.copy_blob(blob, dst_bucket) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def dataprep_job_gcs_trigger(event, context):\n\n head_tail = os.path.split(event['name'])\n newfilename = head_tail[1]\n newfilepath = head_tail[0]\n\n datataprep_auth_token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbklkIjoiNDZiOWY2YWUtYTg0Zi00ZWQyLTgxNTMtZDA0MjBjNzIyZTk2IiwiaWF0IjoxNjA2MjI1NTU4LCJhdWQiOiJ0cmlmYWN0YSIsImlzcyI6ImRhdGFwcmVwLWFwaS1hY2Nlc3MtdG9rZW5AdHJpZmFjdGEtZ2Nsb3VkLXByb2QuaWFtLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJzdWIiOiJkYXRhcHJlcC1hcGktYWNjZXNzLXRva2VuQHRyaWZhY3RhLWdjbG91ZC1wcm9kLmlhbS5nc2VydmljZWFjY291bnQuY29tIn0.QKr_IfTOw_7SfK2sjMBAy_GDwdGNRuIP3f5PgUyqfj3rPdpr_4CAqNVDh11_q-NfpxoCkQEscgWs_jBrqXaOR0n4gVXzv0Yc8JAw2Qy5C0ZopbKHYvv0Pvdnd1ELjQTmzPCTzu1DdWEPLlby6feJdzeBDEA2nQvG9LkR9394V7nJK6Ly5XwdcAqWtcyPDaOZn06Ul1wRNcTgRuESVvcG-BfkKsRFCEVMZUJYr9Wc7ngVWCq80pEfksQYa2BQ-T4T6W89x2VfwHadGmXyruqWuvEv59WRxmaZ0CUjtmiocXOzzuJHTSyp9kPN9HlJ5a7wcR7Lz_53-lLKsUpHU0re0g'\n dataprep_jobid = 2011662\n\n if context.event_type == 'google.storage.object.finalize' and newfilepath == 'DESIGN_PATTER_SOLUTION_P1':\n\n file_uncompressed = zipextract(\"dataprep-staging-67278b43-7b2d-4e79-8d2f-5d8c470e77eb\", newfilepath, newfilename)\n \n print('Run Dataprep job on new file: {}'.format(file_uncompressed))\n\n dataprep_runjob_endpoint = 'https://api.clouddataprep.com/v4/jobGroups'\n datataprep_job_param = {\n \"wrangledDataset\": {\"id\": dataprep_jobid},\n \"runParameters\": {\"overrides\": {\"data\": [{\"key\": \"filename\",\"value\": file_uncompressed}]}}\n }\n print('Run Dataprep job param: {}'.format(datataprep_job_param))\n dataprep_headers = {\n \"Content-Type\":\"application/json\",\n \"Authorization\": \"Bearer \"+datataprep_auth_token\n } \n\n resp = requests.post(\n url=dataprep_runjob_endpoint,\n headers=dataprep_headers,\n data=json.dumps(datataprep_job_param)\n )\n\n print('Status Code : {}'.format(resp.status_code)) \n print('Result : {}'.format(resp.json()))\n\n return 'End File event'.format(newfilename)",
"def notify_cloudwatch(function):\n @wraps(function)\n def wrapper(event, context):\n logger.info(f\"'{context.function_name}' - entry:'{event}'\")\n result = function(event, context)\n logger.info(f\"'{context.function_name}' - entry.'{result}'\")\n return result\n return wrapper",
"def main(msg: func.QueueMessage) -> None:\n code_start_time = time.time()\n logging.info('Python queue trigger function processed a queue item: %s',\n msg.get_body().decode('utf-8'))\n # modify the log level of azure sdk requests\n logging.getLogger('azure').setLevel(logging.WARNING)\n init_config_values()\n\n tc = TelemetryClient(APPINSIGHTS_INSTRUMENTATIONKEY)\n tc.context.application.ver = '1.0'\n tc.context.properties[\"PROCESS_PROGRAM\"] = PROCESS_PROGRAM_NAME\n tc.context.properties[\"PROCESS_START\"] = time.time()\n\n # 1. Get trigger file content (rename event)\n content_json = json.loads(msg.get_body().decode('utf-8'))\n\n logging.info(\"meta-data event content: {}\".format(msg.get_body().decode('utf-8')))\n file_url = content_json['data']['destinationUrl']\n logging.info(f\"file_url: {file_url}\")\n event_time = content_json['eventTime']\n\n # 2. Download metadata blob content\n logging.info(f\"{HEADER} Download blob file from {file_url}\")\n temp_blob_client = BlobClient.from_blob_url(blob_url=file_url, logging_enable=False)\n blob_path = temp_blob_client.blob_name\n container_name = temp_blob_client.container_name\n\n try:\n metadata_file_content = get_blob_content(container_name, blob_path)\n except Exception:\n logging.exception(f\"Failed to download blob from url {file_url}\")\n raise\n\n # 3. Parse split output file from the metadata\n queue_msg_list = generate_metadata_queue_messages(event_time, metadata_file_content)\n logging.info(\n f\"{HEADER} Generate metadata queue_messages from {file_url}, {len(queue_msg_list)} messages\")\n\n # 4. Loop to enqueue msg to ADX ingest queue\n queue_client_list = []\n for q_url in ADX_INGEST_QUEUE_URL_LIST:\n queue_client = get_queue_client(q_url)\n queue_client_list.append(queue_client)\n\n asyncio.set_event_loop(asyncio.new_event_loop())\n loop = asyncio.get_event_loop()\n tasks = gen_metadata_msg_enqueue_tasks(queue_msg_list, queue_client_list, tc)\n loop.run_until_complete(gather_with_concurrency(CONCURRENT_ENQUEUE_TASKS, tasks))\n close_queue_clients(queue_client_list, loop)\n loop.close()\n\n logging.info(f\"{HEADER} Done queuing up messages to Ingestion queue\")\n\n if file_url.endswith(\".compact\"): # reduce compact file size\n update_blob_content(container_name,\n blob_path,\n get_shrinked_checkpoint_content(\n metadata_file_content, MAX_COMPACT_FILE_RECORDS))\n logging.info(f\"{HEADER} Reduced checkpoint files {file_url}, max lines is {MAX_COMPACT_FILE_RECORDS}\")\n\n code_duration = time.time() - code_start_time\n tc.track_event(METADATA_HANDLE_EVENT_NAME,\n {'FILE_URL': file_url},\n {METADATA_HANDLE_EVENT_NAME + '_DURATION_SEC': code_duration})\n tc.flush()",
"def redact_gcs(event, context):\n # CLIENT\n storage_client = storage.Client()\n\n # CONFIG\n # NOTE project = os.environ.get(\"GOOGLE_CLOUD_PROJECT\")\n # ENV variable only exists in GCE, not GCF runtime\n project = 'sc-nlp'\n destination_bucket = \"dlp-outbound\" # inbound bucket is in deploy call\n output_filename = event['name']\n\n # Construct buckets and blobs\n input_bucket_obj = storage_client.get_bucket(event['bucket'])\n input_byte_obj = input_bucket_obj.get_blob(event['name'])\n input_bytes = input_byte_obj.download_as_bytes()\n\n output_bucket_obj = storage_client.get_bucket(destination_bucket)\n output_blob = output_bucket_obj.blob(output_filename)\n\n # Write bytes to object and upload\n result = redact_image_all_text(project, input_bytes)\n output_blob.upload_from_string(result)",
"def main(event, context):\n current_time = datetime.utcnow()\n logging.info(f\"Cloud Function was triggered on {current_time}\")\n\n # message\n message_decoded = b64decode(event[\"data\"].encode(\"ascii\")).decode(\"ascii\")\n message = json.loads(message_decoded) if message_decoded else {}\n\n logging.info(f\"Downloading confirmed: {source_url}\")\n df = (\n pd.read_csv(source_url)\n .dropna(subset=[\"COUNTY_FIPS_NUMBER\"])\n .rename(columns={\n \"REPORT_DATE\": \"date_id\",\n \"COUNTY_FIPS_NUMBER\": \"county_id\",\n \"PEOPLE_POSITIVE_CASES_COUNT\": \"total_cases\",\n \"PEOPLE_POSITIVE_NEW_CASES_COUNT\": \"new_cases\",\n \"PEOPLE_DEATH_NEW_COUNT\": \"new_deaths\",\n \"PEOPLE_DEATH_COUNT\": \"total_deaths\",\n })[[\n \"county_id\",\n \"date_id\",\n \"new_cases\",\n \"new_deaths\",\n \"total_cases\",\n \"total_deaths\",\n ]]\n )\n df[\"date_id\"] = pd.to_datetime(df[\"date_id\"]).dt.strftime(\"%Y%m%d\")\n df[\"county_id\"] = df[\"county_id\"].astype(int).astype(str).str.zfill(5)\n df.loc[df[\"new_cases\"] < 0, \"new_deaths\"] = 0\n df.loc[df[\"new_deaths\"] < 0, \"new_deaths\"] = 0\n\n df.to_csv(\"data/import/county_cases.csv\", index=False)",
"def webhook_upload(user, application, complete_path, init_es, tool, scan_name, user_host, to_name,hook_log):\n hook_log = WebhookLog.objects.get(id=hook_log)\n hook_log.file_upload_event = True\n hook_log.file_upload_datetime = timezone.now()\n hook_log.save()\n process_files(user, application, complete_path, init_es, tool, scan_name, user_host, to_name,hook_log=hook_log)\n info_debug_log(event='Webhook upload',status='success')",
"def notify_upload():\n file_type = request.json.get(\"file_type\")\n file_name = request.json.get(\"file_name\")\n file_path = request.json.get(\"file_path\")\n file_size = request.json.get(\"file_size\")\n print(\"File was uploaded:\", file_path, file_name, file_type)\n # Marks the upload as confirmed.\n d = datetime.datetime.utcnow()\n db.upload.update_or_insert(\n ((db.upload.owner == get_user_email()) &\n (db.upload.file_path == file_path)),\n owner=get_user_email(),\n file_path=file_path,\n file_name=file_name,\n file_type=file_type,\n file_date=d,\n file_size=file_size,\n confirmed=True,\n )\n # Returns the file information.\n return dict(\n download_url=gcs_url(GCS_KEYS, file_path, verb='GET'),\n file_date=d,\n )",
"def processTempLog(file_name):",
"def on_sync(self):\r\n self.log()",
"def upload_progress(self, cloud_file, size, uploaded):",
"def __on_backup_created(self, logger, *args):",
"def upload_finish(self, cloud_file):",
"def lambda_handler(event, context):\n print(event)\n print(context)\n storage_gateway_status()",
"def update_log(er=\"File created\",log_path=log_path, s3_path_log = s3_path_log, upload=False):\n print(er)\n with open(log_path, 'a') as file:\n file.write(str(datetime.now()) + ',' + str(er) + '\\n')\n # if upload is True:\n # s3.meta.client.upload_file(log_path, bucket_name, s3_path_log)",
"def watcher():\n # checking if logger is working or not\n # if not then handle exception otherwise watcher thread would stop\n create_logs = True\n try:\n logger = Logger()\n logger.pipeline_logs(\"Watcher Started\")\n except pymongo.errors.ServerSelectionTimeoutError:\n create_logs = False\n except Exception as e:\n print(e)\n create_logs = False\n\n cloud = Cloud()\n db = DbConnector()\n current_file_count = None\n total_file_count = None\n print('WATCHER THREAD STARTED')\n while True:\n if total_file_count is None or current_file_count is None:\n filenames = cloud.get_file_names('wafer/data/prediction/')\n filecount = len(filenames)\n current_file_count = filecount\n total_file_count = filecount\n elif current_file_count < total_file_count:\n total_file_count = current_file_count\n else:\n time.sleep(120)\n filenames = cloud.get_file_names('wafer/data/prediction/')\n current_file_count = len(filenames)\n if current_file_count != total_file_count and current_file_count != 0:\n print('TRIGGERED PREDICTION')\n if create_logs is True:\n logger.pipeline_logs('TRIGGER : PREDICTION TRIGGERED : New Files Found For Prediction')\n\n prepare_data = PreparePredictionData(logger, cloud, db)\n prepare_data.prepare()\n\n predictor = Predictor(logger, cloud, db)\n predictor.predict()\n if create_logs is True:\n logger.pipeline_logs('TRIGGER : PROCESS COMPLETED : PREDICTIONS SAVED TO DATABASE ')\n total_file_count = current_file_count",
"def _trigger(self, event):\n if self._tests_running:\n # Avoid infinite loop\n return\n\n if self._in_retention_period():\n return\n\n relevant = self._is_relevant(event)\n\n if not relevant:\n return\n\n cache_key = self._get_cache_key(event)\n if cache_key in self._file_cache:\n print('>>>> {0} is cached'.format(cache_key))\n return\n else:\n print('>>>> {0} NOT in cache'.format(cache_key))\n self._file_cache[cache_key] = True\n\n print('>> Trigger: {0}'.format(event))\n self.run_tests()",
"def monitor(self, filename):\n self.do_tail(filename, 0)",
"def track_with_info(context, action, resource, message, file, line_number,\n function, loglevel=logging.INFO):\n LogActionTrack.track_with_file_info(context, action, resource, message,\n file, line_number, function,\n loglevel=loglevel)",
"def on_exception(self, path, exc_info):\n\t\tlog.exception(\"Watching file %s failed.\"%path)",
"def Run(args, track=None, enable_runtime=True):\n flags.ValidateV1TimeoutFlag(args)\n\n # Check for labels that start with `deployment`, which is not allowed.\n labels_util.CheckNoDeploymentLabels('--remove-labels', args.remove_labels)\n labels_util.CheckNoDeploymentLabels('--update-labels', args.update_labels)\n\n # Check that exactly one trigger type is specified properly.\n trigger_util.ValidateTriggerArgs(args.trigger_event, args.trigger_resource,\n args.IsSpecified('retry'),\n args.IsSpecified('trigger_http'))\n trigger_params = trigger_util.GetTriggerEventParams(args.trigger_http,\n args.trigger_bucket,\n args.trigger_topic,\n args.trigger_event,\n args.trigger_resource)\n\n function_ref = args.CONCEPTS.name.Parse()\n function_url = function_ref.RelativeName()\n\n messages = api_util.GetApiMessagesModule(track)\n\n # Get an existing function or create a new one.\n function = api_util.GetFunction(function_url)\n\n is_new_function = function is None\n had_vpc_connector = bool(\n function.vpcConnector) if not is_new_function else False\n had_http_trigger = bool(\n function.httpsTrigger) if not is_new_function else False\n if is_new_function:\n trigger_util.CheckTriggerSpecified(args)\n function = messages.CloudFunction()\n function.name = function_url\n elif trigger_params:\n # If the new deployment would implicitly change the trigger_event type\n # raise error\n trigger_util.CheckLegacyTriggerUpdate(function.eventTrigger,\n trigger_params['trigger_event'])\n\n # Keep track of which fields are updated in the case of patching.\n updated_fields = []\n\n # Populate function properties based on args.\n if args.entry_point:\n function.entryPoint = args.entry_point\n updated_fields.append('entryPoint')\n if args.timeout:\n function.timeout = '{}s'.format(args.timeout)\n updated_fields.append('timeout')\n if args.memory:\n function.availableMemoryMb = utils.BytesToMb(args.memory)\n updated_fields.append('availableMemoryMb')\n if args.service_account:\n function.serviceAccountEmail = args.service_account\n updated_fields.append('serviceAccountEmail')\n if (args.IsSpecified('max_instances') or\n args.IsSpecified('clear_max_instances')):\n max_instances = 0 if args.clear_max_instances else args.max_instances\n function.maxInstances = max_instances\n updated_fields.append('maxInstances')\n if track in (calliope_base.ReleaseTrack.ALPHA,\n calliope_base.ReleaseTrack.BETA):\n if (args.IsSpecified('min_instances') or\n args.IsSpecified('clear_min_instances')):\n min_instances = 0 if args.clear_min_instances else args.min_instances\n function.minInstances = min_instances\n updated_fields.append('minInstances')\n if enable_runtime:\n if args.IsSpecified('runtime'):\n function.runtime = args.runtime\n updated_fields.append('runtime')\n\n warning = api_util.ValidateRuntime(args.runtime)\n if warning:\n log.warning(warning)\n\n elif is_new_function:\n raise calliope_exceptions.RequiredArgumentException(\n 'runtime', 'Flag `--runtime` is required for new functions.')\n if args.vpc_connector or args.clear_vpc_connector:\n function.vpcConnector = ('' if args.clear_vpc_connector else\n args.vpc_connector)\n updated_fields.append('vpcConnector')\n if args.IsSpecified('egress_settings'):\n will_have_vpc_connector = ((had_vpc_connector and\n not args.clear_vpc_connector) or\n args.vpc_connector)\n if not will_have_vpc_connector:\n raise calliope_exceptions.RequiredArgumentException(\n 'vpc-connector', 'Flag `--vpc-connector` is '\n 'required for setting `egress-settings`.')\n egress_settings_enum = arg_utils.ChoiceEnumMapper(\n arg_name='egress_settings',\n message_enum=function.VpcConnectorEgressSettingsValueValuesEnum,\n custom_mappings=flags.EGRESS_SETTINGS_MAPPING).GetEnumForChoice(\n args.egress_settings)\n function.vpcConnectorEgressSettings = egress_settings_enum\n updated_fields.append('vpcConnectorEgressSettings')\n if args.IsSpecified('ingress_settings'):\n ingress_settings_enum = arg_utils.ChoiceEnumMapper(\n arg_name='ingress_settings',\n message_enum=function.IngressSettingsValueValuesEnum,\n custom_mappings=flags.INGRESS_SETTINGS_MAPPING).GetEnumForChoice(\n args.ingress_settings)\n function.ingressSettings = ingress_settings_enum\n updated_fields.append('ingressSettings')\n if args.build_worker_pool or args.clear_build_worker_pool:\n function.buildWorkerPool = ('' if args.clear_build_worker_pool else\n args.build_worker_pool)\n updated_fields.append('buildWorkerPool')\n # Populate trigger properties of function based on trigger args.\n if args.trigger_http:\n function.httpsTrigger = messages.HttpsTrigger()\n function.eventTrigger = None\n updated_fields.extend(['eventTrigger', 'httpsTrigger'])\n if trigger_params:\n function.eventTrigger = trigger_util.CreateEventTrigger(**trigger_params)\n function.httpsTrigger = None\n updated_fields.extend(['eventTrigger', 'httpsTrigger'])\n if args.IsSpecified('retry'):\n updated_fields.append('eventTrigger.failurePolicy')\n if args.retry:\n function.eventTrigger.failurePolicy = messages.FailurePolicy()\n function.eventTrigger.failurePolicy.retry = messages.Retry()\n else:\n function.eventTrigger.failurePolicy = None\n elif function.eventTrigger:\n function.eventTrigger.failurePolicy = None\n if args.IsSpecified('security_level'):\n will_have_http_trigger = had_http_trigger or args.trigger_http\n if not will_have_http_trigger:\n raise calliope_exceptions.RequiredArgumentException(\n 'trigger-http',\n 'Flag `--trigger-http` is required for setting `security-level`.')\n security_level_enum = arg_utils.ChoiceEnumMapper(\n arg_name='security_level',\n message_enum=function.httpsTrigger.SecurityLevelValueValuesEnum,\n custom_mappings=flags.SECURITY_LEVEL_MAPPING).GetEnumForChoice(\n args.security_level)\n function.httpsTrigger.securityLevel = security_level_enum\n updated_fields.append('httpsTrigger.securityLevel')\n\n # Populate source properties of function based on source args.\n # Only Add source to function if its explicitly provided, a new function,\n # using a stage bucket or deploy of an existing function that previously\n # used local source.\n if (args.source or args.stage_bucket or is_new_function or\n function.sourceUploadUrl):\n updated_fields.extend(\n source_util.SetFunctionSourceProps(function, function_ref, args.source,\n args.stage_bucket, args.ignore_file))\n\n # Apply label args to function\n if labels_util.SetFunctionLabels(function, args.update_labels,\n args.remove_labels, args.clear_labels):\n updated_fields.append('labels')\n\n # Apply build environment variables args to function\n updated_fields.extend(_ApplyBuildEnvVarsArgsToFunction(function, args))\n\n # Apply environment variables args to function\n updated_fields.extend(_ApplyEnvVarsArgsToFunction(function, args))\n\n ensure_all_users_invoke = flags.ShouldEnsureAllUsersInvoke(args)\n deny_all_users_invoke = flags.ShouldDenyAllUsersInvoke(args)\n\n # Applies secrets args to function\n updated_fields.extend(_ApplySecretsArgsToFunction(function, args))\n\n # Applies CMEK args to function\n updated_fields.extend(\n _ApplyCMEKArgsToFunction(function_ref, function, args, track))\n\n if is_new_function:\n if (function.httpsTrigger and not ensure_all_users_invoke and\n not deny_all_users_invoke and\n api_util.CanAddFunctionIamPolicyBinding(_GetProject())):\n ensure_all_users_invoke = console_io.PromptContinue(\n prompt_string=(\n 'Allow unauthenticated invocations of new function [{}]?'.format(\n args.NAME)),\n default=False)\n\n op = api_util.CreateFunction(function, function_ref.Parent().RelativeName())\n if (function.httpsTrigger and not ensure_all_users_invoke and\n not deny_all_users_invoke):\n template = ('Function created with limited-access IAM policy. '\n 'To enable unauthorized access consider `%s`')\n log.warning(template % _CreateBindPolicyCommand(function_ref))\n deny_all_users_invoke = True\n\n elif updated_fields:\n op = api_util.PatchFunction(function, updated_fields)\n\n else:\n op = None # Nothing to wait for\n if not ensure_all_users_invoke and not deny_all_users_invoke:\n log.status.Print('Nothing to update.')\n return\n\n stop_trying_perm_set = [False]\n\n # The server asyncrhonously sets allUsers invoker permissions some time after\n # we create the function. That means, to remove it, we need do so after the\n # server adds it. We can remove this mess after the default changes.\n # TODO(b/130604453): Remove the \"remove\" path, only bother adding. Remove the\n # logic from the polling loop. Remove the ability to add logic like this to\n # the polling loop.\n # Because of the DRS policy restrictions, private-by-default behavior is not\n # guaranteed for all projects and we need this hack until IAM deny is\n # implemented and all projects have private-by-default.\n def TryToSetInvokerPermission():\n \"\"\"Try to make the invoker permission be what we said it should.\n\n This is for executing in the polling loop, and will stop trying as soon as\n it succeeds at making a change.\n \"\"\"\n if stop_trying_perm_set[0]:\n return\n try:\n if ensure_all_users_invoke:\n api_util.AddFunctionIamPolicyBinding(function.name)\n stop_trying_perm_set[0] = True\n elif deny_all_users_invoke:\n stop_trying_perm_set[0] = (\n api_util.RemoveFunctionIamPolicyBindingIfFound(function.name))\n except calliope_exceptions.HttpException:\n stop_trying_perm_set[0] = True\n log.warning('Setting IAM policy failed, try `%s`' %\n _CreateBindPolicyCommand(function_ref))\n\n log_stackdriver_url = [True]\n\n def TryToLogStackdriverURL(op):\n \"\"\"Logs stackdriver URL.\n\n This is for executing in the polling loop, and will stop trying as soon as\n it succeeds at making a change.\n\n Args:\n op: the operation\n \"\"\"\n if log_stackdriver_url[0] and op.metadata:\n metadata = encoding.PyValueToMessage(\n messages.OperationMetadataV1, encoding.MessageToPyValue(op.metadata))\n if metadata.buildName and _BUILD_NAME_REGEX.match(metadata.buildName):\n log.status.Print('\\nFor Cloud Build Logs, visit: %s' %\n _CreateCloudBuildLogURL(metadata.buildName))\n log_stackdriver_url[0] = False\n elif metadata.buildId:\n sd_info_template = '\\nFor Cloud Build Stackdriver Logs, visit: %s'\n log.status.Print(\n sd_info_template %\n _CreateStackdriverURLforBuildLogs(metadata.buildId, _GetProject()))\n log_stackdriver_url[0] = False\n\n if op:\n try_set_invoker = None\n if function.httpsTrigger:\n try_set_invoker = TryToSetInvokerPermission\n api_util.WaitForFunctionUpdateOperation(\n op,\n try_set_invoker=try_set_invoker,\n on_every_poll=[TryToLogStackdriverURL])\n return api_util.GetFunction(function.name)",
"def handler(event, context):\n message = [record['body'] for record in event.get('Records', [])]\n email_record = json.loads(message[0])[\"Records\"][0]\n\n new_email = [(email_record['s3']['bucket']['name'],\n urllib.parse.unquote(email_record['s3']['object']['key']))]\n\n if new_email:\n LOG.info(\"Changed/new object notification received from S3 bucket to the sqs queue\")\n for bucket, s3_key in new_email:\n LOG.info(\"Processing S3 bucket://%s/%s\", bucket, s3_key)\n email_body = S3.Object(bucket, s3_key).get()['Body'].read().decode('utf-8')\n\n # Process PBS job info and push the metadata doc to AWS ES\n _process_pbs_job_info(email_body)\n else:\n LOG.info(\"No new/updated email record found in the S3 bucket\")",
"def handler(event, context):\n if event and \"Records\" in event:\n for record in event[\"Records\"]:\n time_str = time.ctime()\n if \"body\" in record:\n try:\n hasura_request(record[\"body\"])\n except Exception as e:\n print(f\"Start Time: {time_str}\", str(e))\n time_str = time.ctime()\n print(\"Done executing: \", time_str)\n raise_critical_error(\n message=f\"Could not process record: {str(e)}\",\n data=record,\n exception_type=Exception\n )",
"def on_modified(self, event):\n self.log.debug(f\"ManifestFileChangeHandler: file '{event.src_path}' has been modified.\")\n manifest = self.component_cache._load_manifest(filename=event.src_path)\n if manifest: # only update the manifest if there is work to do\n for catalog, action in manifest.items():\n self.log.debug(f\"ManifestFileChangeHandler: inserting ({catalog},{action}) into update queue...\")\n if action == \"delete\":\n # The metadata instance has already been deleted, so we must\n # fabricate an instance that only consists of a catalog name\n catalog_instance = ComponentCatalogMetadata(name=catalog)\n\n else: # cache_action == 'modify':\n # Fetch the catalog instance associated with this action\n catalog_instance = MetadataManager(\n schemaspace=ComponentCatalogs.COMPONENT_CATALOGS_SCHEMASPACE_ID\n ).get(name=catalog)\n\n self.component_cache.update(catalog=catalog_instance, action=action)\n self.component_cache.update_manifest(filename=event.src_path) # clear the manifest",
"def lambda_handler(event, context):\n print(\"Incoming event: {}\".format(event))\n for object in event.get(\"Records\"):\n key = unquote_plus(object[\"s3\"][\"object\"][\"key\"])\n bucket_name = unquote_plus(object[\"s3\"][\"object\"][\"bucket_name\"])\n print(\"Pymage: Resizing {} in bucket: {}\".format(key, bucket_name))\n get_file_and_resize(bucket_name=bucket_name, file_name=key)",
"def _upload_to_gcs(self, files_to_upload):\n # Compose mime_type using file format passed as param\n mime_type = 'application/' + self.export_format['file_format']\n hook = GoogleCloudStorageHook(\n google_cloud_storage_conn_id=self.google_cloud_storage_conn_id,\n delegate_to=self.delegate_to)\n for object, tmp_file_handle in files_to_upload.items():\n hook.upload(self.bucket, object, tmp_file_handle.name, mime_type)",
"def _record_storage_event(metric, value=0):\n command_name = properties.VALUES.metrics.command_name.Get()\n metrics.CustomKeyValue(command_name, 'Storage-' + metric, value)",
"def info(event, context):\n query_string_parameters = event.get('queryStringParameters') or {}\n include_deleted = query_string_parameters.get('deleted') == 'yes'\n include_nonstored = query_string_parameters.get('nonstored') == 'yes'\n LOGGER.debug('File info includes deleted={} includes non-stored={}'.format(include_deleted, include_nonstored))\n file_ids = json.loads(event.get('body'))\n file_ids = file_ids[:runtime_context.QUERY_LIMIT] # limit the number of files queried\n files = FileModel.get_by_ids(file_ids)\n for file in files:\n if not file.get('deleted_at') and file.get('stored_at'): # only return not deleted and stored\n file['url'] = get_presigned_url_for_download(file)\n else:\n if (file.get('deleted_at') and include_deleted) or (not file.get('stored_at') and include_nonstored):\n pass\n else: # remove deleted or non-stored\n files.remove(file)\n return {\n \"statusCode\": 200,\n \"body\": json.dumps(files, cls=utils.DateTimeEncoder)\n }",
"def on_file_changed(self, path):\n\t\tpass",
"def on_modified(self, event):\n \n if not event.is_directory: \n\n file_name = os.path.basename(event.src_path)\n \n if file_name not in self.ignore_files:\n parent = os.path.dirname(event.src_path)\n file_id = list(filter(lambda f: f[\"name\"] == file_name, self.filesystem[parent][\"files\"]))[0][\"id\"]\n self.gapy.update_file(file_id, path=parent)\n self.gapy.logger.info(\"The file {} was modified, the content was updated\".format(file_name, parent))\n print(f\"\\nThe file {file_name} was modified and synchronized\")",
"def log(self, event):\n\n log_message = '{} - {} file: {}'.format(\n datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n event.event_type.capitalize(),\n event.src_path\n )\n\n if hasattr(event, 'dest_path'):\n log_message += ' => {}'.format(event.dest_path)\n\n sys.stdout.write(log_message + '\\n')\n sys.stdout.flush()"
] | [
"0.60732645",
"0.5688646",
"0.5619583",
"0.551703",
"0.53179324",
"0.52507126",
"0.52309644",
"0.5212064",
"0.5203661",
"0.51629466",
"0.5137545",
"0.506098",
"0.505003",
"0.5038273",
"0.50262076",
"0.5013108",
"0.497659",
"0.49158835",
"0.4913968",
"0.487022",
"0.485576",
"0.48541868",
"0.48516524",
"0.48483586",
"0.48469108",
"0.48455134",
"0.48442554",
"0.48379752",
"0.48357537",
"0.48339844"
] | 0.64327574 | 0 |
Test the get_factor_list function and factors generator on a few numbers. | def main():
print("-----------------\n|")
print("| codedrome.com |")
print("| Factorization |")
print("-----------------\n")
numbers_to_factorize = [15,19,25,50,77,99]
print("factorization.get_factor_list\n-----------------------------")
for n in numbers_to_factorize:
factors = factorization.get_factor_list(n)
print("Factors of {}: {}".format(n, factors))
print("\nfactorization.factors (generator)\n---------------------------------")
for n in numbers_to_factorize:
print("Factors of {}: ".format(n), end="")
for f in factorization.factors(n):
print("{} ".format(f), end="")
print("") | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_factors():",
"def primeFactors(number):\n factorlist=[]\n loop=2\n while loop<=number:\n if number%loop==0:\n number/=loop\n factorlist.append(loop)\n else: \n loop+=1\n return factorlist",
"def factor(checknumber):\n if checknumber < 0:\n checknumber *= -1\n factorlist = [-1]\n else:\n factorlist = [1]\n for x in xrange(2, int(math.sqrt(checknumber))+1):\n if checknumber % x == 0:\n factorlist.append(x)\n templist = factorlist\n for x in templist:\n test = checknumber/x \n if test not in factorlist:\n factorlist.append(test)\n return factorlist",
"def get_factors(number):\n\n factors = [1, number]\n\n for i in range(2, int(math.sqrt(number))):\n if number % i == 0:\n factors.extend([i, number / i])\n\n return(factors)",
"def factors(n):\r\n\tif n<0: n=-n # Only deal with positive integers\r\n\tif (is_prime(n)):\r\n\t\treturn [n]\r\n\tfact = factorone(n)\r\n\tif (fact == 1): return \"Unable to factor \"+str(n) # Can't deal with units\r\n\tfacts = factors(n/fact) + factors(fact)\r\n\tfacts.sort()\r\n\treturn facts",
"def setFactors(self, number):\n self.number = number\n length = len(self.primes)\n p = self.primes[:self.closestPrimeIndex(self.primes, self.number**0.5) + 1]\n\n start = clock()\n self.facts = serial_factor(self.number, p)\n print \"Time taken ======================> \", clock() - start\n\n c = 1\n for fact in self.facts:\n c = c * fact\n\n if c != self.number:\n num = self.number / c\n for fact in self.facts:\n while num % fact == 0:\n num = num / fact\n\n if num != 1:\n self.facts.append(num)",
"def prime_factors(num):\n if prime_checker(num):\n return num\n if num > 10^5:\n maxPrime = round(num**0.5) + 1\n else:\n maxPrime = round(num/2)+1\n primelist = prime_generator(maxPrime)\n factors = []\n\n while num > 1 and num not in primelist:\n for prime in primelist:\n if num % prime == 0:\n factors.append(prime)\n num = int(num / prime)\n break\n if not num == 1:\n factors.append(num)\n \n return factors",
"def test_factorization_special_case(self):\n factorization = pauli_word_exp_factorization(1.2, PauliWord(\"ZZIIIIIZZ\"))\n print(factorization)\n self.assertEqual(\n len(factorization),\n 5\n )",
"def factors(number):\n\n if not (isinstance(number, int)):\n raise TypeError(\n \"Incorrect number type provided. Only integers are accepted.\")\n\n factors = []\n for i in range(1, number + 1):\n if number % i == 0:\n factors.append(i)\n return factors",
"def get_factors(num):\n factors = []\n\n # Extend range by 1 to include num\n for i in range(1, num+1):\n if num % i == 0:\n factors.append(i)\n return factors",
"def result_factorization(N,factors):\n if len(factors) !=2:\n print(\"len(factors) != 2\")\n sys.exit()\n\n if N != factors[0] * factors[1]:\n print(\"factors[0]×factors[1] != N @print_factors in ModulesFactorization\")\n sys.exit()\n\n if factors[0] ==1:\n print(\"自明な約数しか見つかりませんでした。\")\n return False\n else:\n print(\"{0}={1}×{2}\".format(N,factors[0],factors[1]))\n return True",
"def find_factors(number):\n \n i = 2\n prod = 1\n factors = []\n sqrt = math.sqrt(number)\n num = number\n \n while i < num:\n div = check_divisbility(number, i)\n if div == 'divisible':\n factors.append(i)\n number /= i\n prod *= i\n recurse = find_factors(number)\n \n #I recurse here because it prevents us wasting time playing with large numbers\n for fac in recurse:\n factors.append(fac)\n number /= fac\n prod *= fac\n #stop if we find a factor greater tha sqrt(number)\n if i >= sqrt:\n break\n #make sure we're not looking once we find all the factors \n if prod == num:\n break\n else:\n if i> sqrt:\n if len(factors)==0:\n factors.append(num)\n prod *= num\n else: \n print i\n recurse = find_factors(number)\n for fac in recurse:\n factors.append(fac)\n prod *= fac\n if prod == num:\n break\n i = i+1\n if prod != num:\n raise ValueError (\"This isn't right\")\n return factors",
"def _factors(n):\n gen = ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)\n return set(sum(gen, []))",
"def find_factors(num):\n factors = set()\n i = 1\n while i*i < num:\n if num % i == 0:\n factors.add(i)\n factors.add(int(num/i))\n i+=1\n factors = list(factors)\n factors.sort()\n return factors",
"def factor(cls, number):\n factors = []\n for prime in cls():\n if prime > number:\n break\n # print 'Checking to see if %d is a factor of %d' % (prime, number)\n # reduce the total iterations\n if prime > math.sqrt(number):\n factors.append(number)\n break\n while not number % prime:\n number /= prime\n factors.append(prime)\n return factors",
"def factorize(number, factors, result=None):\n if result is None:\n result = []\n factor = _max_factor(number, factors)\n amount = _num_factor(number, factor)\n remain = _remainder(number, factor)\n result.append((amount, factor))\n if remain == 0:\n return result\n return factorize(remain, factors, result)",
"def factor(n):\r\n\t# Rewritten to align with SAGE. Previous semantics available as factors(n).\r\n\tif (abs(n) == 1): return \"Unable to factor \"+str(n) # Can't deal with units\r\n\tfactspow = []\r\n\tcurrfact = None\r\n\tfor thefact in factors(n):\r\n\t\tif thefact != currfact:\r\n\t\t\tif currfact != None:\r\n\t\t\t\tfactspow += [(currfact,thecount)]\r\n\t\t\tcurrfact = thefact\r\n\t\t\tthecount = 1\r\n\t\telse:\r\n\t\t\tthecount += 1\r\n\tfactspow += [(thefact,thecount)]\r\n\treturn factspow",
"def _prime_factorization(n):\n factors = []\n f = 2\n # Use trial division to add factors\n while f**2 <= n:\n while (n % f) == 0:\n factors.append(f)\n n //= f\n f += 1\n\n if n > 1:\n factors.append(n)\n\n return factors",
"def factors(self):\n self.assert_sampled()\n return self._factors",
"def factors(n):\n\tif n<0: n=-n # Only deal with positive integers\n\tif (is_prime(n)):\n\t\treturn [n]\n\tfact = factorone(n)\n\tif ((abs(n) == 1) or (n == 0)): raise ValueError('Unable to factor \\\"{0}\\\"'.format(n))\n\tfacts = factors(n//fact) + factors(fact)\n\tfacts.sort()\n\treturn facts",
"def factorize(self,num):\n def sieveOfEratosthenes(N, s): \n prime = [False] * (N+1) \n for i in range(2, N+1, 2): \n s[i] = 2\n for i in range(3, N+1, 2): \n if (prime[i] == False): \n s[i] = i \n for j in range(i, int(N / i) + 1, 2): \n if (prime[i*j] == False): \n prime[i*j] = True\n s[i * j] = i \n\n\n def generatePrimeFactors(N): \n ans=[]\n s = [0] * (N+1) \n sieveOfEratosthenes(N, s) \n curr = s[N] \n cnt = 1\n while (N > 1): \n N //= s[N]\n if (curr == s[N]): \n cnt += 1\n continue\n\n ans.append((str(curr),str(cnt))) \n\n curr = s[N] \n cnt = 1\n return ans\n \n return generatePrimeFactors(num)",
"def FactorInList(N, List):\n a = 1\n b = N \n for num in List:\n if N % num == 0:\n a = num\n b = N//num\n break\n \n return [a, b]",
"def factor(number):\n\tdividing_primes = sieve(number/2 + 1)\n\tfactors = []\n\t\n\twhile number != 1:\t\n\t\tif not dividing_primes:\n\t\t\treturn [number]\n\n\t\tnext_divisor = min(dividing_primes)\n\n\t\tif not number % next_divisor:\n\t\t\tfactors.append(next_divisor)\n\t\t\tnumber /= next_divisor\n\t\telse:\n\t\t\tdividing_primes.remove(next_divisor)\n\n\treturn factors",
"def factors(n: int) -> List[int]:\n k = 1\n while k**2 < n:\n if n % k == 0:\n yield k\n k += 1\n\n k = int(n**(1/2))\n while k > 0:\n if n % k == 0:\n yield n // k\n k -= 1",
"def factors(n):\n f = list(reduce(list.__add__, ([i, n // i] for i in range(1, int(pow(n, 0.5) + 1)) if n % i == 0)))\n return sorted(f)",
"def get_factors(self, triples):\n pass",
"def prime_factors(number):\n factors = []\n\n if number == 0 : return factors\n\n # first round factors by two\n while number % 2 == 0:\n factors.append(2)\n number /= 2\n\n # other rounds goes by odd numbers only (no other even is prime)\n divisor = 3\n while divisor <= number:\n while number % divisor == 0:\n factors.append(divisor)\n number /= divisor\n divisor += 2\n\n return factors",
"def getallprimefactors(n):\n factors = []\n d = 2\n while n > 1:\n while n % d == 0:\n factors.append(d)\n print(n)\n n /= d\n d += 1\n return factors",
"def factor(n: int) -> List[Tuple[int, int]]:\n if n <= 1:\n raise ValueError\n\n factors = list()\n\n ml = 0\n p = 2\n while n % p == 0:\n n //= p\n ml += 1\n if ml > 0:\n factors.append((p, ml,))\n\n p = 3\n while p ** 2 <= n:\n ml = 0\n while n % p == 0:\n n //= p\n ml += 1\n if ml > 0:\n factors.append((p, ml,))\n p += 2\n\n if n > 2:\n factors.append((n, 1,))\n\n return factors",
"def factorize(num):\n factors = []\n while num not in primes_list:\n for prime in primes_list:\n if num % prime == 0:\n factors.append(prime)\n num /= prime\n break\n factors.append(num)\n factors = sorted(factors)\n return factors"
] | [
"0.703959",
"0.6972541",
"0.68969446",
"0.6865352",
"0.6846568",
"0.6835772",
"0.679891",
"0.67738396",
"0.67580175",
"0.6727128",
"0.6691032",
"0.6637499",
"0.6631842",
"0.6576136",
"0.6561167",
"0.65292734",
"0.6512977",
"0.6510949",
"0.6502786",
"0.64898217",
"0.6483006",
"0.6481011",
"0.64776576",
"0.64526725",
"0.6427097",
"0.64071625",
"0.63767254",
"0.6367679",
"0.6362824",
"0.6356194"
] | 0.7025335 | 1 |
Test that we fallback to gecos if there is no displayname | def test_user_no_displayname(dummy_user_dict):
del dummy_user_dict["displayname"]
dummy_user_dict["gecos"] = ["GCOS"]
user = User(dummy_user_dict)
assert user.name == "GCOS" | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_user_no_displayname_no_gcos(dummy_user_dict):\n del dummy_user_dict[\"displayname\"]\n del dummy_user_dict[\"gecos\"]\n dummy_user_dict[\"cn\"] = [\"CN\"]\n user = User(dummy_user_dict)\n assert user.name == \"CN\"",
"def test_user_no_displayname_no_gcos_no_cn(dummy_user_dict):\n del dummy_user_dict[\"displayname\"]\n del dummy_user_dict[\"gecos\"]\n del dummy_user_dict[\"cn\"]\n user = User(dummy_user_dict)\n assert user.name is None",
"def test_get_country_by_geo_location(self):\n pass",
"def test_single_word_exeter(self):\n result = location.lookup_location('Exeter GB')\n\n self.assertEqual(result['country'], 'GB')",
"def test_double_word_coombe_martin(self):\n result = location.lookup_location('Combe Martin GB')\n\n self.assertEqual(result['country'], 'GB')",
"def test_does_not_have_geocode(self):\n name = Name.objects.create(name=\"Test Name\", name_type=Name.PERSONAL)\n assert not name.has_geocode()",
"def species_has_geo(species_output_dict: dict) -> bool:\n if species_output_dict['paths']['geo'] or species_output_dict['paths']['composite']:\n return True\n return False",
"def test_get_name(self):\n provider = GCPLocalProvider()\n self.assertEqual(provider.name(), Provider.PROVIDER_GCP_LOCAL)",
"def test_single_word_swanage(self):\n result = location.lookup_location('Swanage GB')\n\n self.assertEqual(result['country'], 'GB')",
"def displayName(self):\r\n return self.tr(\"PDOK Reverse Geocoder\")",
"def test_has_geocode(self):\n\n lat, lng = 33.210241, -97.148857\n name = Name.objects.create(name=\"Test Name\", name_type=Name.PERSONAL)\n Location.objects.create(belong_to_name=name, longitude=lng,\n latitude=lat)\n assert name.has_geocode()",
"def test_country_name_in_countries(self):\n\t\tcountry_code = get_country_code('Andorra')\n\t\tself.assertEqual(country_code, 'ad')",
"def test_country_name_not_in_countries(self):\n\t\tcountry_code = get_country_code('Venezuela, RB')\n\t\tself.assertEqual(country_code, 've')",
"def test_get_name(self):\n provider = AWSLocalProvider()\n self.assertEqual(provider.name(), Provider.PROVIDER_AWS_LOCAL)",
"def test_get_formatted_location(self):\n\t\tformatted_location = get_formatted_location('seoul', 'south korea')\n\t\tself.assertEqual(formatted_location, 'Seoul, South Korea')",
"def test_city_country(self):\n santiago_chile = get_city_name('santiago', 'chile')\n self.assertEqual(santiago_chile, 'Santiago, Chile')",
"def test_city_country(self):\n formatted_name = make_formatted_name('santiago', 'chile')\n self.assertEqual(formatted_name, 'Santiago, Chile')",
"def test_missingName(self):\n servers = {\n ('1.1.2.3', 53): {\n (b'foo.example.com', A): {\n 'rCode': ENAME,\n },\n },\n }\n resolver = self._getResolver(servers)\n d = resolver.lookupAddress(b'foo.example.com')\n return self.assertFailure(d, DNSNameError)",
"def ValidateDisplayName(display_name):\n if display_name is not None and not display_name:\n raise exceptions.InvalidArgumentException(\n '--display-name',\n 'Display name can not be empty.')",
"def test_triple_word_weston_super_mare(self):\n result = location.lookup_location('Weston Super Mare GB')\n\n self.assertEqual(result['country'], 'GB')",
"def test_single_word_salisbury(self):\n result = location.lookup_location('Salisbury GB')\n\n self.assertEqual(result['country'], 'GB')",
"def test_single_word_boston(self):\n result = location.lookup_location('Boston GB')\n\n self.assertEqual(result['country'], 'GB')",
"def test_city_country(self):\n your_location = location_name(\"lviv\", \"ukraine\")\n self.assertEqual(your_location, \"Lviv, Ukraine\")",
"def test_unknown_device_name(self):\n search_response = SearchResponse()\n assert search_response.device_name == \"UNKNOWN\"",
"def test_city_country(self):\n formatted_name = city_country('santiago', 'chile')\n self.assertEqual(formatted_name, 'Santiago, Chile')",
"def is_hometown(town_name):\n\n\tDC = [\"washington d.c.\", \"dc\", \"washington dc\", \"d.c.\"]\n\n\tif town_name.lower() in DC:\n\t\treturn True\n\telse: \n\t\treturn False",
"def get_valid_geonames():\n return json.load(open(dirpath / \"lci\" / \"geodata.json\", encoding=\"utf-8\"))[\"names\"]",
"def test_geoiplookup(self):\n\n try:\n output = subprocess.check_output('geoiplookup 1.1.1.1', shell=True).decode('utf-8')\n if not 'Cloudflare' in output:\n self.fail('Are your geoip databases in /usr/share/GeoIP/ ???')\n except:\n self.fail('Error when calling geoiplookup')",
"def test_location(self):\n self.assertEqual(self.show.country, None)\n self.assertEqual(self.show.state, None)\n self.assertEqual(self.show.country, None)",
"def test_get_zr_location_profile(self):\n pass"
] | [
"0.60861444",
"0.59474826",
"0.5857862",
"0.57941484",
"0.568906",
"0.5602406",
"0.5574571",
"0.5562333",
"0.55328804",
"0.5530129",
"0.5523503",
"0.5471552",
"0.5394567",
"0.5376542",
"0.5328532",
"0.5319873",
"0.5316677",
"0.53014374",
"0.52880996",
"0.5282158",
"0.5272012",
"0.5253533",
"0.522443",
"0.5198525",
"0.5192501",
"0.51743144",
"0.5165376",
"0.515884",
"0.51372004",
"0.5131121"
] | 0.6004263 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.