query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Broadcasts the test signs stop command All signs connected to the serial port will stop the test sequence.
def stop_test_signs(self): self._write(TestSignsStopPacket())
[ "def _stop_sequence(self):\n self.logger.info(\"Received stop command, executing stop sequence\")\n try:\n self.es.stop()\n self.logger.info(\"Sending stop command to relay\")\n try:\n self.logger.info(\"Connecting to relay socket at %s, port %s\" %\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends an image to a sign to be displayed
def draw_image(self, image_data: np.array, sign_name: str = None): if sign_name is None: if len(self.signs) == 1: # Get the only sign sign = next(iter(self.signs.values())) else: raise ValueError( "Cannot determine which...
[ "def step_send_picture(self):\n\n s = self.find('org.thoughtcrime.securesms:id/attach_button')\n with self.mark(self.delivered_suffix('send_image_no_caption')):\n self.click(s)\n self.click(\n \"//android.widget.FrameLayout[@index='{0}']\"\n \"/andro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a call to the API
def _call(self, method, url, params): if not url.startswith('http'): url = self.root + url headers = self._auth_headers() headers['Content-Type'] = 'application/json' r = self._session.request(method, url, headers=headers, ...
[ "def call_api(self):\n\n request = (requests.get(self.url, headers=self.headers))\n print(f\"\\nStatus code: {request.status_code}\")\n\n # Process the request\n self._process_data(request)", "def _execApiCall(headers, params, method_name,\r\n domain='ma.gnolia.com',\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print the distribution of labels in a data frame
def show_label_distribution(data): stats = [0, 0, 0, 0] for index, row in data.iterrows(): if int(row['label']) == 0: stats[0] = stats[0] + 1 elif int(row['label']) == 1: stats[1] = stats[1] + 1 elif int(row['label']) == 2: stats[2] = stats[2] + 1 ...
[ "def display_labels(self):\n\n nsubj = len(self.infiles)\n\n print('-- final label table (length %d):' % len(self.labels))\n for label in self.labels:\n nv = self.maxcounts[label]\n if nv == 1: cstr = '%3d val' % nv\n else: cstr = '%3d vals' % nv\n nv = self.subj...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read Cartesian grid HDF5 file.
def read_grid(filename_grid, dim=2, slc=None): ## get shape and slice fid = h5py.File(filename_grid, 'r') if dim==2: varnames = ['x', 'y', 'ep'] if slc is None: slc = np.s_[0,:,:] if dim==3: varnames = ['x', 'y', 'z', 'ep'] if slc is None: slc = np.s_[:,:,:] dset = f...
[ "def ReadGrid(self, grdfile):\n nc = Dataset(grdfile,'r')\n \n self.xv = nc.variables['xv'][:]\n self.yv = nc.variables['yv'][:]\n self.xp = nc.variables['xp'][:]\n self.yp = nc.variables['yp'][:]\n self.xe = nc.variables['xe'][:]\n self.ye = nc.variables['ye...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configures logging. Commandline arguments ``v`` and ``q`` set both the code log file and what streams to stdout. The ``v`` flag turns on debug level, and ``q`` sets it to info level. The math logger will always be set to debug level.
def logging_config(args): # Any handlers from a basicConfig, which we will reconfigure. for handler in logging.root.handlers: logging.root.removeHandler(handler) level = logging.INFO - 10 * args.verbose + 10 * args.quiet # The command-line logging level specifies what goes to stderr. root_h...
[ "def setup_logging():\r\n # pylint: disable=W0603\r\n global logging_ready\r\n if logging_ready:\r\n return\r\n if sys.argv.count(\"-v\") > 2:\r\n logging.basicConfig(level=logging.DEBUG)\r\n elif sys.argv.count(\"-v\") == 2:\r\n logging.basicConfig(level=logging.INFO)\r\n els...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the vacuum state is correct.
def test_vacuum_state(self, hbar, tol): modes = 3 means, cov = symplectic.vacuum_state(modes, hbar=hbar) assert np.allclose(means, np.zeros([2 * modes]), atol=tol, rtol=0) assert np.allclose(cov, np.identity(2 * modes) * hbar / 2, atol=tol, rtol=0)
[ "async def test_vacuum(hass: HomeAssistant, mock_account: MagicMock) -> None:\n ent_reg = er.async_get(hass)\n\n ent_reg.async_get_or_create(\n PLATFORM_DOMAIN,\n DOMAIN,\n VACUUM_UNIQUE_ID,\n suggested_object_id=VACUUM_ENTITY_ID.replace(PLATFORM_DOMAIN, \"\"),\n )\n ent_reg_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the squeeze operator is symplectic
def test_symplectic(self, tol): r = 0.543 phi = 0.123 S = symplectic.squeezing(r, phi) # the symplectic matrix O = np.array([[0, 1], [-1, 0]]) assert np.allclose(S @ O @ S.T, O, atol=tol, rtol=0)
[ "def test_is_symplectic():\n theta = np.pi / 6\n r = np.arcsinh(1.0)\n phi = np.pi / 8\n S = symplectic.rotation(theta)\n assert symplectic.is_symplectic(S)\n S = symplectic.squeezing(r, theta)\n assert symplectic.is_symplectic(S)\n S = symplectic.beam_splitter(theta, phi)\n assert symple...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the squeezing symplectic transform.
def test_squeezing(self, tol): r = 0.543 phi = 0.123 S = symplectic.squeezing(r, phi) out = S @ S.T # apply to an identity covariance matrix rotation = np.array( [[np.cos(phi / 2), -np.sin(phi / 2)], [np.sin(phi / 2), np.cos(phi / 2)]] ) expec...
[ "def test_symplectic(self, tol):\n r = 0.543\n phi = 0.123\n S = symplectic.squeezing(r, phi)\n\n # the symplectic matrix\n O = np.array([[0, 1], [-1, 0]])\n\n assert np.allclose(S @ O @ S.T, O, atol=tol, rtol=0)", "def test_squeezing_no_phi(self, tol):\n r = 0.543...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the squeezing symplectic transform without specifying phi
def test_squeezing_no_phi(self, tol): r = 0.543 phi = 0.0 S = symplectic.squeezing(r) out = S @ S.T # apply to an identity covariance matrix rotation = np.array( [[np.cos(phi / 2), -np.sin(phi / 2)], [np.sin(phi / 2), np.cos(phi / 2)]] ) expec...
[ "def test_symplectic(self, tol):\n r = 0.543\n phi = 0.123\n S = symplectic.squeezing(r, phi)\n\n # the symplectic matrix\n O = np.array([[0, 1], [-1, 0]])\n\n assert np.allclose(S @ O @ S.T, O, atol=tol, rtol=0)", "def test_squeezing(self, tol):\n r = 0.543\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test multimode version gives symplectic matrix
def test_symplectic_multimode(self, tol): r = [0.543] * 4 phi = [0.123] * 4 S = symplectic.squeezing(r, phi) # the symplectic matrix O = symplectic.sympmat(4) assert np.allclose(S @ O @ S.T, O, atol=tol, rtol=0)
[ "def test_has_matrix_true_via_factor_has_matrix(self):\n\n sprod_op = SProd(0.7, qml.RZ(0.23, wires=\"a\"))\n assert sprod_op.has_matrix is True", "def test_modes_from_matrix():\n\n # Calculate modes and eigenvalues from matrix\n pmodes, svals, vh = np.linalg.svd(LUVOIR_INTENSITY_MATRIX_SMALL,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the two mode squeezing symplectic transform decomposes correctly.
def test_decompose(self, tol): r = 0.543 phi = 0.123 S = symplectic.two_mode_squeezing(r, phi) # test that S = B^\dagger(pi/4, 0) [S(z) x S(-z)] B(pi/4) # fmt:off B = np.array([[1, -1, 0, 0], [1, 1, 0, 0], [0, 0, 1, -1], [0, 0, 1, 1]])/np.sqrt(2) Sq1 = np.array(...
[ "def test_exact_two_qubit_cnot_decompose_paulis(self):\n unitary = Operator.from_label(\"XZ\")\n self.check_exact_decomposition(unitary.data, two_qubit_cnot_decompose)", "def test_sprod_decomposition(self):\n op = Exp(qml.s_prod(3, qml.PauliX(0)), 1j)\n assert op.has_decomposition", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that an interferometer returns correct symplectic
def test_interferometer(self, tol): # fmt:off U = np.array([[0.83645892-0.40533293j, -0.20215326+0.30850569j], [-0.23889780-0.28101519j, -0.88031770-0.29832709j]]) # fmt:on S = symplectic.interferometer(U) expected = np.block([[U.real, -U.imag], [U.imag, U....
[ "def test_ion_thermal_speed():\n\n assert ion_thermal_speed(T_i).unit == u.m/u.s\n\n # The NRL Plasma Formulary uses a definition of the ion thermal\n # speed that differs by a factor of sqrt(2).\n assert np.isclose(ion_thermal_speed(1*u.MK, ion='p').si.value,\n 128486.56960876315)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the interferometer is symplectic
def test_symplectic(self, tol): # random interferometer # fmt:off U = np.array([[-0.06658906-0.36413058j, 0.07229868+0.65935896j, 0.59094625-0.17369183j, -0.18254686-0.10140904j], [0.53854866+0.36529723j, 0.61152793+0.15022026j, 0.05073631+0.32624882j, -0.17482023-0.2010377...
[ "def test_interferometer(self, tol):\n # fmt:off\n U = np.array([[0.83645892-0.40533293j, -0.20215326+0.30850569j],\n [-0.23889780-0.28101519j, -0.88031770-0.29832709j]])\n # fmt:on\n\n S = symplectic.interferometer(U)\n expected = np.block([[U.real, -U.imag],...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that an interferometer returns correct symplectic for a 5050 beamsplitter
def test_50_50_beamsplitter(self, tol): U = np.array([[1, -1], [1, 1]]) / np.sqrt(2) S = symplectic.interferometer(U) B = np.array([[1, -1, 0, 0], [1, 1, 0, 0], [0, 0, 1, -1], [0, 0, 1, 1]]) / np.sqrt(2) assert np.allclose(S, B, atol=tol, rtol=0)
[ "def test_beamsplitter(self, tol):\n theta = 0.98\n phi = 0.41\n U = symplectic.beam_splitter(theta, phi)\n S = symplectic.interferometer(U)\n expected = np.block([[U.real, -U.imag], [U.imag, U.real]])\n np.allclose(S, expected, atol=tol, rtol=0)", "def test_interferomete...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that an interferometer returns correct symplectic for an arbitrary beamsplitter
def test_beamsplitter(self, tol): theta = 0.98 phi = 0.41 U = symplectic.beam_splitter(theta, phi) S = symplectic.interferometer(U) expected = np.block([[U.real, -U.imag], [U.imag, U.real]]) np.allclose(S, expected, atol=tol, rtol=0)
[ "def test_50_50_beamsplitter(self, tol):\n U = np.array([[1, -1], [1, 1]]) / np.sqrt(2)\n\n S = symplectic.interferometer(U)\n B = np.array([[1, -1, 0, 0], [1, 1, 0, 0], [0, 0, 1, -1], [0, 0, 1, 1]]) / np.sqrt(2)\n\n assert np.allclose(S, B, atol=tol, rtol=0)", "def testWaveguideSplit(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that a rotation returns the correct symplectic for an abritrary angle
def test_rotation(self, tol): theta = 0.98 S = symplectic.rotation(theta) expected = np.block([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) np.allclose(S, expected, atol=tol, rtol=0)
[ "def test_calc_rotation(self):\n t = AioBaseTurtle()\n t.speed(speed=2)\n orient, steps, delta = t._calc_rotation(120)\n self.assertEqual(steps, 21)\n self.assertAlmostEqual(delta, 120.0 / 21.0)\n self.assertAlmostEqual(orient[0], math.cos(math.radians(120)))\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the loss channel on a TMS state corresponds to a beamsplitter acting on the mode with loss and an ancilla vacuum state
def test_TMS_against_interferometer(self, hbar, tol): r = 0.543 phi = 0.432 T = 0.812 S = symplectic.two_mode_squeezing(r, phi) cov = S @ S.T * (hbar / 2) # perform loss _, cov_res = symplectic.loss(np.zeros([4]), cov, T, mode=0, hbar=hbar) # create a t...
[ "def test_mlag_status(device, actual, testcase):\n has_state = actual['state']\n exp_state = testcase['expected']['state']\n\n is_up = (exp_state == 'up' and has_state == 'active')\n has_neg_st = actual['negStatus']\n is_neg = has_neg_st == \"connected\"\n\n if is_up and is_neg:\n return Tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the loss channel on a displaced state corresponds to a beamsplitter acting on the mode with loss and an ancilla vacuum state
def test_displaced_loss_against_interferometer(self, hbar, tol): T = 0.812 alpha = np.random.random(size=[2]) + np.random.random(size=[2]) * 1j mu = np.concatenate([alpha.real, alpha.imag]) # perform loss mu_res, _ = symplectic.loss(mu, np.identity(4), T, mode=0, hbar=hbar) ...
[ "def test_coherent_state_has_photons(self, setup_eng, hbar):\n shots = 100\n eng, prog = setup_eng(1)\n alpha = 2\n with prog.context as q:\n ops.Coherent(alpha) | q[0]\n ops.MeasureFock() | q[0]\n state = eng.run(prog).state\n samples = np.array(eng.r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test loss on part of a thermal state
def test_loss_thermal_state(self, hbar, tol): nbar = np.array([0.4532, 0.123, 0.432]) T = 0.54 mu = np.zeros([2 * len(nbar)]) cov = np.diag(2 * np.tile(nbar, 2) + 1) * (hbar / 2) res = symplectic.loss(mu, cov, T, mode=1, hbar=hbar) # the loss reduces the fractional mea...
[ "def test_non_zero_loss(self):\n # Reset models.\n self.model.load_state_dict(self.initial_model_dict)\n self.actor_model.load_state_dict(self.initial_actor_model_dict)\n\n polybeast.learn(*self.learn_args)\n\n self.assertNotEqual(self.stats[\"total_loss\"], 0.0)\n self.ass...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test that error is raised when length of modes array is incorrect
def test_modes_length(self): with pytest.raises(ValueError, match="length of modes must match the shape of T"): symplectic.expand_passive(np.ones((3, 3)), [0, 1, 2, 3, 4], 8)
[ "def _check_modes(samples, modes):\n num_modes = samples.shape[1]\n flattened_sequence_indices_msg = (\n \"The input modes need to be specified as a flattened sequence of non-negative integers!\"\n )\n\n modes = np.array(modes)\n\n # Extracting non index modes while also checking that the type...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that applying squeezing and interferometers to a four mode circuit, followed by applying the inverse operations, return the state to the vacuum
def test_inverse_ops_cancel(self, hbar, tol): # the symplectic matrix O = np.block([[np.zeros([4, 4]), np.identity(4)], [-np.identity(4), np.zeros([4, 4])]]) # begin in the vacuum state mu_init, cov_init = symplectic.vacuum_state(4, hbar=hbar) # add displacement alpha ...
[ "def test_circuit_mod_5_4(self):\n operations = [\n qml.PauliX(wires=4),\n qml.Hadamard(wires=4),\n qml.CNOT(wires=[3, 4]),\n qml.CNOT(wires=[0, 4]),\n qml.T(wires=4),\n qml.CNOT(wires=[3, 4]),\n qml.adjoint(qml.T)(wires=4),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that the matrices generated in the symplectic module are indeed symplectic
def test_is_symplectic(): theta = np.pi / 6 r = np.arcsinh(1.0) phi = np.pi / 8 S = symplectic.rotation(theta) assert symplectic.is_symplectic(S) S = symplectic.squeezing(r, theta) assert symplectic.is_symplectic(S) S = symplectic.beam_splitter(theta, phi) assert symplectic.is_symple...
[ "def test_symplectic_multimode(self, tol):\n r = [0.543] * 4\n phi = [0.123] * 4\n S = symplectic.squeezing(r, phi)\n\n # the symplectic matrix\n O = symplectic.sympmat(4)\n\n assert np.allclose(S @ O @ S.T, O, atol=tol, rtol=0)", "def test_symplectic(self, tol):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks the correctness of the Autonne decomposition function
def test_autonne(n, datatype, svd_order): if datatype is np.complex128: A = np.random.rand(n, n) + 1j * np.random.rand(n, n) if datatype is np.float64: A = np.random.rand(n, n) A += A.T r, U = symplectic.autonne(A, svd_order=svd_order) assert np.allclose(A, U @ np.diag(r) @ U.T) ...
[ "def test_decomposition_undefined(self):\n with pytest.raises(qml.operation.DecompositionUndefinedError):\n MyOp.compute_decomposition(wires=[1])\n with pytest.raises(qml.operation.DecompositionUndefinedError):\n op.decomposition()", "def test_csendes(self):\n fun = get_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the change of basis function applied to vectors. This function converts from xp to symmetric ordering, and vice versa.
def test_means_changebasis(self): means_xp = np.array([1, 2, 3, 4, 5, 6]) means_symmetric = np.array([1, 4, 2, 5, 3, 6]) assert np.all(symplectic.xxpp_to_xpxp(means_xp) == means_symmetric) assert np.all(symplectic.xpxp_to_xxpp(means_symmetric) == means_xp)
[ "def test_functional_inverse(self, dim):\n M = np.random.rand(dim, dim)\n assert np.all(M == symplectic.xxpp_to_xpxp(symplectic.xpxp_to_xxpp(M)))\n assert np.all(M == symplectic.xpxp_to_xxpp(symplectic.xxpp_to_xpxp(M)))\n\n v = np.random.rand(dim)\n assert np.all(v == symplectic.x...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test correct error is raised when a nonsquare matrix is passed
def test_change_basis_raises_not_square(self, fun): A = np.random.rand(4, 6) with pytest.raises(ValueError, match="The input matrix is not square"): fun(A)
[ "def _check_square(matrix):\n if matrix.ndim != 2 or (matrix.shape[0] != matrix.shape[-1]):\n raise ValueError(\n f\"Expected a square matrix, got array of shape {matrix.shape}.\"\n )", "def test_difference_matrix_fail():\n with pytest.raises(ValueError):\n _algorithm_setup.d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that xxpp_to_xpxp is the inverse of xpxp_to_xxpp and viceversa
def test_functional_inverse(self, dim): M = np.random.rand(dim, dim) assert np.all(M == symplectic.xxpp_to_xpxp(symplectic.xpxp_to_xxpp(M))) assert np.all(M == symplectic.xpxp_to_xxpp(symplectic.xxpp_to_xpxp(M))) v = np.random.rand(dim) assert np.all(v == symplectic.xxpp_to_xpxp...
[ "def test_exact_two_qubit_cnot_decompose_paulis(self):\n unitary = Operator.from_label(\"XZ\")\n self.check_exact_decomposition(unitary.data, two_qubit_cnot_decompose)", "def is_opposite(self, p1, p2):\n x1, y1 = p1\n x2, y2 = p2\n return (x1 == x2 and y1 == -y2 % self.module)",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When a message arrives on the servicebus, send a trigger to IoT Hub to start the fan for that device.
def main(msg: func.ServiceBusMessage): # Extract the method into a dictionary msg_dict = json.loads(msg.get_body().decode("utf-8")) logging.info(f"Python ServiceBus queue trigger processed message: {msg_dict}") # Enable a connection with the IoT Hub. The connectionstring for the IoT Hub #...
[ "def handleMessage_started(self, message):\n self.eventbus.publish(MarathonStartedEvent())", "def doTrigger(self, message):\n try:\n for address in self.UDPlist:\n self.sock.sendto(bytes(message, \"utf-8\"), (address, UDP_PORT))\n except socket.error:\n print ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a Git commandline, setting its working tree to `workTree`, and git directory to `gitDir`, and then appends `subcommand`.
def prepareGitCommand(self, workTree, subcommand, gitDir): absWorkTree = self.__chroot.getDirectory() + workTree absGitDir = self.__chroot.getDirectory() + gitDir command = "git --git-dir=%s --work-tree=%s " % (absGitDir, absWorkTree) command += subcommand return command
[ "def git(*args, **kwargs):\n kwargs['cwd'] = repodir\n args = ['git'] + list(args)\n return Cmd(*args, **kwargs)", "def _run_git(repo, command):\n return _run(\"git --git-dir=\" + repo + \" \" + command)", "def __git(self, command, args=None, logCommand=False, **kwargs):\n parts = [\"git\"]\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a Git 'archive' subcommand with autodetected format. If outputFilePath is None, format will be tar, and output will be stdout.
def makeArchiveGitSubcommand(self, prefix, revision=u"HEAD", outputFilePath=None): command = "archive --prefix=%s/ %s " command = command % (prefix, revision) if outputFilePath is not None: command += " -o %s" % outputFilePath return command
[ "def command_archive(self):\n from time import strftime\n\n required_arguments = {\n 'nice': self.BINARY_PATHS['nice'],\n 'tar': self.BINARY_PATHS['tar'],\n 'nice_value': self.NICE_VALUE,\n 'archive_filename': os.path.join(self.env['awd'],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Git complains if you don't set 'user.name' and 'user.email' config parameters. This method checks if they are set, and in case they aren't, set them.
def checkGitUserConfig(self, workTree, gitDir): confParams = {"user.email": "obslight@example.com", "user.name": "OBS Light"} for param, value in confParams.iteritems(): cmd = self.prepareGitCommand(workTree, "config " + param, gitDir) res = self.__subprocess(cmd, stdout=True, no...
[ "def ensure_config():\n subprocess.check_output(['git', 'config', 'user.email'])", "def setup_git_config(self, cwd=None):\n if self.args.get(\"git_email\"):\n run_command(\n [\"git\", \"config\", \"user.email\", self.args.get(\"git_email\")],\n dry_run=self.args....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns state table dynamodb table resource
def state_table(self): if self._state_table is None: dynamodb = boto3.resource("dynamodb") self._state_table = dynamodb.Table(self._table_name) add_retry_methods_to_resource(self._state_table, ["get_item", "put_item"], context=self._context) return self._state_table
[ "def get_dynamo_table(table_name):\n dynamodb = boto3.resource(\"dynamodb\")\n table = dynamodb.Table(table_name)\n return table", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n defined_columns: Optional[pulumi.Inp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the desired state for the specified account and service
def load(self, account, region): self._dirty = False self._state_info = {} self._current_account_region = "{}:{}".format(account, region) # get single row from dynamoDB try: resp = self.state_table.get_item_with_retries(Key={ InstanceStates.INSTANCE_T...
[ "def load_account(self):\n pass", "def asl_service_states():\n if resource_type == \"states\" and resource == \"startExecution\":\n asl_service_states_startExecution()\n else:\n asl_service_InvalidService()", "def test_get_account_from_state(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the state of an instance
def delete_instance_state(self, instance_id): if instance_id in self._state_info: del self._state_info[instance_id] if instance_id in self._instances_to_purge: self._instances_to_purge.remove(instance_id) self._dirty = True
[ "def clear(self, instance):\n if instance.instance_key in self.state:\n del self.state[instance.instance_key]\n\n # if the file exists, try to delete it.\n if os.path.isfile(instance.file_location):\n try:\n os.remove(instance.file_location)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stores the instance state information to the dynamodb table if it has changed
def save(self): if self._dirty: # key and timestamp data = { InstanceStates.INSTANCE_TABLE_NAME: self._service, InstanceStates.INSTANCE_TABLE_ACCOUNT_REGION: self._current_account_region, InstanceStates.INSTANCE_TABLE_TIMESTAMP: Decimal(tim...
[ "def _update_state(context, node, instance, state):\n values = {'task_state': state}\n if not instance:\n values['instance_uuid'] = None\n values['instance_name'] = None\n db.bm_node_update(context, node['id'], values)", "def _write_to_db(self, instance: DBModelInstance) -> None:\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes instance id's from the table that have been terminated or not being processed by the scheduler. This code contains workaround for instances not being returned by describe_instances when changing state When an instance is not listed it is marked for removal at next cleanup if it is not found again
def cleanup(self, instances): # cleanup only if the last cleanup was more than a the configured interval ago if (Decimal(time.time()) - Decimal(self._timestamp)) > InstanceStates.cleanup_interval: self._logger.info(INF_CLEANING) self._timestamp = time.time() self._dir...
[ "def terminate_preemptible_instances(self, context, instances):\n # NOTE(aloga): we should not delete them directly, but probably send\n # them a signal so that the user is able to save her work.\n elevated = context.elevated()\n for instance in instances:\n LOG.info(_LI(\"Del...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Look up a FQN in a mapper, logging all nonImportError exceptions and converting them to ImportErrors.
def lookupWithMapper(mapper, fqn): try: return mapper.lookup(fqn) except ImportError, e: raise e except: print "Error raised by Exocet mapper while loading %r" % (fqn) traceback.print_exc() raise ImportError(fqn)
[ "def get_import_error_sugg(type_, value, frame):\n assert issubclass(type_, ImportError)\n assert len(value.args) == 1\n error_msg, = value.args\n match = re.match(NOMODULE_RE, error_msg)\n if match:\n module_str, = match.groups()\n return get_module_name_suggestion(module_str)\n mat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a proxy for a module object, overriding some of its attributes with replacement objects.
def proxyModule(original, **replacements): class _ModuleProxy(object): def __getattribute__(self, name): if name in replacements: return replacements[name] else: return getattr(original, name) def __repr__(self): return "<Proxy for %r: %s...
[ "def replaceModule(proxy, mod):\n for e in gc.get_referrers(proxy):\n if isinstance(e, dict):\n for k, v in e.iteritems():\n if v is proxy:\n e[k] = mod", "def enable_module_properties():\n name = sys._getframe(1).f_globals['__name__']\n module = sys.mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a generator based on a ResNet18 model.
def genresnet18(**kwargs): return Generator(resnetblocks.EresNetBasicBlock, resnetblocks.DresNetBasicBlock, [2, 2, 2, 2], **kwargs)
[ "def resnext18( **kwargs):\n model = ResNeXt(BasicBlock, [2, 2, 2, 2], **kwargs)\n return model", "def resnet18():\n model = ResNet18(BasicBlock, [2, 2, 2, 2])\n #if pretrained:\n #model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))\n return model", "def resnet18(pretrained=F...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a discriminator based on a ResNet101 model decoder.
def disresnet101(**kwargs): return Discriminator(resnetblocks.DresNetBottleneck, [3, 4, 23, 3], **kwargs)
[ "def build_discriminator(inputs):\n kernel_size = 5\n layer_filters = [32, 64, 128, 256]\n\n x = inputs\n for filters in layer_filters:\n if filters == layer_filters[-1]:\n strides = 1\n else:\n strides = 2\n x = LeakyReLU(alpha=0.2)(x)\n x = Conv2D(filt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a discriminator based on a ResNet152 model decoder.
def disresnet152(**kwargs): return Discriminator(resnetblocks.DresNetBottleneck, [3, 8, 36, 3], **kwargs)
[ "def disresnet101(**kwargs):\n return Discriminator(resnetblocks.DresNetBottleneck, [3, 4, 23, 3], **kwargs)", "def build_discriminator(inputs):\n kernel_size = 5\n layer_filters = [32, 64, 128, 256]\n\n x = inputs\n for filters in layer_filters:\n if filters == layer_filters[-1]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the model using the parameters (and their ranges) specified in the param_dict input. Features and classes are used to fit the model for testing the accuracy score. Cross validation is used for splitting the data throughout the grid search.
def test_k_models(param_dict, features, classes, cross_val=4): assert type(param_dict) == dict model = GridSearchCV(KNeighborsClassifier(), param_dict, cv=cross_val) model.fit(features, classes) return list(model.best_params_.values())[0]
[ "def fit(train_data, train_target):\r\n for name in models.keys():\r\n est = models[name]\r\n est_params = params2[name]\r\n gscv = GridSearchCV(estimator=est, param_grid=est_params, cv=5)\r\n gscv.fit(train_data, train_target)\r\n print(\"best parameter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find module and determine __all__. Return None if the module is a C module. Return (module_path, __all__) if Python module. Raise an exception or exit if failed.
def find_module_path_and_all(module: str, pyversion: Tuple[int, int], no_import: bool, search_path: List[str], interpreter: str) -> Optional[Tuple[str, Optional[List[st...
[ "def find_import(self, module_name: str) -> Tuple[Optional[str], bool]:\n module_name_split = module_name.split(\".\")\n for searchdir in self.options.pythonpath:\n path = path_utils.join(searchdir, *module_name_split)\n # See if this is a directory with a \"__init__.py\" defined.\n # (These al...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The list of required import lines (as strings with python code)
def import_lines(self) -> List[str]: result = [] # To summarize multiple names imported from a same module, we collect those # in the `module_map` dictionary, mapping a module path to the list of names that should # be imported from it. the names can also be alias in the form 'original ...
[ "def _get_imported_list_from_line(line):\n pattern = re.compile(r'\\s*importScripts\\((.*)\\)')\n m = pattern.match(line)\n if not m:\n raise Exception('Parse importScripts error.')\n return [name.translate(None, '\\' \"') for name in m.group(1).split(',')]", "def getImportL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True for things that look like type expressions Used to know if assignments look like typealiases
def is_type_expression(self, expr: Expression, top_level: bool=True) -> bool: # Assignment of TypeVar(...) are passed through if (isinstance(expr, CallExpr) and isinstance(expr.callee, NameExpr) and expr.callee.name == 'TypeVar'): return True elif isin...
[ "def _assigns_typealias(node: nodes.NodeNG | None) -> bool:\n inferred = utils.safe_infer(node)\n if isinstance(inferred, nodes.ClassDef):\n if inferred.qname() == \".Union\":\n # Union is a special case because it can be used as a type alias\n # or as a type a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a name to be imported from typing, unless it's imported already. The import will be internal to the stub.
def add_typing_import(self, name: str) -> None: self.import_tracker.require_name(name)
[ "def addModule(self, name):\n if name in self.needed_modules: return\n self.needed_modules[name] = True #avoid circular references\n\n module = self.moduleResolver.find(name)\n ast = ast.parse(module.getContent(), module.getPath(), 'exec').body\n self.needed_modules[name] = ImportOneModule(self.getMo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a line of text to the import section, unless it's already there.
def add_import_line(self, line: str) -> None: if line not in self._import_lines: self._import_lines.append(line)
[ "def insertLicense (\r\n\r\n self,\r\n text = None\r\n ) :\r\n\r\n if utilities.isEmpty( text ) : text = \"\"\r\n\r\n # builds the text of import lines\r\n \r\n licenseText = \"\"\r\n \r\n for line in self.licenseLine...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Are we processing the top level of a file?
def is_top_level(self) -> bool: return self._indent == ''
[ "def is_toplevel(self):\n return self.srcnode == self.path", "def is_toplevel(self):\n return self.srcnode == self.path", "def is_input_file(self):\r\n return self.depth == 0", "def is_input_file(self):\n return self.depth == 0", "def isMainFile(filename,jobOrder):\n # drop the ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Has this name been recorded previously?
def is_recorded_name(self, name: str) -> bool: return self.is_top_level() and name in self._toplevel_names
[ "def hasname(self):\n\t\treturn self.name is not None", "def is_named(self):\n return self._name != \"\"", "def is_retired(self):\n if str.__str__(self) in UID_dictionary:\n return bool(UID_dictionary[self][3])\n\n return False", "def is_saved(self):\n last_path = self.__key...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find checkpoint files based on its max steps. is_outdir indicates whether find from outdir or modeldir. note that outdir generated from train and eval copy them to modeldir.
def _find_train_ckptfiles(path, is_delete): # if not exists(path): # return None, -1 steps = [int(f[len(ckpt_prefix):-5]) for f in os.listdir(path) if f[:len(ckpt_prefix)] == ckpt_prefix and f[-5:] == '.meta'] if len(steps) == 0: if is_delete: raise FileNotFoundError...
[ "def checkpoints_dir(self, model):\n return os.path.join(self.work_dir(), 'checkpoints', model)", "def find_last(self):\n # Get directory names. Each directory corresponds to a model\n dir_names = next(os.walk(self.model_dir))[1]\n key = self.config.NAME.lower()\n dir_names = fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get model files based on steps
def _get_model_files(steps, path): if not isinstance(steps, list): steps = [steps] model_files = [] for step in steps: model_pref = ckpt_prefix + str(step) model_files.extend([f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and f[:len(...
[ "def _get_model_list(self):\n return [os.path.join(self.model_dir, f) for f in os.listdir(self.model_dir) if f.endswith(self.MODEL_EXT)]", "def _find_train_ckptfiles(path, is_delete):\n # if not exists(path):\n # return None, -1\n steps = [int(f[len(ckpt_prefix):-5]) for f in os.listdir(path)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy checkpoints from logdir to modeldir
def _copy_ckpt_to_modeldir(modeldir, logdir): files, max_step = _find_train_ckptfiles(logdir, False) _, cur_max_step = _find_train_ckptfiles(modeldir, False) if cur_max_step == max_step: raise FileNotFoundError('No new ckpt. cur_max_step: %s, max_step: %s.' % (cur_max...
[ "def move_checkpoint_to_model_directory(config: Config) -> None:\n\n # Find the only existing checkpoint\n directory: str = config.model_config.get_model_dir()\n print('Looking in this directory:', directory)\n checkpoints: List[str] = os.listdir(directory)\n print('Found the following checkpoints (a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test all expected versioned base URLs responds with 200 This depends on the routers for each kind of server.
def test_versioned_base_urls(client, index_client, server: str): try: import simplejson as json except ImportError: import json from optimade.server.routers.utils import BASE_URL_PREFIXES clients = { "regular": client, "index": index_client, } valid_endpoints =...
[ "def test_api_versioning(self):\n # TODO: Test with a more simple SODAR API view once implemented\n\n response = self.client.get(\n reverse(\n 'projectroles:api_remote_get',\n kwargs={'secret': REMOTE_SITE_SECRET},\n ),\n HTTP_ACCEPT='{};v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lowercase and remove quotes from a TensorFlow string.
def normalize_text(text): text = tf.strings.lower(text) text = tf.strings.regex_replace(text, "'(.*)'", r"\1") return text
[ "def normalize_text(text):\n text = tf.strings.lower(text)\n text = tf.strings.regex_replace(text,\"'(.*)'\", r\"\\1\")\n return text", "def normalize_text(text):\n text = tf.strings.lower(text)\n #text = tf.strings.regex_replace(text, br\"\\\\n\", b\"\\n\")\n #text = tf.strings.rege...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a flavorid not in the DB
def _generate_flavorid(self): nonexistent_flavor = 2700 flavor_ids = [value["id"] for key, value in instance_types.get_all_types().iteritems()] while nonexistent_flavor in flavor_ids: nonexistent_flavor += 1 else: return nonexistent_flavor
[ "def is_valid_db_flavor(cdb, id):\n try:\n cdb.get_flavor(id)\n return True\n except:\n return False", "def validate_flavor(cli, flavor):\n\n if flavor is None:\n return\n flavor_list = cli.nova().flavors.list()\n for f in flavor_list:\n if f.name == flavor or f.id == flavor:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure instance types raises InvalidInput for invalid characters
def test_instance_type_create_with_special_characters(self): name = "foo.bar!@#$%^-test_name" flavorid = "flavor1" self.assertRaises(exception.InvalidInput, instance_types.create, name, 256, 1, 120, 100, flavorid)
[ "def test_types(self):\n values.String.validate('String value')\n\n for cls in (int, float, bool):\n with self.assertRaises(TypeError):\n values.String.validate(cls('1'))", "def _validate_input(self):\n pass", "def test_that_values_are_validated_against_specified_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensures that all instance types can be retrieved
def test_get_all_instance_types(self): session = sql_session.get_session() total_instance_types = session.query(models.InstanceTypes).count() inst_types = instance_types.get_all_types() self.assertEqual(total_instance_types, len(inst_types))
[ "def load_instance_types(self):\n # this must be imported here to avoid a circular import\n from ggprovisioner.cloud import aws\n\n def get_instance_types():\n \"\"\"\n Get the set of instances from the database\n \"\"\"\n instances = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensures that instance type creation fails with invalid args
def test_invalid_create_args_should_fail(self): invalid_sigs = [ (('Zero memory', 0, 1, 10, 20, 'flavor1'), {}), (('Negative memory', -256, 1, 10, 20, 'flavor1'), {}), (('Non-integer memory', 'asdf', 1, 10, 20, 'flavor1'), {}), (('Zero vcpus', 256, 0, 10, 20, 'fl...
[ "def test_constructor_invalid():\n with pytest.raises(TypeError, match='missing 1 required positional argument'):\n PseudoPotentialData() # pylint: disable=no-value-for-parameter", "def test_person_cannot_be_instantiated():\n with pt.raises(TypeError):\n Person()", "def test_constru...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensures that name duplicates raise InstanceTypeCreateFailed
def test_duplicate_names_fail(self): name = 'some_name' instance_types.create(name, 256, 1, 120, 200, 'flavor1') self.assertRaises(exception.InstanceTypeExists, instance_types.create, name, 256, 1, 120, 200, 'flavor2')
[ "def test_duplicate_flavorids_fail(self):\n flavorid = 'flavor1'\n instance_types.create('name one', 256, 1, 120, 200, flavorid)\n self.assertRaises(exception.InstanceTypeIdExists,\n instance_types.create,\n 'name two', 256, 1, 120, 200, flavori...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensures that flavorid duplicates raise InstanceTypeCreateFailed
def test_duplicate_flavorids_fail(self): flavorid = 'flavor1' instance_types.create('name one', 256, 1, 120, 200, flavorid) self.assertRaises(exception.InstanceTypeIdExists, instance_types.create, 'name two', 256, 1, 120, 200, flavorid)
[ "def test_duplicate_names_fail(self):\n name = 'some_name'\n instance_types.create(name, 256, 1, 120, 200, 'flavor1')\n self.assertRaises(exception.InstanceTypeExists,\n instance_types.create,\n name, 256, 1, 120, 200, 'flavor2')", "def test_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ensures error raised on bad default instance type
def test_will_not_get_bad_default_instance_type(self): self.flags(default_instance_type='unknown_flavor') self.assertRaises(exception.InstanceTypeNotFound, instance_types.get_default_instance_type)
[ "def testDefaultFields_InvalidSingle(self):\n def action(field_class):\n self.assertRaises(messages.InvalidDefaultError,\n field_class,\n 1,\n default=object())\n self.ActionOnAllFieldClasses(action)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure deleted instance types can be read when querying flavor_id
def test_can_read_deleted_types_using_flavor_id(self): inst_type_name = "test" inst_type_flavor_id = "test1" inst_type = instance_types.create(inst_type_name, 256, 1, 120, 100, inst_type_flavor_id) self.assertEqual(inst_type_name, inst_type["name"]) # NOTE(jk0):...
[ "def test_will_list_deleted_type_for_active_instance(self):\n ctxt = context.get_admin_context()\n inst_type = instance_types.create(\"test\", 256, 1, 120, 100, \"test1\")\n\n instance_params = {\"instance_type_id\": inst_type[\"id\"]}\n instance = db.instance_create(ctxt, instance_param...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure deleted instance types with active instances can be read
def test_will_list_deleted_type_for_active_instance(self): ctxt = context.get_admin_context() inst_type = instance_types.create("test", 256, 1, 120, 100, "test1") instance_params = {"instance_type_id": inst_type["id"]} instance = db.instance_create(ctxt, instance_params) # NOTE...
[ "def test_can_read_deleted_types_using_flavor_id(self):\n inst_type_name = \"test\"\n inst_type_flavor_id = \"test1\"\n\n inst_type = instance_types.create(inst_type_name, 256, 1, 120, 100,\n inst_type_flavor_id)\n self.assertEqual(inst_type_name, inst_type[\"name\"])\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exclude tiny instance which is 512 MB
def test_min_memory_mb_filter(self): filters = dict(min_memory_mb=513) expected = [ 'cg1.2xlarge', 'cg1.4xlarge', 'cg1.large', 'cg1.medium', 'cg1.small', 'cg1.xlarge', 'm1.large', 'm1.medium', ...
[ "def isLowMemory():\n return options.low_memory", "def testExcessiveRamUsage(self):\n c = Simulation()\n c.set_simulation_parameters(\n seed=1,\n task=36,\n output_directory=\"output\",\n min_speciation_rate=0.5,\n sigma=2,\n tau=2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exclude everything but large and xlarge which have >= 80 GB
def test_min_memory_mb_AND_root_gb_filter(self): filters = dict(min_memory_mb=16384, min_root_gb=80) expected = [ 'cg1.2xlarge', 'cg1.4xlarge', 'cg1.xlarge', 'm1.xlarge', 'sh1.16xlarge', 'sh1.2xlarge', 'sh1.32xlar...
[ "def test_min_memory_mb_filter(self):\n filters = dict(min_memory_mb=513)\n expected = [\n 'cg1.2xlarge',\n 'cg1.4xlarge',\n 'cg1.large',\n 'cg1.medium',\n 'cg1.small',\n 'cg1.xlarge',\n 'm1.large',\n 'm1.m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the main executor classes and establish their relationships. Then start the execution thread to launch the procedure execution
def prepareExecution(self): try: LOG("Setting up procedure controller for " + repr(self.procId)) if self.thread is not None: del self.thread self.thread = None if self.mailbox is not None: del self.mailbox if...
[ "def __init__(self):\n super(Executor, self).__init__()\n self.__scheduler = _scheduler.Scheduler()\n self.__procedures_lock = threading.RLock()\n self.__procedures = WeakValueDictionary()\n self.__threads_lock = threading.RLock()\n self.__executors = []\n self.__num...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setup procedure manager before the procedure execution
def setupProcedures(self): try: LOG("Setting up procedure manager") ProcedureManager.instance().setup(ctxName) except SpellException,ex: traceback.print_exc( file = sys.stderr ) LOG("Could not setup procedure manager: " + repr(ex), LOG_ERROR) ...
[ "def prepareExecution(self):\r\n try:\r\n LOG(\"Setting up procedure controller for \" + repr(self.procId))\r\n if self.thread is not None:\r\n del self.thread\r\n self.thread = None\r\n if self.mailbox is not None:\r\n del self.ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform the cleanup. If executionOnly is True, only the execution thread is stopped. This implies that the execution context is reset, and this is used tipically for reloading. If executionOnly is False, an entire cleanup is performed, including the SPELL driver.
def cleanup(self, executionOnly = False ): LOG("Stopping execution") if not executionOnly: LOG("Stopping client interface") ClientIF.cleanup() self.thread.stop() self.thread.join() self.cleanResources(not executionOnly) if not executionOnly...
[ "def clean_up_executors(self):\n pass", "def cleanup(self):\n logger.debug('Beginning cleanup ...')\n self.stop()\n\n #Clear subscriptions\n for sub, dev in self.subs.items():\n dev.clear_sub(sub)\n\n #Clear databases\n self.subs.clear()\n self.cmds.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Obtain the absolute path to the AsRun file.
def getAsRunFile(self): return ClientIF.getAsRun()
[ "def _get_R_script_path(self):\r\n return join(self._get_R_script_dir(), self._R_script)", "def _get_R_script_path(self):\r\n return join(self._get_R_script_dir(), self._r_script)", "def exepath(filename):\r\n return os.path.abspath(os.path.join(os.path.dirname(sys._getframe(1).f_code.co_filena...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start a wait condition processing in the executor. If no callback is given, the executor simply goes to WAITING status. If a callback is provided, it is called periodically to check wether the condition (whatever it is) is fulfilled or not (this is indicated by returning True or False in the callback, respectively). On...
def startWait(self, checkCallback = None, period = 0.5 ): self.scheduler.startWait(checkCallback,period)
[ "def _WaitForCondition(condition_callback, timeout=None):\n deadline = None if timeout is None else time.time() + timeout\n delay = _WAIT_MIN_RECHECK_DELAY\n while True:\n if condition_callback():\n return True\n remaining_time = (_WAIT_MAX_RECHECK_DELAY if deadline is None\n else...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Abort the execution of the procedure. Tipically used by SPELL language wrappers.
def abort(self): LOG("Aborting execution") self.controller.abort()
[ "def Abort(self):\n handler = self.get_command_object(\"Abort\")\n handler()", "def abort(self):\n self._result = self.inst.abort(\"Abort forced by suite runner.\")\n return self._result", "def abort(self):", "def abort(self):\n raise NotImplementedError", "def abort(self)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process an incomming message from the clients.
def processMessage(self, msg): LOG("Received message: " + msg.getId()) # Process messages incoming from child executor, if any procId = msg[FIELD_PROC_ID] if procId != self.procId: if self.childManager.hasChild(): self.childManager.processChild...
[ "def receive_incoming(self, msg):\r\n self.process_incoming(msg)", "def processIncommingMessages(self):\n while self.inqueue:\n msg = self.inqueue.popleft()\n dest_model = msg.destination\n if dest_model not in self.model.local_model_ids:\n # NOTE do i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Obtain the current stack position.
def getStackPosition(self): return self.callstack.getStack()
[ "def get_stack_position(self):\n\n\t\treturn struct.unpack('<Q', self.item_raw[32 : 40])[0]", "def read_stack_pointer(self):\n return self.STACK_POINTER", "def get_stack(self):\n return self.stack", "def top(self):\n if self.stack[0] > 0:\n return self.stack[self.stack[0]]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used by the language to change the runinto flag
def setRunInto(self, enabled): if enabled == True: LOG("Enabled RunInto") self.controller.enableRunInto() elif enabled == False: LOG("Disabled RunInto") self.controller.disableRunInto() #TODO: send notification EXECUTOR CONFIGURED
[ "def run(self, flags):\n pass", "def test_put_flag_setting(self):\n pass", "def set_flag(self, flag, value):\n self.engine.set_flag(flag, value)", "def set_flag(self, sample, individual):\n flag = None\n evaluator = self.QC_TITLE_TO_FLAG_EVALUATOR.get(self.title)\n if eva...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used by the language to change the browsablelib flag
def setBrowsableLib(self, enabled): if enabled == True: LOG("Enabled browsable lib") self.thread.setBrowsableLib(True) elif enabled == False: LOG("Disabled browsable lib") self.thread.setBrowsableLib(False) #TODO: send notification EXECUTOR ...
[ "def set_flag(self, new):\n self.flag = new", "def b_mode(self, b_mode):\n self._b_mode = b_mode", "def set_flags(self):\n offset = self.template['flagoffset']//8\n\n # comm keys provided?\n self.tpl_buff = bytes_transform(self.tpl_buff, offset+1, offset+2, lambda x: self.set_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trains the agent for episode_per_ticker, on each of num_tickers, looping over the approved list of tickers. This is a convenience function.
def train(self, num_tickers=4, episodes_per_ticker=5, **kwargs): num_tickers = min(num_tickers, len(self.filtered_tickers)) for i in range(num_tickers): ticker = self.filtered_tickers[i % num_tickers] env = self.ENV_CONSTRUCTOR(ticker=ticker, **kwargs) for j in tqdm(r...
[ "def train_and_evaluate(\n env, agent, num_episodes,\n eval_frequency=10, eval_num_episodes=10,\n min_return=-500,\n new_episode_hook=None,\n):\n if eval_frequency == 0:\n train_episodes = num_episodes\n else:\n train_episodes = eval_frequency\n for episode_num in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adds padding to the side of images, create a mask, and moves the results to the imag and mask folders
def run_padding(self): image_padded, mask, self.pad_to_right, self.pad_to_bottom = gen_padded_image_and_mask (os.path.join('utils_dfn/temp', self.file_name_with_ext), self.new_height, self.new_width) cv2.imwrite(os.path.join('utils...
[ "def mask_images(self, folder_name, mask_image_name):\n\n photo_list = self.get_photo_list(folder_name)\n masked_folder_name = folder_name + '_background'\n\n try:\n print(\"Making dir \" + str(masked_folder_name) + \" for masking\")\n os.mkdir(masked_folder_name)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
rescale an images to the new_width and new_height using the model provided and adds file_description to the result image
def rescale_image(self, img_file, new_width, new_height, model_path, file_description): cwd = os.getcwd() self.new_width = new_width self.new_height = new_height self.extract_file_name(img_file) shutil.copy(img_file, os.path.join('utils_dfn/temp', self.file_name_with_ext)) ...
[ "def _resize_img(self, results):\n for key in results.get('img_fields', ['img']):\n if self.keep_ratio:\n img, scale_factor = general_ocr.imrescale(\n results[key],\n results['scale'],\n return_scale=True,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes any files and subfolders that temporary created in the rescaling process
def clean(): folders = ['utils_dfn/temp', 'utils_dfn/img', 'utils_dfn/mask', 'utils_dfn/output'] for folder in folders: for item in os.listdir(folder): item_path = os.path.join(folder, item) if os.path.isdir(item_path): shutil.rmtree(item_path) elif os...
[ "def _clean_up_optimization():\n for (root, dirs, files) in walk(TEMP_MODULES_DIR_PATH, topdown=False):\n for file in files:\n if file.startswith(\"__temp_\"):\n remove(f\"{root}/{file}\")\n try:\n rmdir(root)\n except OSError:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an index and returns the matching Address index index to search on Address address matched to index
def getAddressAtIndex(self, index: int) -> ghidra.program.model.address.Address: ...
[ "def query_address(self, index):\n raw = self.__stack.query_address(index)\n if raw[0] & 0x80:\n return GroupAddress(raw)\n elif raw[0] == AddressType.SUBNETNODE:\n return SubnetNodeAddress(raw)\n elif raw[0] == AddressType.BROADCAST:\n return BroadcastAd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Eliminates incompatible values from var's neighbors' domains, modifying the original csp. Returns an alphabetically sorted list of the neighboring variables whose domains were reduced, with each variable appearing at most once. If no domains were reduced, returns empty list. If a domain is reduced to size 0, quits imme...
def eliminate_from_neighbors(csp, var) : eliminated_vars=[] val1s=csp.get_domain(var) neighbors=csp.get_neighbors(var) for neighbor in neighbors: eliminated=False constraints=csp.constraints_between(var,neighbor) tem=csp.copy() neighbor_domain=tem.get_domain(neighbor) ...
[ "def eliminate_from_neighbors(csp, var) :\n\n \"\"\"First, we will write a helper function to eliminate inconsistent values from a\n variable's neighbors' domains. In particular, for a given neighbor n of a variable v,\n if n has a value nval that violates a constraint with every value in v's domain, we\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses constraints to reduce domains, modifying the original csp. If queue is None, initializes propagation queue by adding all variables in their default order. Returns a list of all variables that were dequeued, in the order they were removed from the queue. Variables may appear in the list multiple times. If a domain ...
def domain_reduction(csp, queue=None) : if queue==None: queue=csp.get_all_variables() dequeued=[] while len(queue)!=0: current_var=queue.pop(0) dequeued.append(current_var) eliminated=eliminate_from_neighbors(csp,current_var) if(eliminated==None): return N...
[ "def domain_reduction(csp, queue=None) :\n if (queue==None):\n queue = csp.get_all_variables()\n dequeued = []\n while len(queue)!=0:\n removedVar = queue[0]\n dequeued.append(removedVar)\n queue = queue[1:]\n for constraint in csp.constraints_between(removedVar,None)[:]:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solves the problem using depthfirst search with forward checking and propagation through singleton domains. Same return type as solve_constraint_dfs.
def solve_constraint_propagate_singleton_domains(problem) : agenda=[problem] extension=0 current_prob=agenda.pop(0) extension+=1 #check failure if has_empty_domains(current_prob) or (not check_all_constraints(current_prob)): return (None, extension) #check success all_assigned=...
[ "def solve_constraint_propagate_singleton_domains(problem) :\n q = [problem]\n extCount = 0\n while len(q)!=0:\n removed = q[0]\n q = q[1:]\n extCount+=1\n if has_empty_domains(removed) or check_all_constraints(removed)==False:\n continue\n if len(removed.unass...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if var should be enqueued under the allreduceddomains condition, otherwise False
def condition_domain_reduction(csp, var) : return True
[ "def condition_singleton(csp, var) :\n if len(csp.get_domain(var))==1:\n return True\n return False", "def condition_singleton(csp, var) :\n return len(csp.get_domain(var))==1", "def condition_singleton(csp, var) :\n return len(csp.get_domain(var)) is 1", "def condition_singleton(csp, var) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if var should be enqueued under the singletondomains condition, otherwise False
def condition_singleton(csp, var) : if len(csp.get_domain(var))==1: return True return False
[ "def condition_singleton(csp, var) :\n domain = csp.get_domain(var)\n if len(domain) == 1:\n return True\n return False", "def condition_singleton(csp, var) :\n return len(csp.get_domain(var)) is 1", "def condition_singleton(csp, var) :\n return len(csp.get_domain(var))==1", "def is_shar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if var should be enqueued under the forwardchecking condition, otherwise False
def condition_forward_checking(csp, var) : return False
[ "def condition_forward_checking(csp, var) :\n # ???\n return False", "def __forward_check(self, assigned_var, assigned_value, unassigned_vars):\n for unassigned_neighbor in self.__unassigned_neighbors(assigned_var, unassigned_vars):\n consistent_values = self.__consistent_domain_values(ass...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solves the problem, calling propagate with the specified enqueue condition (a function). If enqueue_condition is None, uses DFS only. Same return type as solve_constraint_dfs.
def solve_constraint_generic(problem, enqueue_condition=None) : agenda=[problem] extension=0 current_prob=agenda.pop(0) extension+=1 #check failure if has_empty_domains(current_prob) or (not check_all_constraints(current_prob)): return (None, extension) #check success all_assig...
[ "def solve_constraint_generic(problem, enqueue_condition=None) :\n raise NotImplementedError", "def solve_constraint_generic(problem, enqueue_condition=None) :\n if enqueue_condition is None:\n return solve_constraint_dfs(problem)\n\n agenda = [problem]\n extensions = 0\n while agenda:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if m and n are adjacent, otherwise False. Assume m and n are ints.
def constraint_adjacent(m, n) : if abs(m-n)==1: return True return False
[ "def constraint_adjacent(m, n) :\n difference = m - n\n if difference is 1 or difference is -1:\n return True\n return False", "def constraint_adjacent(m, n) :\n if abs(m-n) == 1:\n return True\n else:\n return False\n \n raise NotImplementedError", "def constraint_adja...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if m and n are NOT adjacent, otherwise False. Assume m and n are ints.
def constraint_not_adjacent(m, n) : if abs(m-n)==1: return False return True
[ "def constraint_adjacent(m, n) :\n difference = m - n\n if difference is 1 or difference is -1:\n return True\n return False", "def constraint_adjacent(m, n) :\n if abs(m-n)==1:\n return True\n return False", "def constraint_not_adjacent(m, n) :\n return not constraint_adjacent(m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of constraints, with one difference constraint between each pair of variables.
def all_different(variables) : constraints=[] for index,var in enumerate(variables): for sub_index in range(index+1,len(variables)): var1=var var2=variables[sub_index] new_constraint=Constraint(var1,var2,constraint_different) constraints.append(new_constra...
[ "def all_different(variables) :\n constraints = []\n for i in xrange(len(variables)):\n var1 = variables[i]\n for j in xrange(i+1,len(variables)):\n var2 = variables[j]\n if var1!=var2:\n constraints.append(Constraint(var1,var2,constraint_different))\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
p should be captured. If increment > 0, it searches the lower limit.
def search_the_limit_outwards(p, increment, flow, factor, printIt): if not(p.captured): exception_msg = 'Sorry, the particle isn\'t captured. We cannot ' \ + 'proceed to the computation :(' raise Exception(exception_msg) x0, y0 = p.pos0 new_p = deepcopy(p) while ...
[ "def next(self):\n\t\tif (self.current is None):\n\t\t\treturn None\n\t\t\n\t\tif (self.current == []):\n\t\t\tself.current = range(1, self.min + 1)\n\t\telse:\n\t\t\tself.current = Pattern_maker.increment(self.current)\n\t\t\n\t\twhile (not Pattern_maker.contains_relative(self.current, self.pat, self.rotate)):\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that the metadata_cache_uri config property can be set using the `metadataStoreUri` config dict key when created via the Ocean __init__
def test_metadataStoreUri_config_key(): config_dict = {"metadataStoreUri": "http://ItWorked.com", "network": GANACHE_URL} ocean_instance = Ocean(config=config_dict) assert "http://ItWorked.com" == ocean_instance.config.metadata_cache_uri
[ "def test_metadataCacheUri_config_key():\n config_dict = {\"metadataCacheUri\": \"http://ItWorked.com\", \"network\": GANACHE_URL}\n ocean_instance = Ocean(config=config_dict)\n assert \"http://ItWorked.com\" == ocean_instance.config.metadata_cache_uri", "def test_metadata_cache_uri_set_via_config_option...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that the metadata_cache_uri config property can be set using the `metadataCacheUri` config dict key when created via the Ocean __init__
def test_metadataCacheUri_config_key(): config_dict = {"metadataCacheUri": "http://ItWorked.com", "network": GANACHE_URL} ocean_instance = Ocean(config=config_dict) assert "http://ItWorked.com" == ocean_instance.config.metadata_cache_uri
[ "def test_metadataStoreUri_config_key():\n config_dict = {\"metadataStoreUri\": \"http://ItWorked.com\", \"network\": GANACHE_URL}\n ocean_instance = Ocean(config=config_dict)\n assert \"http://ItWorked.com\" == ocean_instance.config.metadata_cache_uri", "def test_metadata_cache_uri_set_via_config_option...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the metadata_cache_uri property fallback logic when set via a config dict
def test_metadata_cache_uri_set_via_config_options(caplog): config_dict = {"resources": {"metadata_cache_uri": "https://custom-aqua.uri"}} config = Config(options_dict=config_dict) assert config.metadata_cache_uri == "https://custom-aqua.uri" config_dict = { "resources": { "metadata...
[ "def test_metadataCacheUri_config_key():\n config_dict = {\"metadataCacheUri\": \"http://ItWorked.com\", \"network\": GANACHE_URL}\n ocean_instance = Ocean(config=config_dict)\n assert \"http://ItWorked.com\" == ocean_instance.config.metadata_cache_uri", "def test_metadataStoreUri_config_key():\n conf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the metadata_cache_uri property fallback logic when set via an environment variable
def test_metadata_cache_uri_set_via_env_vars(monkeypatch, caplog): ENV_METADATA_CACHE_URI = environ_names_and_sections[NAME_METADATA_CACHE_URI][0] ENV_AQUARIUS_URL = deprecated_environ_names[NAME_AQUARIUS_URL][0] monkeypatch.delenv(ENV_METADATA_CACHE_URI, raising=False) monkeypatch.delenv(ENV_AQUARIUS_...
[ "def test_metadataCacheUri_config_key():\n config_dict = {\"metadataCacheUri\": \"http://ItWorked.com\", \"network\": GANACHE_URL}\n ocean_instance = Ocean(config=config_dict)\n assert \"http://ItWorked.com\" == ocean_instance.config.metadata_cache_uri", "def test_metadataStoreUri_config_key():\n conf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the Config.address_file property.
def test_address_file(monkeypatch): # Test default value when ADDRESS_FILE envvar and address.file config option not set ENV_ADDRESS_FILE = environ_names_and_sections[NAME_ADDRESS_FILE][0] monkeypatch.delenv(ENV_ADDRESS_FILE) config_text_empty = "" config = Config(text=config_text_empty) assert...
[ "def test_retrieve_address(self):\n pass", "def test_client_address_retrieve(self):\n pass", "def test_check_address_validity(self):\n pass", "def test_get_contracts_addresses_good_path_custom_network(tmp_path):\n # tmp_path:pathlib.Path is special pytest feature\n\n # create & fill...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
批量删除 param is not None
def detele_batch(self, collection, param): if param is not None and isinstance(param, dict): result = self.db.get_collection(collection).delete_many(param) return result.deleted_count else: raise Exception("参数类型异常")
[ "def batch_delete(self, base_id: str, table_name: str, record_ids: List[str]):\n return super()._batch_delete(base_id, table_name, record_ids)", "def delete_batch(self, pk_list):\n for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):\n where = self.where_class()\n fie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find lyric video for this music video
def get_lyrics_url(non_lyrics_url, driver=None): if not driver: driver = get_browser() driver.get(non_lyrics_url) song_name = get_current_song_name(driver) search_url = "https://www.youtube.com/results?search_query=" + song_name + " lyrics lyrical words" driver.get(search_url) driver.fi...
[ "def search_youtube_music_video(self, artist, name, duration_ms):\n\t\t# return val : false until proven wrong\n\t\tsuccess = False # could not find matching youtube video\n\t\terror_des = \"none\"\n\n\t\tself.authorize()\n\n\n\n\t\t# build search params aka q\n\t\t#finders = ['vevo','lyrics']\t\t\t# words t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the ionization fraction, in equilibrium, for all ions of the element. Calculate the population fractions for every ion of this element as a function of temperature, assuming ionization equilibrium. This returns a matrix with dimensions ``(n,Z+1)``, where ``n`` corresponds to the temperature dimension and ``Z+...
def equilibrium_ionization(self): # Solve system of equations using singular value decomposition _, _, V = np.linalg.svd(self._rate_matrix.value) # Select columns of V with smallest eigenvalues (returned in descending order) # NOTE: must take the absolute value as the SVD solution is onl...
[ "def ioneq(self):\n temperature = self.temperature.to_value('K')\n temperature_data = self._ioneq[self._dset_names['ioneq_filename']]['temperature'].to_value('K')\n ioneq_data = self._ioneq[self._dset_names['ioneq_filename']]['ionization_fraction'].value\n # Perform PCHIP interpolation i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store ticket changes in the database. The ticket must already exist in the database.
def save_changes(self, author, comment, when=0, db=None): assert self.exists, 'Cannot update a new ticket' if not self._old and not comment: return # Not modified if not db: db = self.env.get_db_cnx() handle_ta = True else: hand...
[ "def update_db(self):\n\n LOGGER.debug('Received call to updateDB')\n\n self.tracker_db_ticket.ticket_status = self.status\n self.tracker_db_ticket.ticket_assignee = self.assignee\n self.tracker_db_ticket.ticket_updated = datetime.datetime.today()", "def ticket_created(self, ticket):",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }