query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Extract emission line fluxes from a grid (represented as a DataFrame) by inputting gridpoint indices and taking the fluxes at the nearest gridpoint | def extract_grid_fluxes_i(DF, p_name_ind_map, line_names):
val_arrs = {p:np.unique(DF[p].values) for p in p_name_ind_map}
assert len(DF) == np.product([len(v) for v in val_arrs.values()])
where = np.full(len(DF), 1, dtype=bool)
for p,ind in p_name_ind_map.items():
where &= (DF.loc[:,p] == val_ar... | [
"def _get_xy_individual_fluxes(self):\n y = self._dataset.flux[self._dataset.good]\n\n if self.fix_source_flux is False:\n x = np.array(self._data_magnification)\n if self.model.n_sources == 1:\n x = x[self._dataset.good]\n else:\n x = x[:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure the parameter estimates are as expected | def test_parameter_estimates(self):
DF_est = self.Result.Posterior.DF_estimates
self.assertTrue(all(p in DF_est.index for p in self.params))
# Tolerance for distance between gridpoint we chose and the estimate:
grid_sep_frac = 0.1 # Allowed fraction of distance between gridpoints
... | [
"def test_parameter_estimates(self):\n DF_est = self.Result.Posterior.DF_estimates # DataFrame\n p0_est = DF_est.loc[\"p0\", \"Estimate\"]\n self.assertTrue(np.isclose(p0_est, self.expected_p0, atol=1))",
"def test_estimate_bounds_checks(self):\n DF = self.Result.Posterior.DF_estimate... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure the raw grid spec is as expected | def test_raw_Grid_spec(self):
RGrid_spec = self.NB_Model_1.Raw_grids
self.assertEqual(RGrid_spec.param_names, self.params)
self.assertEqual(RGrid_spec.ndim, len(self.params))
self.assertEqual(RGrid_spec.shape, self.n_gridpts_list)
self.assertEqual(RGrid_spec.n_gridpoints, np.prod... | [
"def test_interpolated_Grid_spec(self):\n IGrid_spec = self.Result.Grid_spec\n self.assertEqual(IGrid_spec.param_names, self.params)\n self.assertEqual(IGrid_spec.param_display_names, self.params)\n self.assertEqual(IGrid_spec.shape, tuple(self.interpd_shape))\n self.assertEqual(I... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure the interpolated grid spec is as expected | def test_interpolated_Grid_spec(self):
IGrid_spec = self.Result.Grid_spec
self.assertEqual(IGrid_spec.param_names, self.params)
self.assertEqual(IGrid_spec.param_display_names, self.params)
self.assertEqual(IGrid_spec.shape, tuple(self.interpd_shape))
self.assertEqual(IGrid_spec.... | [
"def test_interpolation_to_grid(grid):\n sf = ScalarField.random_uniform(grid)\n sf2 = sf.interpolate_to_grid(grid)\n np.testing.assert_allclose(sf.data, sf2.data, rtol=1e-6)",
"def test_vector_grid_formatting(self):\n self.assertEqual(1, 1)",
"def test_raw_Grid_spec(self):\n RGrid_spec =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the list of best model keys is what is documented | def test_best_model_dict_keys(self):
expected_keys = sorted(["table", "chi2", "extinction_Av_mag",
"grid_location"])
key_list = sorted(list(self.Result.Posterior.best_model.keys()))
self.assertEqual(key_list, expected_keys) | [
"def _check_model_params(self):",
"def test_all_field_opts_model(self, all_field_opts):\n for field in all_field_opts:\n api_keys = field.keys()\n # Tests if API and model have same number of keys\n assert len(self.model_keys) == len(api_keys)\n # Tests if the AP... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure that the "checking columns" in the estimate table are all showing that the estimates are good. | def test_estimate_bounds_checks(self):
DF = self.Result.Posterior.DF_estimates # Parameter estimate table
for p in ["12 + log O/H", "log P/k", "log U"]:
for col in ["Est_in_CI68?", "Est_in_CI95?"]:
self.assertTrue(DF.loc[p,col] == "Y")
for col in ["Est_at_lower?"... | [
"def data_checks():\n for func in [read_adult, read_bank, read_compas, read_german, read_sqf,\n read_synthetic]:\n xtr, xte, ytr, yte, ztr, zte = func()\n\n if np.any(xtr[:, 0] != 1.) or np.any(xte[:, 0] != 1.):\n print(\"WARNING: intercept issue in {}\".format(func.__nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regression check that chi2 doesn't change | def test_chi2(self):
chi2 = self.Result.Posterior.best_model["chi2"]
self.assertTrue(np.isclose(chi2, 2568.7, atol=0.2), msg=str(chi2)) | [
"def test_chi2(self):\n chi2 = self.Result.Posterior.best_model[\"chi2\"]\n self.assertTrue(np.isclose(chi2, 2522.7, atol=0.2), msg=str(chi2))",
"def set_chi2(self):\n\n y_observed = self._y\n y_expected = []\n #i = 0\n for x in self._x:\n #y_expected.append(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regression check that chi2 doesn't change | def test_chi2(self):
chi2 = self.Result.Posterior.best_model["chi2"]
self.assertTrue(np.isclose(chi2, 2522.7, atol=0.2), msg=str(chi2)) | [
"def test_chi2(self):\n chi2 = self.Result.Posterior.best_model[\"chi2\"]\n self.assertTrue(np.isclose(chi2, 2568.7, atol=0.2), msg=str(chi2))",
"def set_chi2(self):\n\n y_observed = self._y\n y_expected = []\n #i = 0\n for x in self._x:\n #y_expected.append(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure dereddening attributes added to Result object. | def test_dereddening_result_attributes(self):
self.assertTrue(self.Result.deredden)
self.assertTrue(self.Result.propagate_dered_errors) | [
"def set_attributes_all_required(instance, attrs, res):\r\n for attr in attrs:\r\n attr_val = res.get(attr)\r\n # all attributes are required\r\n if not attr_val:\r\n print(attr)\r\n abort(400)\r\n setattr(instance, attr, attr_val)\r\n return instance",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regression test check the parameter estimate is as expected. | def test_parameter_estimates(self):
DF_est = self.Result.Posterior.DF_estimates # DataFrame
p0_est = DF_est.loc["p0", "Estimate"]
self.assertTrue(np.isclose(p0_est, self.expected_p0, atol=1)) | [
"def test_parameter_estimates(self):\n DF_est = self.Result.Posterior.DF_estimates\n self.assertTrue(all(p in DF_est.index for p in self.params))\n # Tolerance for distance between gridpoint we chose and the estimate:\n grid_sep_frac = 0.1 # Allowed fraction of distance between gridpoin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regression test check likelihood is all zero. | def test_likelihood_all_zero(self):
likelihood = self.Result.Likelihood.nd_pdf
self.assertTrue(np.all(likelihood == 0)) | [
"def test_likelihood_mostly_zero(self):\n likelihood = self.Result.Likelihood.nd_pdf\n self.assertTrue(np.sum(likelihood != 0) < 65)",
"def test_positive_pred(self,y):\n self.assertTrue((y>0).all())",
"def test_multiscale_zero(self):\n self.assertEqual(0, metrics.multiscale_spectral_loss... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regression test check posterior is all zero. | def test_posterior_all_zero(self):
posterior = self.Result.Posterior.nd_pdf
self.assertTrue(np.all(posterior == 0)) | [
"def test_positive_pred(self,y):\n self.assertTrue((y>0).all())",
"def test_likelihood_all_zero(self):\n likelihood = self.Result.Likelihood.nd_pdf\n self.assertTrue(np.all(likelihood == 0))",
"def test_likelihood_mostly_zero(self):\n likelihood = self.Result.Likelihood.nd_pdf\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regression test check likelihood is mostly zero. | def test_likelihood_mostly_zero(self):
likelihood = self.Result.Likelihood.nd_pdf
self.assertTrue(np.sum(likelihood != 0) < 65) | [
"def test_likelihood_all_zero(self):\n likelihood = self.Result.Likelihood.nd_pdf\n self.assertTrue(np.all(likelihood == 0))",
"def perplexity(model, test_data):\n return np.exp(-model.mean_log_likelihood(test_data))",
"def test_single_linear_regression_rmse(reg_model):\n assert(pytest.appro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regression test check posterior is all zero. | def test_posterior_all_zero(self):
posterior = self.Result.Posterior.nd_pdf
self.assertTrue(np.all(posterior == 0)) | [
"def test_positive_pred(self,y):\n self.assertTrue((y>0).all())",
"def test_likelihood_all_zero(self):\n likelihood = self.Result.Likelihood.nd_pdf\n self.assertTrue(np.all(likelihood == 0))",
"def test_likelihood_mostly_zero(self):\n likelihood = self.Result.Likelihood.nd_pdf\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the marginalised 1D pdfs are as expected | def test_marginalised_1D_pdf(self):
m_1D = self.NB_nd_pdf_1.marginalised_1D
self.assertEqual(len(m_1D), 2)
# Scale the pdfs to compare despite the m_1D PDFs being normalised
m_1D["log U"] /= m_1D["log U"].max()
m_1D["12 + log O/H"] /= m_1D["12 + log O/H"].max()
expected_x... | [
"def test_compute_pdf_matrix(self):\n pdf_matrix = self.cluster_obj_2.compute_pdf_matrix()\n self.assertEqual(round(pdf_matrix[0,0], 3), 0.044)\n self.assertEqual(round(pdf_matrix[0,1], 3), 0.038)",
"def test_posterior_all_zero(self):\n posterior = self.Result.Posterior.nd_pdf\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the normalised nd_pdf matches the input raw nd_pdf. We avoid doing a proper normalisation by comparing with a simple scaling. | def test_nd_pdf(self):
pdf = self.NB_nd_pdf_1.nd_pdf
scaled_raw_nd_pdf = self.raw_pdf / self.raw_pdf.max()
self.assertTrue(np.array_equal(pdf / pdf.max(), scaled_raw_nd_pdf)) | [
"def test_norm_pdf():\n # Note: Neither my code nor theirs check that cov is symmetric, and they\n # will give different results if cov is asymmetric.\n x = np.array([4., 5.])\n mean = np.array([3., 2.])\n cov = np.array([[3., 2.], [2., 4.]])\n ref_p = 0.017161310176083477\n # nose.tools.assert... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check propagate_dered_errors values on Result object | def test_propagate_dered_errors(self):
# Checks default value of False
self.assertFalse(self.Result_dered1.propagate_dered_errors)
self.assertTrue(self.Result_dered2.propagate_dered_errors) | [
"def test_dereddening_result_attributes(self):\n self.assertTrue(self.Result.deredden)\n self.assertTrue(self.Result.propagate_dered_errors)",
"def _check_reproduced_expected_errors(self):\n if self.__reproduced_expected_errors:\n pytest.xfail(reason=self._get_reproduced_expected_errors_msg(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regression test lines not included in likelihood calculation should still appear in the "best model" table. | def test_non_likelihood_lines_in_best_model_table(self):
self.assertTrue(all(l in self.DF_best.index for l in self.exclude_lines)) | [
"def test_In_lhood_field_in_best_model_table(self):\n correct = [(\"N\" if l in self.exclude_lines else \"Y\") for l in self.lines]\n self.assertTrue(self.DF_best[\"In_lhood?\"].values.tolist() == correct)",
"def test_single_linear_regression_fit(reg_model):\n assert(pytest.approx(reg_model.b1, 0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regression test check fields of best model table (we test for the case of no dereddening; field names are different with dereddening). | def test_best_model_table_fields(self):
correct_fields = ["In_lhood?", "Obs", "Model", "Resid_Stds", "Obs_S/N"]
t_fields = self.DF_best.columns.tolist()
self.assertTrue(t_fields == correct_fields, t_fields) | [
"def test_get(self):\n correct_fields = {\n \"features\": self.features,\n \"num_features\": self.num_features,\n \"target\": self.target,\n \"method\": self.method,\n \"num_examples\": self.num_examples,\n }\n\n print(self.model)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regression test the "In_lhood?" field in the best model table should correctly identify if a line was used in the likelihood. | def test_In_lhood_field_in_best_model_table(self):
correct = [("N" if l in self.exclude_lines else "Y") for l in self.lines]
self.assertTrue(self.DF_best["In_lhood?"].values.tolist() == correct) | [
"def test_non_likelihood_lines_in_best_model_table(self):\n self.assertTrue(all(l in self.DF_best.index for l in self.exclude_lines))",
"def test_ll_nom(self):\n pars = list(self.spec.central)\n nominal = self.spec(pars)\n self.spec.set_data(nominal) # nominal data\n stats = np... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regression test the order of the input lines should not affect the results. There was a real bug introduced with the "likelihood_lines" feature this test fails on NB version 0.9.6 and 0.9.7! | def test_permuting_input_line_order(self):
n = len(self.lines)
for i, ind_tuple in enumerate(itertools.permutations(range(n))):
# There are 5! = 120 permutations, so only check one in five:
if i % 5 != 2:
continue
obs_fluxes = [self.obs_fluxes[j] for j... | [
"def test_non_likelihood_lines_in_best_model_table(self):\n self.assertTrue(all(l in self.DF_best.index for l in self.exclude_lines))",
"def dataLikelihood(self, step):",
"def likelihoods(self, step):",
"def priorLikelihood(self, step):",
"def likelihood(self, x: np.ndarray) -> np.ndarray:",
"def t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test correct error is raised if there are too few unique values for a grid parameter. | def test_bad_grid_parameter_with_too_few_unique_values(self):
DF = pd.DataFrame({"p1": [4, 4, 4, 4], "p2": [1, 2, 3, 4],
"l2": [5, 6, 7, 8]})
self.assertRaisesRE(ValueError, "3 unique values are required",
NB_Model, DF, ["p1", "p2"]) | [
"def test_is_grid_row_invalid():\n assert not sudoku.is_grid_valid(BAD_ROW_GRID)",
"def test_grid_list_cell_outside_range_invalid():\n assert not sudoku.no_wrong_integers(BAD_INTEGER_OUTSIDE_RANGE)",
"def test_check_unique_header(self):\n header = [\"GENE\", \"foo\", \"foo2\", \"foo3\"]\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function needs to be called manually to test the interactive plotting. from test_NB import interactive_plot_tests interactive_plot_tests() | def interactive_plot_tests():
lines = ["OII3726_29", "Hgamma", "OIII4363", "Hbeta", "OIII5007",
"NI5200", "OI6300", "Halpha", "NII6583", "SII6716", "SII6731"]
obs_fluxes = [1.22496, 0.3991, 0.00298, 1.0, 0.44942,
0.00766, 0.02923, 4.25103, 1.65312, 0.45598, 0.41482]
obs_er... | [
"def test_plot_instance_components(browser_backend):\n raw = _get_raw()\n picks = _get_picks(raw)\n ica = ICA(noise_cov=read_cov(cov_fname), n_components=2)\n with pytest.warns(RuntimeWarning, match=\"projection\"):\n ica.fit(raw, picks=picks)\n ica.exclude = [0]\n fig = ica.plot_sources(ra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Commands to migrate records from legacy. | def migrate(): | [
"def Migrate(self):\n\n # TODO(amoser): This doesn't do anything yet.\n pass",
"def record(recid):\n click.echo(f\"Migrating record {recid} from INSPIRE legacy\")\n migrate_record_from_legacy(recid)",
"def migrate() -> None:\n run_migration()",
"def migrate(params='', do_backup=False):\n # i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Migrate the records in the provided file. The file can be an (optionallygzipped) XML file containing MARCXML, or a prodsync tarball. | def migrate_file(file_name, mirror_only=False, force=False, wait=False):
halt_if_debug_mode(force=force)
click.echo(f"Migrating records from file: {file_name}")
populate_mirror_from_file(file_name)
if not mirror_only:
task = migrate_from_mirror()
if wait:
wait_for_all_tasks(... | [
"def migrate(self,f):\n fs = f.status()\n if ( fs == FILE_CLOSED ):\n ret = self.reqDb.migrateFile(f.name(),f.path())\n if ( ret ):\n return self._setFileState(f, FILE_MIGRATING)\n return fail('Cannot migrate file:',f.name(),' to longterm storage.')\n elif ( fs == FILE_MIGRATING or fs... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Migrate records from the mirror. By default, only records that have not been migrated yet are migrated. | def mirror(also_migrate=None, force=False, wait=False, date_from=None):
halt_if_debug_mode(force=force)
task = migrate_from_mirror(
also_migrate=also_migrate, disable_external_push=True, date_from=date_from
)
if wait:
wait_for_all_tasks(task) | [
"def Migrate(self):\n\n # TODO(amoser): This doesn't do anything yet.\n pass",
"def migrate(self, source):\n raise NotImplementedError",
"def migrate(self, epoch: int):\n ordered_players = self.migration_order_policy(self.players)\n\n for p in ordered_players:\n p.migrate()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Migrate a single record from legacy. | def record(recid):
click.echo(f"Migrating record {recid} from INSPIRE legacy")
migrate_record_from_legacy(recid) | [
"def Migrate(self):\n\n # TODO(amoser): This doesn't do anything yet.\n pass",
"def upgrade_legacy(self):\n # Transform to version 1\n if not hasattr(self, 'version'):\n self._models = [\n self.conv1,\n self.conv2,\n self.conv3,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to randomly select the four elements of the winning ticket | def pick_winner(self) :
winning_combo = []
count = 0
while count <= 3 :
random = self.lotto_elements[randint(0, 14)]
winning_combo.append(random)
count += 1
return winning_combo | [
"def draw_winning_ticket(self):\r\n number_taken = []\r\n ticket = []\r\n n_number = 0\r\n while len(ticket)<6:\r\n number = random.randint(1, 45)\r\n if number not in ticket:\r\n ticket.append(number)\r\n number_taken.append(number)\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
converts a txt file into a csv | def convert_to_csv(txtfile, csvfile):
with open(txtfile, 'r') as f1, open(csvfile, 'w', newline='') as f2:
out_file = csv.writer(f2)
for line in f1:
line = line.strip(' \n\t')
for ch in [',', ';', '.', '"', '!', '(', ')', ':', '/', "-", '\\', '?' ]:
if ch in l... | [
"def txt_to_csv(path_to_txt_file):\n\tcsv_filename = f\"{path_to_txt_file.split('/')[-1][:-4]}.csv\"\n\twith open(path_to_txt_file.split('/')[-1]) as fin, open(csv_filename, 'w') as fout:\n\n\t\to=csv.writer(fout)\n\t\tfor line in fin:\n\t\t\to.writerow(line.split())\n\n\t#the text processing ruins the columns name... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update self.body and set new timestamp | def update(self, body):
self.body = body | [
"def save(self, *args, **kwargs):\n self.updated_ts = datetime.utcnow()\n super().save(*args, **kwargs)",
"def update(self, *args, **kwargs):\n utcnow = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S UTC\")\n self.updated_at = utcnow\n\n super(ModelBaseWithTimeStamp, se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Records the outcome of a single match between two players and updates all tables. | def reportMatch(player1, player2, outcome):
player1 = bleach.clean(player1)
player2 = bleach.clean(player2)
outcome = bleach.clean(outcome)
if player1 == outcome:
winner = player1
loser = player2
else:
winner = player2
loser = player1
result = checkMatch(play... | [
"def reportMatch(winner, loser):\n\n db = connect()\n c = db.cursor()\n\n # these following lines will retrieve\n query = \"SELECT score FROM players WHERE id = %s\"\n\n data = (winner, )\n c.execute(query, data)\n w_score = c.fetchone()\n w_score = int(w_score[0])\n\n data = (loser, )\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of pairs of players for the next round of a match. Assuming that there are an even number of players registered, each player appears exactly once in the pairings. If there is an odd number of players then an odd player is assigned a 'bye' only once per tournament. A 'bye' is reported as an id of 0, with ... | def swissPairings():
count = countPlayers()
odd_player = count % 2
adjust = count-odd_player
total_matches = totalMatches()
matches_count = (total_matches + (total_matches*odd_player)/count)/2
total_rounds = int(math.log(adjust,2))
round_no = int(total_matches/count) + 1
if round_no > ... | [
"def swissPairings():\n current_standings = playerStandings()\n next_round = []\n match_count = 0\n for player_row in current_standings:\n player_id = player_row[0]\n name = player_row[1]\n if match_count % 2 == 0:\n match_list = [player_id, name]\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a set of message components with yes/no buttons, ready for use. If provided, the given IDs will be used for the buttons. If not, the button custom IDs will be set to the strings "YES" and "NO". | def boolean_buttons(cls, yes_id: str = None, no_id: str = None) -> 'MessageComponents':
return cls(
ActionRow(
Button(label="Yes", style=ButtonStyle.success, custom_id=yes_id or "YES"),
Button(label="No", style=ButtonStyle.danger, custom_id=no_id or "NO"),
... | [
"def YesNo(title, question, default):\n dlg = wx.MessageDialog(None, question, title, wx.YES_NO | wx.ICON_QUESTION) \n if dlg.ShowModal() == wx.ID_YES:\n result = True\n else:\n result = False\n dlg.Destroy()\n return result",
"def translateButtonsFromKupu(self, context, buttons):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a message components object with a list of number buttons added. Each number is added as its own button. Numbers provided as a list will be added as primary, where numbers added as negatives (if ``add_negative`` is set to ``True``) will be added as secondary buttons. A confirm button will not be automatically a... | def add_number_buttons(
cls, numbers: typing.List[int] = MISSING, *,
add_negative: bool = False):
if numbers is MISSING:
numbers = [1, 5, 10, 50, 100]
v = cls()
if add_negative:
v.add_component(ActionRow(*[
Button(label=f"{i:+d}",... | [
"def add_number_buttons(self):\r\n add_rowspace, add_colspace = False, False\r\n for i in range(len(self.board)): # for each row i of the board\r\n add_rowspace = ((i+1)%self.base_size == 1 and i != 0)\r\n if add_rowspace:\r\n [self.widget_board.add_widget(Label(te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pagerank v1 With the eucidean_distance | def pagerank_v2(page_map, eps=1.0e-8, d=0.85):
vertex_num = page_map.shape[1]
v_rank = np.ones((vertex_num, 1), dtype=np.float32)
v_rank = v_rank/vertex_num
last_v_rank = np.ones((vertex_num, 1), dtype=np.float32)
page_map_hat = (d * page_map) + (((1 - d) / vertex_num) * np.ones((vertex_num, vertex... | [
"def pagerank_calc(corpus, old_pagerank, damping_factor):\n new_pagerank = {}\n pages = list(corpus.keys())\n pagerank_base_prob = (1-damping_factor)/len(pages)\n\n for page in pages:\n # Set of tuples of all the links that link to the current page\n # (page_name, num_links_on_the_page)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure we can create a basic LtpType and then read it back | def test_create_type_no_parent(self, app):
with app.app_context():
conn = get_connection(current_app)
name = 'Book'
desc = 'A physical or digital book'
resp = conn.create_type(name, desc)
assert type(resp) == LtpType
assert str(resp.name... | [
"def test_tool_types_read(self):\n pass",
"def testGetType(self):\n self.assertEqual(b\"PhysAddress\",\n mib.ffi.string(mib._getType(\"PhysAddress\").name))\n self.assertEqual(b\"InetAddress\",\n mib.ffi.string(mib._getType(b\"InetAddress\").nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the optimal path from starting_point to the zero contour of travel_time. Solve the equation x_t = grad t / | grad t | travel_time is the travel time for each point of image from the trial point (zero contour) dx is the grid spacing N is the maximum travel time | def minimal_path(travel_time, starting_point, dx, boundary, steps, N=100):
grad_t_y, grad_t_x = np.gradient(travel_time, dx)
if isinstance(travel_time, np.ma.MaskedArray):
grad_t_y[grad_t_y.mask] = 0.0
grad_t_y = grad_t_y.data
grad_t_x[grad_t_x.mask] = 0.0
grad_t_x = gr... | [
"def optimal_path(x,distances,predecessors,xstart,xmin,xmax,resolution=None,cost=None):\n xmin = np.asarray(xmin)\n xmax = np.asarray(xmax)\n if resolution is None:\n rmax = np.max(xmax-xmin)\n resolution = rmax/DEFAULT_RESOLUTION\n invresolution = np.divide(1.0,resolution)\n corner = n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns normalized velocity at the position | def get_velocity(position):
x, y = position
vel = np.array([gradx_interp(y, x)[0][0],
grady_interp(y, x)[0][0]])
return vel / np.linalg.norm(vel) | [
"def normalize_velocity(velocity, velocity_range):\n return (velocity - velocity_range[0]) / (velocity_range[1] - velocity_range[0])",
"def u(self):\n return self.centroid_velocity / np.linalg.norm(self.centroid_velocity)",
"def v(self):\n return self.centroid_velocity_tangent / np.linalg.norm(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Python 3.3 added a an addtional LOAD_CONST before MAKE_FUNCTION and this has an effect on many rules. | def add_make_function_rule(self, rule, opname, attr, customize):
new_rule = rule % (('LOAD_CONST ') * (1 if self.version >= 3.3 else 0))
self.add_unique_rule(new_rule, opname, attr, customize) | [
"def __addConstantInitCode(\n context,\n emit,\n check,\n constant_type,\n constant_value,\n constant_identifier,\n module_level,\n):\n # This has many cases, that all return, and do a lot.\n # pylint: disable=too-many-branches,too-many-locals,too-many-return-statements,too-many-statement... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints 'args' and 'kwargs' in human readable form. | def inspect_args(*args, **kwargs):
args_string = ', '.join(['{0!r}'.format(i) for i in args])
print('Positional arguments:')
print(args_string)
print()
kwargs_string = ', '.join(
'{0}={1!r}'.format(k, v) for k, v in kwargs.items())
print('Keyword arguments:')
print(kwargs_string) | [
"def print_arg_summary(args: dict) -> None:\n print(\"Arguments object:\")\n print(args)",
"def dump_args(func):\n argnames = func.func_code.co_varnames[:func.func_code.co_argcount]\n fname = func.func_name\n\n def echo_func(*args, **kwargs):\n print fname, \":\", ', '.join('%s=%r' % entry\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a CNF that is satisfied exactly when at most one literal in the list is satisfied | def max_1(lits: List[Literal]):
cnf: Formula = []
for i in range(len(lits)):
for j in range(i + 1, len(lits)):
cnf.append([negate(lits[i]), negate(lits[j])])
return cnf | [
"def atMostOne(literals) :\n \"*** YOUR CODE HERE ***\"\n \"\"\"\n Never exist two expr is true\n for example literals=[A,B,C], we return (~A|~B)&(~A|~C)&(~B|~C)\n \"\"\"\n symbols=[]\n results=[]\n for symbol in literals:\n symbols.append(~symbol)\n for i in range(0,len(literals)-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a BayesGraph object from an input file in .uai format | def __init__(self: BayesGraph, file_object: TextIO):
graph_type = file_object.readline()
if graph_type != "BAYES\n":
raise Exception("File does not contain a Bayes network in .uai format")
num_vars = file_object.readline()
self.cardinalities = [ int(n) for n in file_object.readline().split() ]
... | [
"def from_graphML(self, in_file):\n pass",
"def __init__(self, gfile):\n # open the file\n f = open(gfile, \"r\")\n # read the file\n file = f.readlines()\n\n line_count = 0\n for line in file:\n if line_count == 0:\n # initialise all vert... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a CNF representing evidence (i.e. observed vertices and their values) on the graph from a .uai.evid file representation. Note that in our representation, the indicator variable that the random variable i is set to its jth value is the nth indicator variable where n is the sum of the cardinalities of all the ran... | def evidence_to_formula(self: BayesGraph, file_object: TextIO):
evidence_description = [ int(i) for i in file_object.read().split()]
if evidence_description[0] != (len(evidence_description) - 1) / 2:
raise Exception("evidence file is improperly formatted")
indicators_map = [0]
for cardinality in s... | [
"def to_formula_file_with_evidence(self: BayesGraph, evidence: TextIO, ffile: TextIO, wfile: TextIO):\n weights, cnf = self.to_formula()\n cnf.extend(self.evidence_to_formula(evidence))\n ffile.write(\"p cnf {} {}\\n\".format(len(weights), len(cnf)))\n for clause in cnf:\n clause_str = \" \".join([... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a CNF encoding of the graph represented by this object to a file in DIMACS format, together with an associated weights file. | def to_formula_file_with_evidence(self: BayesGraph, evidence: TextIO, ffile: TextIO, wfile: TextIO):
weights, cnf = self.to_formula()
cnf.extend(self.evidence_to_formula(evidence))
ffile.write("p cnf {} {}\n".format(len(weights), len(cnf)))
for clause in cnf:
clause_str = " ".join([ ("" if sign el... | [
"def write_graph(self, filename):\n pass",
"def to_file(self, fileout):\n dirout =os.path.split(fileout)[0]\n pathlib.Path(dirout).mkdir(parents=True, exist_ok=True)\n\n jout = {'constraints': {}, 'agents': {}, 'variables': {}}\n for a in self.agents:\n agt = self.age... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the cvss_score of this VulnerabilityVulnerability. | def cvss_score(self, cvss_score):
self._cvss_score = cvss_score | [
"def risk_score(self, risk_score: Union[float, PaillierCiphertext]) -> None:\n self._risk_score = risk_score",
"def __setScore(self, score):\n\t\tself.score = score\n\t\treturn self.score",
"def setNodeScore(self, score):\n self.score = score",
"def set_input_score(self, score):\n pass",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the severity of this VulnerabilityVulnerability. | def severity(self, severity):
self._severity = severity | [
"def set_severity(self, severity, operator):\n if severity not in VulnerabilityQuery.VALID_SEVERITY:\n raise ApiError(\"Invalid severity\")\n self._update_criteria(\"severity\", severity, operator)\n return self",
"def severity(self, severity):\n\n if not severity:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the details of this VulnerabilityVulnerability. | def details(self, details):
self._details = details | [
"def details(self, value):\n\t\tself._details = value",
"def vat_details(self, vat_details):\n\n self._vat_details = vat_details",
"def details(self, details: List[Details]):\n\n self._details = details",
"def recruitment_details(self, recruitment_details):\n\n self._recruitment_details =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the cvss_v3 of this VulnerabilityVulnerability. | def cvss_v3(self, cvss_v3):
self._cvss_v3 = cvss_v3 | [
"def v3_data(self, v3_data):\n\n self._v3_data = v3_data",
"def _3(self, _3):\n\n self.__3 = _3",
"def box3(self, box3):\n\n self._box3 = box3",
"def SetVariance(self, *args) -> \"void\":\n return _itkDiscreteGaussianDerivativeImageFilterPython.itkDiscreteGaussianDerivativeImageFil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the windows_details of this VulnerabilityVulnerability. | def windows_details(self, windows_details):
self._windows_details = windows_details | [
"def __update_os_details(self):\n self.os_details['os_name'] = self.os_details.get('ProductName',\n 'Windows')\n self.os_details['distro'] = 'Windows'\n self.os_details['str_os_kernel_bld'] = self.os_details.get('BuildLab',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the source_update_time of this VulnerabilityVulnerability. | def source_update_time(self, source_update_time):
self._source_update_time = source_update_time | [
"def local_update_time(self, local_update_time):\n\n self._local_update_time = local_update_time",
"def set_source_path(self, source_path):\n\n self.source_path = source_path",
"def set_last_update_time(self, time):\n self.last_updated = time",
"def update_venue_timestamps(\n self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads information from .uio file format with relations. Returns a nested list where sublists contain the follwing tokenlevel information. | def read_relations(path_to_file):
relation_info = []
with open(path_to_file) as f:
lines = f.readlines()
for line in lines:
if line.startswith("# sent_id = "):
continue
elif line == "\n":
continue
elif line.startswith("# text =... | [
"def read_level(opt: Config):\n # Multi-Input not implemented, but if we wanted to use it, we would need to sync the tokens\n\n # with World Files, we need the coords of our actual level\n if not opt.coords:\n # Default coords: Ruins\n opt.coords = ((1044, 1060), (64, 80), (1104, 1120)) # y,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if get_reply_delay() returns the value previously set with set_reply_delay(). | def test(device):
old_value = device.get_reply_delay()
assert type(old_value) is int
result = device.set_reply_delay(old_value + 100)
assert result is None
result = device.get_reply_delay()
assert type(result) is int
assert result == old_value + 100
# restore old value
device.set_... | [
"def delay(self, delay):\n delay = int(delay)\n if self.__handler.delay != int(delay):\n self.__handler.delay = delay\n debug('ReplyServer.delay: set to %d ms', delay)",
"def trigger_checkDELAY(self):\n self.open.write('TRIGGER:DELAY?')\n reply = self.open.read() ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function creates new temporary pdf file with same content, assigns given password to pdf and rename it with original file. | def set_password(input_file, user_pass):
# temporary output file with name same as input file but prepended
# by "temp_", inside same direcory as input file.
owner_pass=user_pass
path, filename = os.path.split(input_file)
output_file = os.path.join(path, "temp_" + filename)
output = PdfFileWrit... | [
"def set_password(input_file, user_pass, owner_pass):\n # temporary output file with name same as input file but prepended\n # by \"temp_\", inside same direcory as input file.\n path, filename = os.path.split(input_file)\n output_file = os.path.join(path, \"temp_\" + filename)\n\n output = PyPDF2.Pd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute wkhtmltopdf as a subprocess in order to convert html given in input into a pdf document. | def _run_wkhtmltopdf_enscript(self, headers, footers, bodies, landscape, paperformat, spec_paperformat_args=None, save_in_attachment=None, set_viewport_size=False, password=False ):
if not password:
return self._run_wkhtmltopdf(headers, footers, bodies, landscape, paperformat, spec_paperformat_args=... | [
"def xhtml2pdf(xhtml_file, files, temp_dir, print_style, pdfgen, output_pdf, verbose=False):\n\n CSS_FILE = os.path.join(BASE_PATH, 'css', '%s.css' % print_style)\n\n # Run Prince (or an Opensource) to generate an abstract tree 1st\n strCmd = [pdfgen, '-v', '--style=%s' % CSS_FILE, '--output=%s' % output_pdf, xh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves all games with their length. | def get_all_games(self):
games = []
rows = self.session.query(Game, func.count(Action.id)).outerjoin(
Action, and_(Game.id == Action.game_id, Action.code == ActionCodes.TURN)).group_by(
Game.id).order_by(Game.id).all()
for row in rows:
game_data, game_le... | [
"def get(self):\n return list(Game.query.all()), 200",
"def get_game_list(self):\n game_list = self.dal.get_games()\n return make_response(True, data=game_list)",
"def get_all_games():\n return league.GameLog().overall()['GAME_ID'].unique()",
"def get(self):\n return {'status': ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Closes and commits session. | def close(self):
self.session.commit()
self.session.close() | [
"async def __aexit__(self, *exc):\n await self.session.close()\n self.db_session.commit()",
"def commit(self):\n SessionMemoryStore.sessions[self.token] = self.session",
"def commit(self, session):\n session.commit()",
"def session_commit(self, session):\n # this may happen ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses Client args from the arg string. | def parse_args():
parser = argparse.ArgumentParser(description='Parse Client args.')
parser.add_argument('-p', '--port', type=int, default=8080,
help='Set the port to talk to')
parser.add_argument('-m', '--message', type=str,
help='Message ... | [
"def parse(self, cli_args=str(_sys.argv)[1:-1]):\n if cli_args is not _sys.argv:\n cli_args = cli_args.split()\n for i in range(len(cli_args)):\n cli_args[i] = cli_args[i].split('=')\n cli_args = sum(cli_args, [])\n\n self._ensure_required(cli_args)\n self._e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clear all logging configs for the `mltk` package. | def clear_logging() -> None:
logger = logging.getLogger('mltk')
logger.propagate = True
logger.setLevel(logging.NOTSET)
logger.handlers.clear() | [
"def clear_loggers():\n import logging\n\n loggers = [logging.getLogger()] + list(logging.Logger.manager.loggerDict.values())\n for logger in loggers:\n handlers = getattr(logger, \"handlers\", [])\n for handler in handlers:\n logger.removeHandler(handler)",
"def clear_logs():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. Example res = source.min() | def min(self, comparer=None):
return self.min_by(identity, comparer).map(first_only) | [
"def min(sequence):\n return __builtin__.min(sequence)",
"def min_by(collection, transform_function):\n if len(collection) == 0:\n return None\n\n min_value = transform_function(collection[0])\n min_item = collection[0]\n\n for item in collection[1:]:\n this_value = transform_func... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Caseinsensitive `getattr` for enums. | def get_caseins_enum_attr(enum: tp.NamedTuple, attr: str) -> tp.Any:
lower_attr_keys = list(map(lambda x: x.lower(), enum._fields))
attr_idx = lower_attr_keys.index(attr.lower())
orig_attr = enum._fields[attr_idx]
return getattr(enum, orig_attr) | [
"def get_enum_name(self):\n return self.name.upper()",
"def for_name(name='', enum_type=None, enum_description=''):\n found = None\n _name = name.upper()\n\n try:\n found = enum_type[_name]\n except Exception:\n raise ValueError(\"Unsupported {0} {1}\".form... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prepare value of an enum. `enum` is expected to be an instance of `collections.namedtuple`. `value` can a string of any case or a tuple/list of such, otherwise returns unmodified value. | def prepare_enum_value(enum: tp.NamedTuple, value: tp.Any) -> tp.Any:
def _converter(x):
if isinstance(x, str):
return get_caseins_enum_attr(enum, str(x))
return x
if isinstance(value, str):
# Convert str to int
value = _converter(value)
elif isinstance(value, (... | [
"def _parse_enum_value(enum_value_ast: dict) -> \"EnumValueNode\":\n return EnumValueNode(\n value=enum_value_ast[\"value\"],\n location=_parse_location(enum_value_ast[\"loc\"]),\n )",
"def enum_converter(value: typing.Union[str, int]) -> enum.Enum:\n value = int_converter(value)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create value map from enum. | def to_value_map(enum: tp.NamedTuple) -> dict:
value_map = dict(zip(tuple(enum), enum._fields))
if -1 not in value_map:
value_map[-1] = None
return value_map | [
"def to_dict(self):\n d = asdict(self)\n for k, v in d.items():\n if isinstance(v, Enum):\n d[k] = v.value\n if isinstance(v, list) and len(v) > 0 and isinstance(v[0], Enum):\n d[k] = [x.value for x in v]\n return d",
"def enum_to_dict_fn(e:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a transaction based on cart information | def create_transaction_from_cart(cart: Cart) -> DbTransaction:
res = DbTransaction(type=TransactionType.PURCHASE, currency=cart.currency, timestamp=now(),
total_amount=cart.total_amount, state=TransactionState.INITIALIZED, id=ObjectId())
items = []
vat: Dict[Decimal, Vat] = {}
fo... | [
"def create(self, request):\n\n cart = Cart.objects.create(user=request.user)\n return Response({'cart': CartSerializer(cart).data})",
"def create_cart_checkout(self,\r\n account_number,\r\n cart_id,\r\n cart_checkou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finalize purchase transaction and create receipt | def _finalize_traveller_purchase(auth_ctx: AuthorizationContext, transaction: DbTransaction, finalization_data: str) \
-> None:
if transaction.payment_method_transaction_data:
payment_method = get_wallet_payment_method(transaction.wallet, transaction.payment_method_id)
psd = get_payment_serv... | [
"def finalize_transaction_receipt(auth_ctx: AuthorizationContext, transaction_id: str,\n receipt_req: Dict[str, Any]) -> Receipt:\n req = ReceiptRequest.from_dict(receipt_req)\n transaction = finalize_transaction(auth_ctx, transaction_id, req.payment_reference)\n return tran... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create MTB products and set cancellable state | def _finalize_create_mtb_products(transaction):
transaction.cancellable = True
transaction.cancellable_expire = expire(shared.config.parameters.purchase.cancel_ttl_max)
try:
for item in transaction.items:
item.mtb_product_ids = []
for mp in create_mtb_products(item, transacti... | [
"def create_products():",
"def make(self, product):\n resp = None\n product_id = product[0]\n product_name = product[1]\n logging.info('Coffee machine status checking.')\n status_table = self.statusTable\n\n logging.info('Make product: %s.', product_name)\n if not ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mark products and transaction as purchased | def _mark_purchased(transaction: DbTransaction) -> None:
transaction.state = TransactionState.PURCHASED
for item in transaction.items:
if item.mtb_product_ids:
for mp_id in item.mtb_product_ids:
try:
mtb_prod = get_db_mtb_product(None, mp_id, all=True, ref... | [
"def notify_purchased(self):\n notify(CheckoutComplete(self.old_cart))",
"def make_purchase(self):\n sale_type = self.get_sale_type()\n if len(self.rhslist) != 2:\n raise self.BrokerError(\"You must ask for both an amount and a price.\")\n amount = self.get_amount(self.rhsli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finalize vendor transaction and create receipt | def _finalize_vendor_purchase(auth_ctx: AuthorizationContext, transaction: DbTransaction, finalization_data: str) \
-> None:
if not finalization_data:
abort(400, "Vendor finalization requires payment reference")
transaction.payment_reference = finalization_data
try:
_finalize_create_... | [
"def finalize_transaction_receipt(auth_ctx: AuthorizationContext, transaction_id: str,\n receipt_req: Dict[str, Any]) -> Receipt:\n req = ReceiptRequest.from_dict(receipt_req)\n transaction = finalize_transaction(auth_ctx, transaction_id, req.payment_reference)\n return tran... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finalize transaction and create receipt | def finalize_transaction_receipt(auth_ctx: AuthorizationContext, transaction_id: str,
receipt_req: Dict[str, Any]) -> Receipt:
req = ReceiptRequest.from_dict(receipt_req)
transaction = finalize_transaction(auth_ctx, transaction_id, req.payment_reference)
return transaction.t... | [
"def _finalize_traveller_purchase(auth_ctx: AuthorizationContext, transaction: DbTransaction, finalization_data: str) \\\n -> None:\n if transaction.payment_method_transaction_data:\n payment_method = get_wallet_payment_method(transaction.wallet, transaction.payment_method_id)\n psd = get_pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cancel transaction and refund payments and invalidate products | def cancel_payment_transaction(auth_ctx: AuthorizationContext, transaction: DbTransaction) -> None:
for item in transaction.items:
if item.mtb_product_ids:
for mp_id in item.mtb_product_ids:
try:
prod = get_db_mtb_product(auth_ctx, mp_id)
c... | [
"def spare_cancel(self,cr,uid,ids,context=None):\n\n exchange = self.pool.get('exchange.order')\n wf_service = netsvc.LocalService(\"workflow\")\n for rec in self.browse(cr , uid ,ids):\n exchange_ref = rec.ir_ref\n exchange_id = exchange.search(cr , uid , [('name' , '=' ,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try to refund payment, abort if failed. | def _refund_payment(transaction: DbTransaction, reason: str) -> None:
if transaction.payment_method_amount:
if transaction.payment_method_transaction_data:
payment_method = get_wallet_payment_method(transaction.wallet, transaction.payment_method_id)
psd = get_payment_service_driver(g... | [
"def refund(self, amount=None):\n gateway = get_gateway(self.gateway_name)\n\n # TODO: can this implementation live in dinero.gateways.AuthorizeNet?\n try:\n return gateway.refund(self, amount or self.price)\n except exceptions.PaymentException:\n if amount is None ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Release possible purse reservation | def _release_purse_reservation(transaction: DbTransaction) -> None:
if transaction.purse_reservation_id is not None:
try:
delete_reservation(transaction.wallet.purse_id, transaction.purse_reservation_id)
transaction.purse_reservation_id = None
transaction.save()
e... | [
"def release(self):\n self.free = True\n self.guest = None\n self.occupy_time = None",
"def release(self):\n\n self.transaction(self.holdingshares, ['Cover', 'Sell'][self.action])\n self.holding = 0\n print \" --- %s: released %s shares at gain of %s ---\" % (self.ticker,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Release possible payment method reservation | def _release_payment_method_reservation(transaction: DbTransaction, psd: PaymentServiceDriver,
payment_transaction: PaymentServiceTransaction) -> None:
if transaction.payment_method_amount:
if transaction.payment_method_transaction_data:
try:
... | [
"def _release_purse_reservation(transaction: DbTransaction) -> None:\n if transaction.purse_reservation_id is not None:\n try:\n delete_reservation(transaction.wallet.purse_id, transaction.purse_reservation_id)\n transaction.purse_reservation_id = None\n transaction.save()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send an email with the a receipt for the transaction to the user. Return true if email address found. | def _send_receipt_email(user: User, transaction: DbTransaction, email: str = None) -> bool:
if not email:
email = user.receipt_email
if email:
locale = user.locale
if locale is None:
locale = shared.config.default_locale
logger.debug("Send receipt in %s to %s", locale... | [
"def add_email(self):\n if EMAIL_CONFIRMATION:\n from . import EmailAddress\n self.is_active = False\n self.save()\n EmailAddress.objects.add_email(self, self.email)\n return True\n else:\n return False",
"def confirmation_email(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove id from set. Return True if removed or no set. | def _remove_id_from_optional_set(id: str, id_set: Optional[Set[str]]):
if id_set is None:
return True
try:
id_set.remove(id)
return True
except KeyError:
return False | [
"def safe_remove_set(input_set: set, value):\n try:\n input_set.remove(value)\n except KeyError:\n print(\"trying to remove something funky from a set\")\n pass",
"def removeById(self, id):\n for i in range(len(self.list)):\n if self.list[i].getId()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encode all labels with the given batchsize. Wrapped by memory utilization maximizer to automatically reduce the batch size if needed. | def _encode_all_memory_utilization_optimized(
encoder: "TextEncoder",
labels: Sequence[str],
batch_size: int,
) -> torch.Tensor:
return torch.cat(
[encoder(batch) for batch in chunked(tqdm(map(str, labels), leave=False), batch_size)],
dim=0,
) | [
"def encode_all(\n self,\n labels: Sequence[str],\n batch_size: Optional[int] = None,\n ) -> torch.FloatTensor:\n return _encode_all_memory_utilization_optimized(\n encoder=self, labels=labels, batch_size=batch_size or len(labels)\n ).detach()",
"def next_batch(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encode all labels (inference mode & batched). | def encode_all(
self,
labels: Sequence[str],
batch_size: Optional[int] = None,
) -> torch.FloatTensor:
return _encode_all_memory_utilization_optimized(
encoder=self, labels=labels, batch_size=batch_size or len(labels)
).detach() | [
"def encode_labels(labels):\r\n le = preprocessing.LabelEncoder()\r\n norm_labels = le.fit_transform(labels)\r\n return norm_labels",
"def _save_label_encoders(label_encoder_dict: defaultdict, output_dir: str):\n for label, encoder in label_encoder_dict.items():\n with open(os.path.join(output_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
v[j]u[i]=c[i,j] if x[i,j]>0 v[0]=0 | def calc_u_v(c: np.ndarray, x: np.ndarray) -> (np.array, np.array):
assert c.shape == x.shape
(m, n) = c.shape
# constructing a graph (adjacency list)
graph = defaultdict(list)
for i in range(m):
for j in range(n):
if x[i, j] is not None:
graph[i].append(m+j)
... | [
"def nonzero_values(x):\n return x[x != 0]",
"def proj_cap_ent(d0, v):\n d = d0\n m = len(d)\n if v < 1.0 / m:\n print \"error\"\n # this is more numerically stable than the original pseudo code.\n uu = np.sort(d, kind='quicksort')\n cs = np.cumsum(uu)\n # uu = np.sort(d, kind='quic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
detected object on an image that is passed in a request stream | def detect_objects_image_from_request_body(self, img_name, output_image_name):
print(f'{img_name} detected object on an image that is passed in a request stream')
method = 'ssd'
threshold = 50
includeLabel = True
includeScore = True
allowedLabels = "person"
block... | [
"def image(obj):\n return match(obj, image_matchers)",
"def visualize_detect_objects_image_from_request_body(self, img_name, output_image_name):\n print('Visualize detected object on an image that is passed in a request stream')\n\n def write_to_file(file_path, file_name):\n shutil.cop... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visualize detected object on an image that is passed in a request stream. | def visualize_detect_objects_image_from_request_body(self, img_name, output_image_name):
print('Visualize detected object on an image that is passed in a request stream')
def write_to_file(file_path, file_name):
shutil.copy(file_name, file_path)
print('Image ' + ' i... | [
"def detect_objects_image_from_request_body(self, img_name, output_image_name):\n print(f'{img_name} detected object on an image that is passed in a request stream')\n\n method = 'ssd'\n threshold = 50\n includeLabel = True\n includeScore = True\n allowedLabels = \"person\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the response to the get request to the page of autolab specified by path | def request_autolab(path):
if not(path.startswith(AUTOLAB_URL)):
path = requests.compat.urljoin(AUTOLAB_URL, path)
response = requests.get(path, headers=headers, cookies=cookies)
return response | [
"def do_GET(self):\n path = self.path\n name = path[1:] # strip the leading slash\n \n # if the path is the name of a known pokemon, get its html string and construct the response:\n if name in self.pokemon_dictionary:\n self.send_response(http.HTTPStatus.OK)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the soup of the page of autolab specified by path | def soup_autolab(path):
response = request_autolab(path)
soup = BeautifulSoup(response.text, 'html.parser')
return soup | [
"def extractor(url,wait_time):\n driver = webdriver.Chrome()\n driver.get(url)\n time.sleep(wait_time) # important\n\n html_doc = driver.page_source # stores the source HTML code in the driver's page_source attribute\n soup = BeautifulSoup(html_doc, 'html.parser')\n abstract = soup.find('div', {'c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find all divs that are cards in the soup | def get_cards(soup):
return soup.findAll("div", {"class": "card"}) | [
"def get_clubs(soup):\n return soup.findAll('div', {'class': 'box'})",
"def card_list(search_url):\n card_list = []\n card_link_re = re.compile('^\\/cards\\/[0-9].*')\n \n main_url = \"https://www.hearthpwn.com\"\n \n raw_html = simple_get(main_url+search_url)\n if raw_html is not None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the title of the card, where card is a BeautifulSoup object | def get_card_title(card):
card_title = card.find("span", {"class": "card-title"})
assert card_title is not None
card_title = slugify(card_title.string)
return card_title | [
"def extract_book_title(entry: bs4.BeautifulSoup) -> str:\n try:\n return entry.find(\"div\", attrs={\"class\": \"headsummary\"}).find(\"h1\").text.strip()\n except Exception:\n return \"\"",
"def get_review_title(full_review):\n title_div = full_review.find_all(\"div\", class_=REVIEW_TITLE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get tasks from a card | def get_tasks(card):
tasks = []
anchors = card.findAll("a", {"class": "collection-item"}, href=True)
for anchor in anchors:
task_title = slugify(anchor.string)
task_link = anchor['href']
tasks.append((task_title, task_link))
return tasks | [
"async def get_fetch_tileables(self, task_id: str) -> List[Tileable]:",
"def get_task(self, task_name):",
"def tasks(**_):\n for task in filter(bool, get_all_tasks()):\n print(task)",
"def get_card():\n card = '{\"id\": \"5f835afcf6400f7c70f9597e\", \"checkItemStates\": [], \"closed\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the filename from the download link response | def get_filename(response):
if 'Content-Disposition' in response.headers:
filename_matches = re.findall(
r'filename="(.*)"',
response.headers['Content-Disposition'])
assert len(filename_matches) == 1
return filename_matches[0]
else:
return response.url.spl... | [
"def _get_http_response_filename(resp: Response, link: Link) -> str:\n filename = link.filename # fallback\n # Have a look at the Content-Disposition header for a better guess\n content_disposition = resp.headers.get(\"content-disposition\")\n if content_disposition:\n filename = parse_content_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scrape submissions, handouts, and writeups from a course | def process_course(course):
course_title, course_link = course
print()
print("PROCESSING COURSE ", course)
soup = soup_autolab(course_link)
assns = get_assns(soup)
for assn in assns:
process_assn(assn, course_title) | [
"def scraper(page):\n\n # Initialize empty lists\n titles = []\n urls = []\n techs = []\n instructors = []\n\n # Start scraper and get course blocks\n soup = BeautifulSoup(page, 'html')\n div = soup.findAll(\"div\", { \"class\": \"course-block\"})\n\n # Loop over all courses\n for elem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute Lasso path with Celer and primal extrapolation. | def path(self, X, y, alphas, coef_init=None, return_n_iter=True, **kwargs):
return celer_primal_path(
X, y, alphas=alphas, coef_init=coef_init,
max_iter=self.max_iter, return_n_iter=return_n_iter,
max_epochs=self.max_epochs, p0=self.p0, verbose=self.verbose,
tol=s... | [
"def _lifter(self, cepstra, L=22):\n if L > 0:\n nframes, ncoeff = np.shape(cepstra)\n n = np.arange(ncoeff)\n lift = 1 + (L / 2) * np.sin(np.pi * n / L)\n return lift * cepstra\n else:\n # values of L <= 0, do nothing\n return cepstra"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show conducto login profiles recognized on this computer. | def profile_list():
conf = api.Config()
for profile in conf.profile_sections():
data = conf._profile_general(profile)
try:
_print_profile(profile, data)
except KeyError:
print(
log.format(
f"Invalid or incomplete profile '{pro... | [
"def list_profiles():\n marker = {True: \"(*)\", False: \" \"}\n print(\" Available profiles:\")\n for profile in os.listdir(SCRIPT_DIRECTORY):\n print(\" {} {}\".format(marker[profile == DEFAULT_PROFILE], profile))",
"async def profiles(self, ctx):\n if ctx.invoked_subcommand is None:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new login profile for a specified Conducto URL. | def profile_add(url, default=False, token=None):
if token is not None:
os.environ["CONDUCTO_TOKEN"] = token
profile = _profile_add(url, default=default)
conf = api.Config()
data = conf._profile_general(profile)
_print_profile(profile, data) | [
"def set_access_profile_url(self, access_profile, obj, profile, snmp_ro_community):\n if profile is None:\n raise CommandError(\"Script name must contain profile when using URLs\")\n url = URL(obj)\n access_profile.profile = profile\n access_profile.scheme = Script.get_scheme_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start the local agent for the default or specified profile. | def profile_start_agent(id=None):
if id is not None:
os.environ["CONDUCTO_PROFILE"] = id
token = api.Config().get_token_from_shell()
if os.getenv("CONDUCTO_OS", "").startswith("Windows"):
os.environ["WINDOWS_HOST"] = "plain"
start_status = agent_utils.launch_agent(token=token)
if... | [
"def start_seattle():\n starter_file_path = [SEATTLE_FILES_DIR + os.sep + get_starter_file_name()]\n if OS == \"WindowsCE\":\n windows_api.launch_python_script(starter_file_path)\n else:\n if SILENT_MODE:\n p = subprocess.Popen(starter_file_path,stdout=subprocess.PIPE,\n stde... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop the local agent for the default or specified profile. | def profile_stop_agent(id=None):
if id is not None:
os.environ["CONDUCTO_PROFILE"] = id
container_name = agent_utils.agent_container_name()
running = container_utils.get_running_containers()
if f"{container_name}-old" in running:
cmd = ["docker", "stop", f"{container_name}-old"]
... | [
"def stop_cluster(self, profile):\n self.check_profile(profile)\n data = self.profiles[profile]\n if data['status'] == 'stopped':\n raise web.HTTPError(409, u'cluster not running')\n data = self.profiles[profile]\n cl = data['controller_launcher']\n esl = data['e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Count number of boxes based on the product packaging | def count_boxes(packages: List[dict]) -> int:
volume = sum([p["width"]*p["length"]*p["height"] for p in packages])
weight = sum([p["weight"] for p in packages])
return max(math.ceil(volume/BOX_VOLUME), math.ceil(weight/BOX_WEIGHT)) | [
"def test_team_builder_config_product_groups_count_get(self):\n pass",
"def quantity_size():",
"def number_of_products():\n return NUMBER_OF_PRODUCTS",
"def count_bag_contents(rules, outer):\n \n contents = rules[outer]\n \n # we count ourself\n count = 1\n \n for inner_bag in c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the delivery cost for a specific address and list of products | def get_pricing(products: List[dict], address: dict) -> int:
return count_boxes([p["package"] for p in products]) * get_shipping_cost(address) | [
"def cost_of(amount, item, hours, products):\n for items in products:\n if items[0] == item:\n return float(items[2]) * float(amount) * float(hours)",
"def __get_order_cost(self, order_qty, pack_costs):\n total_cost = 0.00\n\n for pack, qty in order_qty.iteritems():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lambda function handler for /backend/pricing | def handler(event, _):
# Verify that this is a request with IAM credentials
if iam_user_id(event) is None:
logger.warning({"message": "User ARN not found in event"})
return response("Unauthorized", 403)
# Extract the request body
try:
body = json.loads(event["body"])
except... | [
"def ex_get_pricing(self):\r\n action = '/pricing/'\r\n response = self.connection.request(action=action, method='GET')\r\n return response.object",
"def lambda_handler(event, context):\n logger = LOGGER('__cur_cost_usage__').config()\n\n budget = AccountBudget()\n # Get the list of ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deregisters an existing participant | def participants_deregister(id):
query = "UPDATE user SET registered=0 WHERE user_id='{0}'".format(id)
connection = app.config["PYMYSQL_CONNECTION"]
# submit query and retrieve values
with connection.cursor() as cursor:
cursor.execute(query)
return "done.", 200 | [
"def remove_participant(self, participant_id):\n del self._participants[participant_id]",
"def test_auth_delete_participant(self):\n pass",
"async def deregister(self, ctx: Context):\n if ctx.channel.name != self._monitor_channel:\n return\n author_id = str(ctx.message.aut... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns whether the participant exist, and whether it belongs in an existing group already | def participants_is_already_grouped(id):
connection = app.config["PYMYSQL_CONNECTION"]
query = "SELECT group_id FROM user WHERE user_id='{0}'".format(id)
# submit query and retrieve values
with connection.cursor() as cursor:
cursor.execute(query)
query_result = cursor.fetchall()
ou... | [
"def GroupExists(self, groupname):\n return groupname in self._groups",
"def group_exists(c, runner, group):\n return group in groups(c, runner=runner)",
"def group_exists(self, group_name):\n try:\n self.rmc.resource_groups.get(group_name)\n return True\n except CloudE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name of configuration mode to use. Modes are predefined configurations of security controls, extension allowlists and guest configuration, maintained by Microsoft. | def config_mode(self) -> str:
return pulumi.get(self, "config_mode") | [
"def config_mode(self):\n\n pass",
"def user_mode(self):\n return self.config['USER_MODE'].lower()",
"def get_custom_mode_name(system,custom_mode):\n\n return \"%d\" % custom_mode",
"def runmode(self) -> RunMode:\n return RunMode(self._config.get('runmode', RunMode.OTHER))",
"def get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Specified whether the guest configuration service is enabled or disabled. | def guest_configuration_enabled(self) -> str:
return pulumi.get(self, "guest_configuration_enabled") | [
"def hw_virt_ex_enabled(self):\n ret = self._get_attr(\"HWVirtExEnabled\")\n return ret",
"def supports_configuration_admin(self):\n return # boolean",
"def dhcp_enabled(self):\n ret = self._get_attr(\"DHCPEnabled\")\n return ret",
"def enabled(cls):\n return backend... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Specifies the URL of the proxy to be used. | def proxy_url(self) -> str:
return pulumi.get(self, "proxy_url") | [
"def set_http_proxy(self, proxy_url):\r\n result = self._parse_proxy_url(proxy_url=proxy_url)\r\n scheme = result[0]\r\n host = result[1]\r\n port = result[2]\r\n username = result[3]\r\n password = result[4]\r\n\r\n self.proxy_scheme = scheme\r\n self.proxy_h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The error additional info. | def additional_info(self) -> Sequence['outputs.ErrorAdditionalInfoResponse']:
return pulumi.get(self, "additional_info") | [
"def _error_details(self):\n return ErrorDetails(\n protocol=self._protocol_error,\n noniterable_str=self._noniterable_str_error,\n typed_dict=self._typed_dict_error\n )",
"def _err_description(self) -> str:\n return ''",
"def errormessage(self):\n return self._errormess... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |