query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Utility function training a simple CNN for 1 client in a federated setting and adding those weights to the weights_accountant. Call this function in a federated loop that then makes the weights_accountant average the weights to send to a global model. | def train_client_model(client, local_epochs, model, train_data, train_labels, val_data, val_labels, val_people,
val_all_labels, weights_accountant, individual_validation):
weights = model.get_weights()
model, history = train_cnn('federated', model, local_epochs, train_data, train_labels,... | [
"def train(federated_averaging_process, num_rounds, num_clients_per_round, summary_writer):\n # Create a environment to get communication cost.\n environment = set_sizing_environment()\n\n # Initialize the Federated Averaging algorithm to get the initial server state.\n state = federated_averaging_process.initi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes a client model and kicks off the training of that client by calling "train_client_model". | def client_learning(model, client, local_epochs, train_data, train_labels, val_data, val_labels, val_people,
val_all_labels, weights_accountant, individual_validation):
# Get all client specific data points
client_data = train_data.get(client)
client_labels = train_labels.get(client)
... | [
"def train_client_model(client, local_epochs, model, train_data, train_labels, val_data, val_labels, val_people,\n val_all_labels, weights_accountant, individual_validation):\n\n weights = model.get_weights()\n model, history = train_cnn('federated', model, local_epochs, train_data, trai... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
One round of communication between a 'server' and the 'clients'. Each client 'downloads' a global model and trains a local model, updating its weights locally. When all clients have updated their weights, they are 'uploaded' to the server and averaged. | def communication_round(model, clients, train_data, train_labels, train_people, val_data, val_labels, val_people,
val_all_labels, local_epochs, weights_accountant, individual_validation, local_operation):
# Split train and validation data into clients
train_data, train_labels = dL.split... | [
"def send_model(self, client_socket):\n\n if self.ROUNDS == self.training_cycles:\n self.stop_flag = True\n\n weights = np.array(self.GLOBAL_WEIGHTS)\n\n data = {\"STOP_FLAG\":self.stop_flag,\"WEIGHTS\":weights}\n\n data = pickle.dumps(data)\n data = bytes(f\"{len(data)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utility function adding individual validation callback, to track local validation metrics. | def add_additional_validation_callback(callbacks, val_data, val_labels, val_people, val_all_labels):
_, val_data_split, val_labels_split, val_people_split = dL.split_data_into_labels(0, val_all_labels, False,
val_data, val_labe... | [
"def add_validation_rules(self, runner):\n return",
"def validation_event(self, message):",
"def validate(cls):\n\n def register_onvalidation(form):\n\n onvalidation = current.auth.settings.register_onvalidation\n if onvalidation:\n from gluon.tools import call... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get data from this or last time sliced table | def get_data(self, table_name, key, timedelta_slice=1, pickled=True):
item = self.get_item(table_name, key, timedelta_slice=timedelta_slice)
if item:
if pickled and item.get(self.data_property, None):
return pickle.loads(str(item[self.data_property]))
else:
... | [
"def get_data(self, date_time):\n id_columns = ','.join([col for col in self.table_primary_keys if col not in ['EFFECTIVEDATE', 'VERSIONNO']])\n return_columns = ','.join(self.table_columns)\n with self.con:\n cur = self.con.cursor()\n cur.execute(\"DROP TABLE IF EXISTS te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
save/update counter shard indice to the seperated index table | def _update_counter_indice(self, table_name, key, shard, retry=3):
index_table_name = table_name + _COUNTER_SHARD_INDEX_TABLE_SUFFIX
try:
self.conn.update_item(index_table_name,
{self.hash_key_name: {"S": key}},
{self.data_p... | [
"def save_index(self, fn):\r\n utils.save_obj((self.inverted_idx, self.postingDict, self.docs_to_info_dict), fn)",
"def _write_shard(filename, dataset, indices):\n with tf.io.TFRecordWriter(filename) as writer:\n for j in indices:\n writer.write(dataset[j])",
"def _write_shard(filename, dataset,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
delete sharded counter use hight level table to do batch write | def delete_counter(self, table_name, key):
sharded_keys = self._get_counter_keys(table_name, key)
if sharded_keys:
counter_table = self.get_table(table_name)
with counter_table.batch_write() as batch:
for sharded_key in sharded_keys:
batch.dele... | [
"def remove_counter(self, key, path, consistency_level):\r\n pass",
"def remove_counter(self, key, path, consistency_level):\r\n self.send_remove_counter(key, path, consistency_level)\r\n self.recv_remove_counter()",
"def delete_counts(self):\n\n qry = \"TRUNCATE TABLE baseline.parameter_value_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
assert exception is raised if a repo has no tracking branch | def test_repo_no_remote(repo):
with pytest.raises(ValueError):
gitb.pull(repo.working_tree_dir) | [
"def test_branch_fail(repository: Repository) -> None:\n with pytest.raises(KeyError):\n repository.branch(\"branch\")",
"def testNonExistent(self):\n self.assert_(not self._repositoryExists())",
"def test_no_tag_no_branch(self):\n name = 'test_repo'\n protocol = 'test_protocol'\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a successor edge map, produce an inverted predecessor edge map. | def get_pred(succ):
out = {key: [] for key in succ}
for p, ss in succ.items():
for s in ss:
out[s].append(p)
return out | [
"def reorder_edges(edges, flip_map):\n flipped_edges = np.hstack((edges[:, 3:], edges[:, :3]))\n\n reordered_edges = np.array([edges[i] if flip_map[i] == 0 else flipped_edges[\n i] for i in xrange(edges.shape[0])])\n\n return reordered_edges",
"def associate_predecessors(gra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a successor edge map, produce a list of all the nodes in the graph in postorder by appending to the `out` list. | def postorder_helper(succ, root, explored, out):
if root in explored:
return
explored.add(root)
for s in succ[root]:
postorder_helper(succ, s, explored, out)
out.append(root) | [
"def rebuild_path(self, node_map: dict = None, src: int = 0, dest: int = 0) -> list:\n if node_map is None or src == dest:\n return None\n ans = [self._graph.get_node(dest)]\n next_node = node_map.get(dest)\n ans.append(next_node)\n while next_node.key is not src: # Ba... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the transaction_notification_url of this StoreUrlConfiguration. | def transaction_notification_url(self, transaction_notification_url):
self._transaction_notification_url = transaction_notification_url | [
"def recurring_transaction_notification_url(self, recurring_transaction_notification_url):\n\n self._recurring_transaction_notification_url = recurring_transaction_notification_url",
"def notify_url(self, notify_url):\n\n self._notify_url = notify_url",
"def method_notification_url(self, method_no... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the recurring_transaction_notification_url of this StoreUrlConfiguration. | def recurring_transaction_notification_url(self, recurring_transaction_notification_url):
self._recurring_transaction_notification_url = recurring_transaction_notification_url | [
"def transaction_notification_url(self, transaction_notification_url):\n\n self._transaction_notification_url = transaction_notification_url",
"def method_notification_url(self, method_notification_url):\n\n self._method_notification_url = method_notification_url",
"def notify_url(self, notify_url... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the response_success_url of this StoreUrlConfiguration. | def response_success_url(self, response_success_url):
self._response_success_url = response_success_url | [
"def success_url(self, success_url):\n\n self._success_url = success_url",
"def on_success_url(self, on_success_url):\n\n self._on_success_url = on_success_url",
"def get_success_url(self):\n if self.succes_url:\n return self.succes_url\n\n raise ImproperlyConfigured(\"Eit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the response_failure_url of this StoreUrlConfiguration. | def response_failure_url(self, response_failure_url):
self._response_failure_url = response_failure_url | [
"def response_success_url(self, response_success_url):\n\n self._response_success_url = response_success_url",
"def response_kafka_connection_url(self, response_kafka_connection_url: str):\n\n self._response_kafka_connection_url = response_kafka_connection_url",
"def with_error_url(self, url):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the skip_result_page_for_success of this StoreUrlConfiguration. | def skip_result_page_for_success(self, skip_result_page_for_success):
self._skip_result_page_for_success = skip_result_page_for_success | [
"def skip_result_page_for_failure(self, skip_result_page_for_failure):\n\n self._skip_result_page_for_failure = skip_result_page_for_failure",
"def v2_runner_on_skipped(self, result):\n super(Callback, self).v2_runner_on_skipped(result)\n self._store(result, STATUS_SKIPPED)",
"def set_skip(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the skip_result_page_for_failure of this StoreUrlConfiguration. | def skip_result_page_for_failure(self, skip_result_page_for_failure):
self._skip_result_page_for_failure = skip_result_page_for_failure | [
"def skip_result_page_for_success(self, skip_result_page_for_success):\n\n self._skip_result_page_for_success = skip_result_page_for_success",
"def v2_runner_on_skipped(self, result):\n super(Callback, self).v2_runner_on_skipped(result)\n self._store(result, STATUS_SKIPPED)",
"def set_skip(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the overwrite_url_allowed of this StoreUrlConfiguration. | def overwrite_url_allowed(self, overwrite_url_allowed):
self._overwrite_url_allowed = overwrite_url_allowed | [
"def overwrite_url(self):\n if self.has_url_overwrite:\n return self.path\n return None",
"def set_shortener_url(url):\n # Checks that the user that triggered the operation is the owner. If not we cannot allow the\n # operation because only the owner of the smart contract can change... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate IV curve for cells and substrings in series given current and voltage in increasing order by voltage, the average short circuit current and the max current at the breakdown voltage. | def calcSeries(self, I, V, meanIsc, Imax):
# make sure all inputs are numpy arrays, but don't make extra copies
I = np.asarray(I) # currents [A]
V = np.asarray(V) # voltages [V]
meanIsc = np.asarray(meanIsc) # mean Isc [A]
Imax = np.asarray(Imax) # max current [A]
# c... | [
"def EKV(V_d, V_g, V_s = 0, V_t = 26*1e-3 ,V_tn = 0.4, V_am = 50*1e6, L=540*1e-9, my=380*1e-5):\n e_ox = 3.45*1e-11\n t_ox = 2.7*1e-9\n C_ox = e_ox/t_ox\n k_n = my*C_ox\n I_s = 2*k_n*(V_t**2)\n \n Lam = 1/(V_am*L) #proceess paramterer V_a' * Channel length Im gonna make this 0.8 to start\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the sequence of series cells between parallel crossties. | def get_series_cells(cell_pos_column, prev_col=None):
series_cells = [] # empty list of indices of cells in series
# if the previous column is specified, find the indices of cells in the
# current column that correspond to cells between parallel crossties in the
# previous column
if prev_col:
... | [
"def cells(self):\n \"\"\"\n Note that we use the convention that the first cell is (1,1)\n \"\"\"\n spart_star = self.star()\n part = Partition(list(spart_star))\n coordinates = part.cells()\n coordinates = [(x+1, y+1) for x, y in coordinates]\n return co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dot product between two points | def dot(p1, p2):
return p1[0] * p2[0] + p1[1] * p2[1] | [
"def dot(a,b):\n return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]",
"def dot(x, y):\n return sum([a * b for a, b in zip(x, y)])",
"def dotproduct(x, y):\n return sum(vector_apply(lambda a, b: a * b, x, y))",
"def dotProduct(v1, v2):\n n1 = normalize(v1)\n n2 = normalize(v2)\n return n1[0] * n2[0] + n1[1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the similarity between two lines, based on their angles | def angle_similarity(l1, l2):
return angle(l1, l2) | [
"def line_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD):\n d = line_distance_similarity(p1a, p1b, p2a, p2b, T=T)\n a = abs(angle_similarity(normalize(line(p1a, p1b)), normalize(line(p2a, p2b))))\n return d * a",
"def line_distance_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Closest distance between a line segment and a point | def distance_to_line(a, b, p):
return distance(closest_point(a, b, p), p) | [
"def _distance_to_line(begin, end, point):\n return _vec_distance(point, _nearest_point_on_line(begin, end, point))",
"def distance_to_line(self, point, line):\n px, py = point\n x1, y1, x2, y2 = line\n x_diff = x2 - x1\n y_diff = y2 - y1\n num = abs(y_diff * px - x_diff * py... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Line distance similarity between two line segments | def line_distance_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD):
d1 = distance_similarity(p1a, p1b, p2a, T=T)
d2 = distance_similarity(p1a, p1b, p2b, T=T)
return abs(d1 + d2) * 0.5 | [
"def line_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD):\n d = line_distance_similarity(p1a, p1b, p2a, p2b, T=T)\n a = abs(angle_similarity(normalize(line(p1a, p1b)), normalize(line(p2a, p2b))))\n return d * a",
"def _distance(point, line_point1, line_point2):\n vec1 = line_point1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Similarity between two lines | def line_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD):
d = line_distance_similarity(p1a, p1b, p2a, p2b, T=T)
a = abs(angle_similarity(normalize(line(p1a, p1b)), normalize(line(p2a, p2b))))
return d * a | [
"def line_distance_similarity(p1a, p1b, p2a, p2b, T=CLOSE_DISTANCE_THRESHOLD):\n d1 = distance_similarity(p1a, p1b, p2a, T=T)\n d2 = distance_similarity(p1a, p1b, p2b, T=T)\n return abs(d1 + d2) * 0.5",
"def wordSimilarityRatio(sent_1,sent_2):",
"def rate_lines(self, line1, line2):\n return diff... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yield info about the atoms in the batch. Yields | def get_atom_infos(self):
yield from self._atom_infos | [
"def get_atom_infos(self):\n\n yield from self._molecule_state.get_atom_infos()",
"def __iter__(self):\n\n if self.output_mode:\n process_atom = self._process_atom_output\n self.output_names = self.names[:]\n else:\n process_atom = self._process_atom\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test block get number of channels. | async def test_block_get_number_of_channels(mock_block_device, monkeypatch) -> None:
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "type", "emeter")
monkeypatch.setitem(mock_block_device.shelly, "num_emeters", 3)
assert (
get_number_of_channels(
mock_block_device,
... | [
"def nb_channels(self):",
"def get_num_channels():\r\n check_mixer()\r\n return sdl.Mix_GroupCount(-1)",
"def num_blocks(self): # -> int:\n ...",
"def test_channels(self):\n channels = int(self.webm_format.get_audio_stream_entry('channels'))\n self.assertEqual(channels, 2, 'Incorrec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test block get block channel name. | async def test_block_get_block_channel_name(mock_block_device, monkeypatch) -> None:
monkeypatch.setattr(mock_block_device.blocks[DEVICE_BLOCK_ID], "type", "relay")
assert (
get_block_channel_name(
mock_block_device,
mock_block_device.blocks[DEVICE_BLOCK_ID],
)
=... | [
"async def test_get_rpc_channel_name(mock_rpc_device) -> None:\n assert get_rpc_channel_name(mock_rpc_device, \"input:0\") == \"test switch_0\"\n assert get_rpc_channel_name(mock_rpc_device, \"input:3\") == \"Test name switch_3\"",
"def channel_name(self):\n\n return self.channel.name if self.channel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test get block device sleep period. | async def test_get_block_device_sleep_period(settings, sleep_period) -> None:
assert get_block_device_sleep_period(settings) == sleep_period | [
"def testSingleBedAlmostTwoSleeps(self):\n day = timedelta(days=1)\n three_minutes = timedelta(minutes=3)\n ten_minutes = timedelta(minutes=10)\n hour = timedelta(hours=1)\n two_hours = timedelta(hours=2)\n five_hours = timedelta(hours=5)\n\n sleep_duration = timedel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test block test get device uptime. | async def test_get_device_uptime() -> None:
assert get_device_uptime(
55, dt_util.as_utc(dt_util.parse_datetime("2019-01-10 18:42:00+00:00"))
) == dt_util.as_utc(dt_util.parse_datetime("2019-01-10 18:42:00+00:00"))
assert get_device_uptime(
50, dt_util.as_utc(dt_util.parse_datetime("2019-01... | [
"def uptime():\n run('uptime')",
"def uptime():\n run(\"uptime\")",
"async def fetch_device_uptime(client, request: dict) -> Response:\n filter_report = client.parse_filter(\"uptime color > 0\")\n request[\"filters\"].update(filter_report)\n request[\"reports\"] = \"/inventory/devices\"\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test get block input triggers. | async def test_get_block_input_triggers(mock_block_device, monkeypatch) -> None:
monkeypatch.setattr(
mock_block_device.blocks[DEVICE_BLOCK_ID],
"sensor_ids",
{"inputEvent": "S", "inputEventCnt": 0},
)
monkeypatch.setitem(
mock_block_device.settings, "rollers", [{"button_type... | [
"def fixture_input_block():\n return Mock()",
"def checkTriggers():\n # TODO this\n pass",
"async def test_get_rpc_input_triggers(mock_rpc_device, monkeypatch) -> None:\n monkeypatch.setattr(mock_rpc_device, \"config\", {\"input:0\": {\"type\": \"button\"}})\n assert set(get_rpc_input_triggers(mo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test get RPC channel name. | async def test_get_rpc_channel_name(mock_rpc_device) -> None:
assert get_rpc_channel_name(mock_rpc_device, "input:0") == "test switch_0"
assert get_rpc_channel_name(mock_rpc_device, "input:3") == "Test name switch_3" | [
"def test_unicode_channel_name(self):\n channel_layer.send(\"\\u00a3_test\", {\"value\": \"blue\"})\n # Get just one first\n channel, message = channel_layer.receive_many([\"\\u00a3_test\"])\n self.assertEqual(channel, \"\\u00a3_test\")\n self.assertEqual(messa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test get RPC input triggers. | async def test_get_rpc_input_triggers(mock_rpc_device, monkeypatch) -> None:
monkeypatch.setattr(mock_rpc_device, "config", {"input:0": {"type": "button"}})
assert set(get_rpc_input_triggers(mock_rpc_device)) == {
("btn_down", "button1"),
("btn_up", "button1"),
("single_push", "button1")... | [
"def test_get_webhook(self):\n pass",
"def test_get_data_from_user(msg, expected, mocker):\n input_mock = mocker.patch.object(builtins, 'input')\n get_data_from_user(msg)\n assert input_mock.call_count == expected",
"def test_get_run(self):\n pass",
"def test_get_interaction(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the dialogue_reference of the message. | def dialogue_reference(self) -> Tuple[str, str]:
enforce(self.is_set("dialogue_reference"), "dialogue_reference is not set.")
return cast(Tuple[str, str], self.get("dialogue_reference")) | [
"def dialogue_reference(self) -> Tuple[str, str]:\n return self._dialogue_reference",
"def dialogue_reference(self) -> Tuple[str, str]:\n assert self.is_set(\"dialogue_reference\"), \"dialogue_reference is not set.\"\n return cast(Tuple[str, str], self.get(\"dialogue_reference\"))",
"def di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the performative of the message. | def performative(self) -> Performative: # type: ignore # noqa: F821
enforce(self.is_set("performative"), "performative is not set.")
return cast(SigningMessage.Performative, self.get("performative")) | [
"def performative(self) -> Performative: # noqa: F821\n assert self.is_set(\"performative\"), \"performative is not set.\"\n return cast(DefaultMessage.Performative, self.get(\"performative\"))",
"def description(self):\r\n return getattr(split_docstring(self.message_view), 'summary', None)"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the 'raw_message' content from the message. | def raw_message(self) -> CustomRawMessage:
enforce(self.is_set("raw_message"), "'raw_message' content is not set.")
return cast(CustomRawMessage, self.get("raw_message")) | [
"def raw_message(self) -> RawMessage:\n return self.__raw_message",
"def get_message_content(message): # pylint: disable=too-many-return-statements\n if message.content_type == \"photo\":\n return message.photo[0].file_id\n if message.content_type == \"text\":\n return message.text\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the 'raw_transaction' content from the message. | def raw_transaction(self) -> CustomRawTransaction:
enforce(self.is_set("raw_transaction"), "'raw_transaction' content is not set.")
return cast(CustomRawTransaction, self.get("raw_transaction")) | [
"def raw_message(self) -> RawMessage:\n return self.__raw_message",
"def raw_message(self) -> CustomRawMessage:\n enforce(self.is_set(\"raw_message\"), \"'raw_message' content is not set.\")\n return cast(CustomRawMessage, self.get(\"raw_message\"))",
"def content(self):\n if hasattr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the 'signed_message' content from the message. | def signed_message(self) -> CustomSignedMessage:
enforce(self.is_set("signed_message"), "'signed_message' content is not set.")
return cast(CustomSignedMessage, self.get("signed_message")) | [
"def get_message_content(message): # pylint: disable=too-many-return-statements\n if message.content_type == \"photo\":\n return message.photo[0].file_id\n if message.content_type == \"text\":\n return message.text\n if message.content_type == \"audio\":\n return message.audio.file_id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the 'signed_transaction' content from the message. | def signed_transaction(self) -> CustomSignedTransaction:
enforce(
self.is_set("signed_transaction"),
"'signed_transaction' content is not set.",
)
return cast(CustomSignedTransaction, self.get("signed_transaction")) | [
"def signed_message(self) -> CustomSignedMessage:\n enforce(self.is_set(\"signed_message\"), \"'signed_message' content is not set.\")\n return cast(CustomSignedMessage, self.get(\"signed_message\"))",
"def test_signed_transaction(self):\n tx_msg = SigningMessage(\n performative=Si... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sets up config items for delta class, prepares input files, instantiates delta class and runs comparison removes temporary files | def delta_runner(nconfig,
dialect: csvhelper.Dialect) -> gdelta.FileDelta:
adj_temp_dir = nconfig.temp_dir or dirname(nconfig.infiles[1])
adj_out_dir = nconfig.out_dir or dirname(nconfig.infiles[1])
#--- handle all key, compare and ignore logic --------------
def convert_cols(col_titl... | [
"def __init__(self, input_yaml, posinp, prefix=None, run_folder=None,\n ref_calc=None):\n # Set the initial folder\n self.init_folder = os.getcwd()\n\n # Set the folder where the calculation will be run\n if run_folder is None:\n self.run_folder = \".\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return assignment config section after converting col names to offsets. | def get_assign_with_offsets_for_names(col_names: List[str],
assign_config: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
new_assign_config: List[Dict[str, Any]] = copy.deepcopy(assign_config)
for asgn in new_assign_config:
if asgn.get("src_field", None) is not None... | [
"def slice_config(self) -> SliceConfig:\n if self._slice is None:\n return None\n return self._slice.slice_config",
"def get_coil_config_section(cls) -> Optional[str]:\n return None",
"def get_delim_config(cell, delim):\n assert is_raw_cell(cell), \"cannot get delim config fro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines the user config or metadata. Does not get the user input. | def define_user_config(self) -> None:
self.add_standard_metadata('infiles')
self.add_custom_metadata(name='key_cols',
short_name='k',
required=True,
default=[],
nargs='*',... | [
"def define_user_config(self) -> None:\n\n self.add_standard_metadata(\"infiles\")\n self.add_standard_metadata(\"outfile\")\n\n self.add_custom_metadata(name=\"output_format\",\n default=\"readable\",\n type=str)\n self.add... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds file into the exisiting compiled freq dist should input an existing freq dist file | def update_freq_dist(filename):
pass | [
"def addFile(self, fi):",
"def build_frequency_file(dtatcfdir, freq_file, MIN_FREQ, join_sign):\n \n # build frequency file from lemmas\n outputpath = freq_file\n print 'Building frequency file to ' + outputpath + \"...\"\n lemma_count = Counter(build_lemma_list(dtatcfdir, join_sign))\n frequent... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function opens the target word and checks if the word to be added is already in there. If it isn't, the word will get added in | def chk_append_in_out(target_word, word_to_add, data):
# insert syntax to write to temp file
import shutil
filename = filepath1(data)
dict_tmpfile = filepath1(data + ' tmp')
with open(filename, 'r',
encoding='utf8') as dict_file:
dict_reader = csv.reader(dict_file, d... | [
"def add_word(self):\n word = self.word # easier to call word now\n\n wordlist_path = self.get_wordlist_path()\n with open(wordlist_path) as f:\n data = json.load(f)\n\n if exists_already(data,word):\n exit()\n\n next_index = int(data[\"cur_index\"]) + 1 ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method used here is to write a file for all the targets The file will contain all the Predecessors and Successors, including repeats (chk_append_in_out1) The next step is to open evey word file, enter the entire file into working memory do a set, and then write the file. Prefer to do the read/write with temp to prevent... | def update_in_out1(filename):
import shutil
with open(filepath(filename, 'Edges'), 'r',
encoding='utf8') as edge_file:
edge_reader = csv.reader(edge_file, delimiter='\t',
quoting=csv.QUOTE_MINIMAL)
# edges = [l for l in edge_reader] # Lis... | [
"def collate(self):\n files_seen = set()\n dont_write = self._targets_not_to_write()\n for c in self._collections:\n for target, results in c.results.iteritems():\n if (c, target) in dont_write:\n # Skip targets where not all of the rules succeeded.\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use this to quickly plot the hubness of a text, after running hubness | def plothub(filename):
with open(filepath(filename, 'Hubness'),
'r', encoding='utf8') as hubness_file:
hub_reader = csv.reader(hubness_file, delimiter='\t',
quoting=csv.QUOTE_MINIMAL)
data = []
frequency = []
out_hubness = []
... | [
"def visualize():",
"def plot_BSNR_text(data_obj, test_num, yi, xpos, ha, va, fs, dfs):\n\n plt.text(xpos[0], yi, 'Test ' + str(test_num) + ': Organic Material Detection', ha=ha, va=va, fontsize=fs)\n str1 = \"{0:.1f}\".format(data_obj.POM_BSNR) + '$^\\clubsuit$'\n plt.text(xpos[1], yi, str1, ha=ha, va=v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a random square matrix of dimension mn, but rank k Replace last nk columns with linear combinations of the first k | def _randomnk(m, n, k):
a = np.random.random((m, n))
for i in range(k, n):
pars = np.random.random(k)
a[:, i] = a[:, :k] @ pars
return a | [
"def random_matrix(n):\n return [[random() for j in range(n)] for i in range(n)]",
"def generate_random_matrix(n):\n return [[random.randint(1, 50) for i in range(n)] for j in range(n)]",
"def gen_mat(n, dense):\n z = np.zeros((n,n))\n for row in range(n):\n r = []\n total = 0\n for col in rang... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
! When click Column button in 新规页面, return all table or return history data and policy tree data according to the table id return all data or history data and policy tree data | def get(self):
try:
if self.table_id is not '':
tvs = TableViewsSet(request=self.request)
data_history = tvs.get_info_by_table_id(self.table_id, history_need_flag=False)
# get tree information
pt = Policy_tree(self.policy_id)
... | [
"def update_menu_action(self):\n self.update_table(self.db.get_table(self.curr_table)\n ,self.db.get_headers(self.curr_table))",
"def fetch_data(self):\n self.app.cursor.execute('''\n SELECT '' as referenceCode, legacyId, parentId,\n cls_codigo as identifier, cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load significant region from WM、GM、WMGM with p < 0.05 | def load_significant_region_data(flag=4, mask_prop=0.1):
mdd_subjects = 129
hc_subjects = 89
subj_num = mdd_subjects + hc_subjects
if 1 == flag:
features = sio.loadmat("./data/WM_SIG_DATA.mat")["wm_sig_data"]
elif 2 == flag:
features = sio.loadmat("./data/GM_SIG_DATA.mat")["gm_sig_da... | [
"def map_all_sig_p(limitregion=False, region=\"allsky\"):\n \n # Get ids of all pixels that contain RHT data\n rht_cursor, tablename = get_rht_cursor(region = region)\n all_ids = get_all_rht_ids(rht_cursor, tablename)\n \n planck_tqu_db = sqlite3.connect(\"planck_TQU_gal_2048_db.sqlite\")\n pla... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates CIDR block from reverse zone name. | def ReverseZoneToCIDRBlock(self):
if( self.origin.endswith('in-addr.arpa.') ):
ip_parts = self.origin.split('.in-')[0].split('.')
ip_parts.reverse()
for ip_part in ip_parts:
if( not ip_part.isdigit() ):
raise Error('%s is not a reverse zone.' % self.zone_name)
cidr_block =... | [
"def get_subnet_cidr_block():\n current = 0\n high = 255\n while current <= high:\n yield '10.0.%s.0/24' % current\n current += 1",
"def allocate_child_subnet(self, view, parent, child_name, prefix_len):\n # cidr_s = (\"func:nextavailablenetwork:%s,%s,%d\" %\n # (par... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes records in the database from dns.zone class. | def MakeRecordsFromZone(self):
return self.core_helper_instance.AddFormattedRecords(
self.zone_name, self.zone_file_string, self.view) | [
"def update_dns(self):\n if self.ptr:\n which_zone = None\n zones = dns.models.Zone.objects.all()\n for zone in zones:\n if self.ptr.endswith(zone.name) or self.ptr.endswith(zone.name + '.'):\n which_zone = zone\n break\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the cache file | def clear_cache():
os.remove(CACHE_FILE) | [
"def remove(self):\n os.remove(self.__cache_file)",
"def remove_from_cache(self, url):\n os.remove(self.get_cached_filename(url))\n logger.warning('File %s has been removed from cache' % self.get_cached_filename(url))",
"def delete_cached_file(filename):\n global _FILE_CACHE\n\n if fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(string) > (List of 3 Strings) Takes a word and returns 3 rhyming words in a list. Can edit para_dict["max"] = "3" to another number to produce more results > get_rhymes("funny") > ['money', 'honey', 'sunny'] | def get_rhymes(word):
baseurl = "https://api.datamuse.com/words"
para_dict = {}
para_dict['rel_rhy'] = word
para_dict["max"] = '3'#Get a max of 3 results, change for more
resp = requests.get(baseurl, params=para_dict)
word_ds = resp.json()
return [d['word']for d in word_ds]
return resp.j... | [
"def query_rhyme_words(sentence: str, n_rhymes: int, language:str=\"english\") -> List[str]:\n last_word = find_last_word(sentence)\n if language == \"english\":\n return query_datamuse_api(last_word, n_rhymes)\n elif language == \"dutch\":\n return mick_rijmwoordenboek(last_word, n_rhymes)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts span indicies into spacy entity labels. | def spans_to_ents(doc, spans, label):
started = False
left, right, ents = 0, 0, []
for x in doc:
if x.pos_ == 'SPACE':
continue
if spans.intersection(set(range(x.idx, x.idx + len(x.text)))):
if not started:
left, started = x.idx, True
right = x.idx + len(x.text)
elif started:... | [
"def annotate_span(self, labels):\n \t\tfor key in labels:\n \t\t\tspan = \"-[%s-%s]\" % (key[0], key[1])\n \t\t\tnew_label = labels[key] + span\n \t\t\tlabels[key] = new_label\n \t\treturn labels",
"def to_spans(l_ids, voc):\n spans = {}\n current_lbl = None\n current_start = None\n for i, l_id in en... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads csv file with python span list and text. | def read_datafile(filename):
data = []
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
count = 0
for row in reader:
fixed = fix_spans.fix_spans(
ast.literal_eval(row['spans']), row['text'])
data.append((fixed, row['text']))
return data | [
"def loadCSV(input_file):",
"def read_csv_file(self):\n pass",
"def test_read_data_from_csv(self):\n self.assertEqual(CsvOperations.read_data(self.file_name)[0], [\"1\", \"Gold\", \"10\"])\n self.assertEqual(CsvOperations.read_data(self.file_name)[1], [\"2\", \"Platinum\", \"5\"])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds "|Music on voice!" to the nickname | async def on(self, ctx, *, nickname=""):
nickname = nickname.strip()
mention_here = True
mention_everyone = True
if nickname == "":
nickname = "Dank Bot |Music on voice!"
try:
await self.bot.change_nickname(ctx.message.server.me, nickname)
awai... | [
"def voice(self,nick):\n self.logger.debug(\"voicing %s\" % nick)\n self.connection.mode(self.config[\"IRC/channel\"],\"+v \"+nick)",
"def add_nickname(self, nickname):\n if 'Nicknames' not in self.properties:\n self.properties['Nicknames'] = []\n if (len(self.properties['Ni... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes "|Music on voice!" from the nickname | async def off(self, ctx, *, nickname=""):
nickname = nickname.strip()
if nickname == "":
nickname = None
try:
await self.bot.change_nickname(ctx.message.server.me, nickname)
await self.bot.delete_message(ctx.message)
await self.bot.say("RIP music l... | [
"async def on(self, ctx, *, nickname=\"\"):\n nickname = nickname.strip()\n mention_here = True\n mention_everyone = True\n if nickname == \"\":\n nickname = \"Dank Bot |Music on voice!\"\n try:\n await self.bot.change_nickname(ctx.message.server.me, nickname... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lambda function which is supposed to turn on EC2 and RDS instances during working hours and stop them during nonworking hours. | def lambda_handler(event, context):
ec2 = boto3.resource('ec2')
filters = [
{
'Name': 'tag:time',
'Values': ['*']
}
]
print('**************** CHECKING EC2 INSTANCES ****************')
for instance in ec2.instances.filter(Filters=filters):
print('====... | [
"def lambda_handler(event, context):\n Stop_Instances()",
"def stop(self, aws_tags: List[Dict]) -> None:\n for instance_arn in self.tag_api.get_resources(\"ec2:instance\", aws_tags):\n instance_id = instance_arn.split(\"/\")[-1]\n try:\n if not self.asg.describe_auto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates drift between baseline and sample datasets according to a predefined metric (jensenshannon distance or KS) or a userdefined metric. | def calculate_drift(
self,
pre_defined_metric=None,
user_defined_metric=None
):
if pre_defined_metric and user_defined_metric:
print("One of pre_defined_metric or user_defined_metric must be None.")
elif pre_defined_metric:
# Remove capitalizati... | [
"def calculate_concept_drift(\n self, \n pre_defined_metric=None,\n user_defined_metric=None):\n\n if (pre_defined_metric is not None) and (user_defined_metric is not None):\n raise ValueError(\n 'One of pre_defined_metric or user_defined_metric must be None.'\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates concept drift between target columns of baseline and sample datasets according to a predefined metric (jensenshannon distance or KS) or a userdefined metric. | def calculate_concept_drift(
self,
pre_defined_metric=None,
user_defined_metric=None):
if (pre_defined_metric is not None) and (user_defined_metric is not None):
raise ValueError(
'One of pre_defined_metric or user_defined_metric must be None.'
)... | [
"def calculate_drift(\n self, \n pre_defined_metric=None,\n user_defined_metric=None\n ):\n\n if pre_defined_metric and user_defined_metric:\n print(\"One of pre_defined_metric or user_defined_metric must be None.\")\n\n elif pre_defined_metric:\n # Re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A method to compare model performance on baseline and sample datasets. Will call _eval_classifier or _eval_regressor depending on label_type. | def compare_performance(self):
if self.label_type == "categorical":
self._eval_classifier()
elif self.label_type == "numerical":
self._eval_regressor()
return self.performance_comparison | [
"def _eval_classifier(self):\n\n y_pred_baseline = self.df_baseline[self.score_column]\n y_pred_sample = self.df_sample[self.score_column]\n\n y_label_baseline = self.df_baseline[self.label_column]\n y_label_sample = self.df_sample[self.label_column]\n\n precision_baseline = preci... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function to compute accuracy, precision, recall, F1 score, and AUC on baseline and sample datasets. | def _eval_classifier(self):
y_pred_baseline = self.df_baseline[self.score_column]
y_pred_sample = self.df_sample[self.score_column]
y_label_baseline = self.df_baseline[self.label_column]
y_label_sample = self.df_sample[self.label_column]
precision_baseline = precision_score(y_... | [
"def accuracy_metrics(raw):\n \n raw['Recall'] = raw['True Positives'] / (raw['True Positives'] + raw['False Negatives'])\n raw['Precision'] = raw['True Positives'] / (raw['True Positives'] + raw['False Positives'])\n raw['F1'] = 2 * (raw['Precision'] * raw['Recall']) / (raw['Precision'] + raw['Recall']... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function to compute the jensenshannon distances between columns of similar DataFrames. For categorical columns, the probability of each category will be computed separately for `df_baseline` and `df_sample`, and the Jensen Shannon distance between the 2 probability arrays will be computed. For numerical columns, the ... | def js_metric(df_1, df_2, numerical_columns, categorical_columns):
res = {}
STEPS = 100
for col in categorical_columns:
# to ensure similar order, concat before computing probability
col_baseline = df_1[col].to_frame()
col_sample = df_2[col].to_frame()
col_baseline["source"... | [
"def compute_js_divergence(df_1, df_2, n_bins=30):\n a = np.concatenate((df_1, df_2), axis=0)\n e, p = prob_mass_fun(df_1, n = n_bins, range = (a.min(), a.max()))\n _, q = prob_mass_fun(df_2, n = e, range = (a.min(), a.max()))\n\n return scipy.spatial.distance.jensenshannon(p, q)",
"def compute_distan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
caculate the weight of every letter and store it in dict. the weight will be higher of the letter in the front of the str. | def calc_weight(str,dict):
for i,c in enumerate(str):
dict[c] += 10**(len(str)-(i+1)) | [
"def letter_freq( text ):\n\tchars = string.ascii_uppercase\n\ttext = text.upper()\n\tresult = get_letter_dict()\n\ttotal = 0\n\tfor char in chars:\n\t\tcount = text.count(char)\n\t\tresult[char] = count\n\t\ttotal += count\n\tif total != 0:\n\t\tfor char in chars:\n\t\t\tresult[char] = (result[char]*10000 / total)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct a mock feed entry for testing purposes. | def _generate_mock_feed_entry(
external_id,
title,
distance_to_home,
coordinates,
category=None,
attribution=None,
published=None,
updated=None,
status=None,
):
feed_entry = MagicMock()
feed_entry.external_id = external_id
feed_entry.title = title
feed_entry.distance_... | [
"def _generate_mock_feed_entry(\n external_id, title, distance_to_home, coordinates, category\n ):\n feed_entry = MagicMock()\n feed_entry.external_id = external_id\n feed_entry.title = title\n feed_entry.distance_to_home = distance_to_home\n feed_entry.coordinates = coo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the setup with a custom location. | async def test_setup_with_custom_location(hass: HomeAssistant) -> None:
# Set up some mock feed entries for this test.
mock_entry_1 = _generate_mock_feed_entry(
"1234", "Title 1", 20.5, (38.1, -3.1), category="Category 1"
)
with patch("georss_qld_bushfire_alert_client.QldBushfireAlertFeed") as ... | [
"def location_fixture():\n return _create_location()",
"def test_get_zr_location_settings(self):\n pass",
"def test_homepage_with_location(self):\r\n\r\n with self.client:\r\n response = self.client.get('/?location=US-CA')\r\n self.assertEqual(response.status_code, 200)\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the web service up. Prepare to start the server, load base templates. | async def setup(self):
load_base_templates()
uris = URI.gather()
for uri, resource in uris.items():
methods = resource.methods
if "get" not in methods:
methods["get"] = None
for method in methods.keys():
self.app.add_routes([
... | [
"def setup_server():\n cherrypy.config.update('server.conf')\n cherrypy.tree.mount(StringGeneratorWebService(), '/', 'server.conf')",
"def _start(self):\n\n ip = mh.cfg['Extensions']['TestEnv']['server_ip']\n port = mh.cfg['Extensions']['TestEnv']['server_port']\n self._server =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the posterior from prior, data, and beta | def computePosterior(self):
# in their log form, posterior = prior + beta * datalikelihood
# make a copy of prior at first
self.posterior.copy(self.prior)
# add the data likelihood
altar.blas.daxpy(self.beta, self.data, self.posterior)
# all done
return self | [
"def calc_posterior():\n\n a = [alpha, 1-alpha]\n ms = [x_obs, x_obs]\n Ss = map(lambda s: [[s**2]], sigmas)\n\n return pdf.MoG(a=a, ms=ms, Ss=Ss)",
"def update_params(x, prior, posterior):\r\n mu0, kappa0, alpha0, beta0 = prior\r\n mu_t, kappa_t, alpha_t, beta_t = posterior\r\n return np.r_[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Conversion from Topocentric Frame to parent frame | def _to_parent_frame(self, *args, **kwargs):
lat, lon, _ = self.latlonalt
m = rot3(-lon) @ rot2(lat - np.pi / 2.0) @ rot3(self.heading)
offset = np.zeros(6)
offset[:3] = self.coordinates
return self._convert(m, m), offset | [
"def _switch_to_parent_frame(self):\n pass",
"def make_pg_frame(frame):\n return np.transpose(frame, axes=(1, 0, 2))",
"def inner(self):\r\n return Frame(self)",
"def get_pose_in_frame(self, parent_frame, child_frame):\n transform = self.lookup_transform(parent_frame, child_frame)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Column that adds primary key foreign key reference. | def ReferenceCol(tablename, nullable=False, pk_name='id', **kwargs):
return db.Column(
db.ForeignKey("{0}.{1}".format(tablename, pk_name)),
nullable=nullable, **kwargs) | [
"def reference_col(tablename, nullable=False, pk_name='id', **kwargs):\n return db.Column(\n db.ForeignKey('{0}.{1}'.format(tablename, pk_name)),\n nullable=nullable, **kwargs)",
"def reference_col(tablename, nullable=True, pk_name='id', **kwargs):\n return db.Column(\n db.Forei... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plots Correlation matrix using Seaborn's heatmap() | def plot_correlation_mat(corr_matrix):
fig, ax = plt.subplots(figsize=(15, 10))
ax = sns.heatmap(corr_matrix, annot=True, linewidths=0.5, fmt=".2f", cmap="YlGnBu")
return fig, ax | [
"def correlation_matrix(df):\n columns = df.columns\n index = df.index\n data = preprocessing.StandardScaler().fit_transform(df)\n df = pd.DataFrame(data, columns=columns)\n df.index = index\n\n print(df.corr())\n\n plt.figure(figsize=(25, 25))\n dataplot = sb.heatmap(df.corr(), cmap=\"YlGnB... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes an NumPy objects and calculate mean rounded up to 2 decimal places. Uses NumPy. | def mean_and_round(np_arr):
return np.around(np.mean(np_arr), 2) | [
"def numpy_mean(arr):\r\n return arr.mean()",
"def numpy_mean(arr):\n return arr.mean()",
"def mean_average_precision(rs):\n return np.mean([average_precision(r) for r in rs])",
"def arithmetic_mean(numbers):\r\n return numpy.mean(numbers)",
"def mean(x):\n return np.sum(x) / x.size",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Restores the value range of `x` from `scaled_quantization`. | def inverse_scaled_quantization(x, scale):
return x / tf.cast(scale, x.dtype) | [
"def reset_scale(self) -> None:\n self._scale.set(self._start_val)",
"def setScaleX(self,startx,endx):\r\n if startx == endx:\r\n endx += 1\r\n self.scaleLock.acquire()\r\n self.scalex = [startx,endx]\r\n self.scaleLock.release()",
"def _unscale(self, x_scaled,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Flattens each tensor in the structure and concats them as a vector. Each tensor within the structure should have rank >= 1 (i.e. no scalars). | def flatten_concat(structure):
flattened_as_list = []
for x in tf.nest.flatten(structure):
with tf.control_dependencies([tf.debugging.assert_rank_at_least(x, 1)]):
flattened_as_list.append(tf.reshape(x, [-1]))
return tf.concat(flattened_as_list, axis=0) | [
"def inverse_flatten_concat(flat_vector, original_structure):\n location, split_tensors = 0, []\n for orig_t in tf.nest.flatten(original_structure):\n length = tf.size(orig_t)\n split_vector = tf.slice(flat_vector, [location], [length])\n split_tensors.append(tf.reshape(split_vector, orig_t.shape))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies the inverse of `flatten_concat` given the original structure. | def inverse_flatten_concat(flat_vector, original_structure):
location, split_tensors = 0, []
for orig_t in tf.nest.flatten(original_structure):
length = tf.size(orig_t)
split_vector = tf.slice(flat_vector, [location], [length])
split_tensors.append(tf.reshape(split_vector, orig_t.shape))
location +=... | [
"def unflatten(self, x):",
"def unflatten_n(self, xs):",
"def unflatten_tree(tree, xs):\n tree = _replace_nones(tree)\n\n return jax.tree_util.tree_unflatten(jax.tree_util.tree_structure(tree), xs)",
"def test_flatten_unflatten(self):\n op1 = qml.PauliX(0)\n op2 = qml.Hermitian(np.eye(2), wire... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sample uniform random +1/1 values with specified shape/dtype/seed_pair. | def sample_rademacher(shape, dtype, seed_pair):
rand_uniform = tf.random.stateless_uniform(shape=shape, seed=seed_pair)
return tf.cast(tf.sign(rand_uniform - 0.5), dtype) | [
"def uniform(shape, dtype='float32'):\n return np.random.uniform(-1., 1., size=shape).astype(dtype)",
"def random_grid_generator(self, *input_shape):\n rnd = np.random.RandomState(1)\n rnd.rand(input_shape)",
"def sample_uniform(instance, params):\n subpop = np.random.randint(params['N'])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies randomized Hadamard transform to a vector with the given seed. | def randomized_hadamard_transform(x, seed_pair, repeat=1):
def apply_transform(repeat_index, x):
# All sources of randomness depend on the input seed.
cur_seed = seed_pair + repeat_index
# Randomly flip signs.
signs = sample_rademacher(tf.shape(x), dtype=x.dtype, seed_pair=cur_seed)
rademacher_x ... | [
"def Randomize(self, seed):\n return _hypre.HypreParVector_Randomize(self, seed)",
"def Randomize(self, seed=0):\n return _vector.Vector_Randomize(self, seed)",
"def random_seed(seed):\n state = RandomState()\n random.seed(seed) # alter state\n np.random.seed(seed)\n torch.manual_seed... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies inverse of `randomized_hadamard_transform` with the given seed. | def inverse_randomized_hadamard_transform(x, original_dim, seed_pair, repeat=1):
def inverse_transform(repeat_index, x):
# All sources of randomness depend on the input seed.
cur_seed = seed_pair + repeat_index
# Apply Hadamard.
unrotated_x = fast_walsh_hadamard_transform(tf.expand_dims(x, axis=0))
... | [
"def Randomize(self, seed):\n return _hypre.HypreParVector_Randomize(self, seed)",
"def randomized_hadamard_transform(x, seed_pair, repeat=1):\n\n def apply_transform(repeat_index, x):\n # All sources of randomness depend on the input seed.\n cur_seed = seed_pair + repeat_index\n # Randomly flip ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies the fast WalshHadamard transform to a set of vectors. This method uses a composition of existing TensorFlow operations to implement the transform. | def fast_walsh_hadamard_transform(x):
with tf.compat.v1.name_scope(None, 'fast_walsh_hadamard_transform'):
# Validate input.
x = tf.convert_to_tensor(x)
if x.shape.ndims != 2:
raise ValueError('Number of dimensions of x must be 2. Shape of x: %s' %
x.shape)
original_x_sha... | [
"def _apply_transforms(inputs, q_vectors):\n squared_norms = torch.sum(q_vectors ** 2, dim=-1)\n outputs = inputs\n for q_vector, squared_norm in zip(q_vectors, squared_norms):\n temp = outputs @ q_vector # Inner product.\n temp = torch.ger(temp, (2.0 / squared_norm) * q_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search for a language change event This event have to call retranslateUi to change interface language on the fly. | def changeEvent(self, event):
if event.type() == QEvent.LanguageChange:
self.retranslateUi(self)
self.translation()
else:
QWidget.changeEvent(self, event) | [
"def onLanguageChanged(self, argsList):\r\n\t\tiLanguage = argsList[0]",
"def test_change_language(self):\n # Step Open security server for login add user name password\n self.component_ss.login(u'ss1_url')\n\n # Step Change language\n self.component_common.open_select_language_dlg()\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Position galaxies in haloes and give them random velocities. Centrals are positioned at the centre of the halo, satellites are positioned randomly following a NFW profile. Adds position, velocity and cosmological redshift to the catalogue. | def position_galaxies(self):
# random distance to halo centre
distance = self._get_distances()
# position around halo centre
pos = self._get_positions(distance)
# random velocity vector
vel = self._get_velocities()
# add properties to catalogue
self.add... | [
"def populate(centres, masses, halomodel=None, profile=None, hodmod=None, edges=None):\r\n if halomodel is not None:\r\n profile = halomodel.halo_profile\r\n hodmod = halomodel.hod\r\n\r\n masses = np.array(masses)\r\n\r\n # Define which halos have central galaxies.\r\n cgal = np.random.bi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add colours to the galaxy catalogue. | def add_colours(self, colour):
col = np.zeros(self.size)
is_cen = self.get("is_cen")
is_sat = self.get("is_sat")
abs_mag = self.get("abs_mag")
z = self.get("zcos")
col[is_cen] = colour.get_central_colour(abs_mag[is_cen], z[is_cen])
col[is_sat] = colour.g... | [
"def add_color(self, color, id):",
"def updateColors(self):\n if self.type == 'spatial':\n for probeName, scatter in self.scatters.iteritems():\n color = next((p.color for p in self.probes if p.name == probeName), None)\n mpl.artist.setp(scatter,color=color)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add apparent magnitude to catalogue, using a colourdependent kcorrection | def add_apparent_magnitude(self, k_correction):
app_mag = k_correction.apparent_magnitude(self.get("abs_mag"),
self.get("zcos"), self.get("col"))
self.add("app_mag", app_mag) | [
"def apply_absorption_correction(qz, scale):\n global t\n global mu\n global wavelength\n for i in xrange(len(scale)):\n #a = wavelength * qz[i] / 4 / math.pi\n a = 1.18 * qz[i] / 4 / math.pi\n theta = math.asin(a)\n g = 2 / math.sin(theta)\n Ac = t * g / mu / (1-math.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if the group is considered 'active' i.e. downloading, postprocessing, running a script, etc, but NOT 'PAUSED'. | def nzbget_group_is_active(group):
return group['Status'] != 'PAUSED' | [
"def is_active(self):\n return not self.pending",
"def is_active(self):\n result = self.state in {EventTypes.RUNTIME_STATE.value, EventTypes.DATACOLLECT_STATE.value}\n logging.info(\"session(%s) checking if active: %s\", self.id, result)\n return result",
"def is_ever_active(self):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the total size (in MB) of the groups that are considered active. | def nzbget_groups_total_active_size_mb(groups, ignore_group_id=None):
total_size_mb = 0
for group in groups:
group_id = group['NZBID']
if group_id != ignore_group_id and nzbget_group_is_active(group):
total_size_mb += group['FileSizeMB']
return total_size_mb | [
"def group_size(self):\n return self._gsize",
"def queue_size(self):\n return len(self.groups)",
"def get_size(group, include_failed=False):\n return GroupInspector.from_parent_resource(group).size(include_failed)",
"def group_size(self) -> int:\n return self._pb_replica_grouping.getGr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generator func that yields nzbs (groups) from the list of groups in the order of priority. | def nzbget_groups_iter_nzbs_by_priority(groups):
yielded_groups = 0
# the current priority being yielded
# On each iteration, this will be set to the next lowest priority until all
# groups are exhausted
current_priority = 999999
while len(groups) != yielded_groups:
# discover current ... | [
"def itergroups(groups, num=3):\n sortedgroups = sorted(groups, key=santamin)\n\n for c in sortedgroups:\n if num == 1:\n yield (c,)\n else:\n others = (\n t for t in sortedgroups\n if not set.intersection(t, c)\n )\n for ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assess BUSCO completeness on the most prevalent members of the metatranscriptome at each taxonomic level. | def manageBuscoQuery(output_dir, individual_or_summary, samples,
mets_or_mags, pep_ext, nt_ext,
sample_dir, organisms, organisms_taxonomy,
tax_tab, busco_threshold, perc_mem):
max_jobs = calc_max_jobs(len(samples), perc_mem = perc_mem)
samples_compl... | [
"def verify_obc(self):\n self.ceph_cluster.wait_for_noobaa_health_ok()",
"def test_topo_current_occupants_positive():\n instance = topo.Topography()\n assert instance.current_occupants()[\"Herbivores\"] >= 0\\\n and instance.current_occupants()[\"Carnivores\"] >= 0",
"def test_get_utilizatio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the exploration rate and target network if needed. This method is called in ``collect_rollouts()`` after each step in the environment. | def _on_step(self) -> None:
self._n_calls += 1
# Account for multiple environments
# each call to step() corresponds to n_envs transitions
if self._n_calls % max(self.target_update_interval // self.n_envs, 1) == 0:
polyak_update(self.q_net.parameters(), self.q_net_target.para... | [
"def update_target_net(self, sess):\n sess.run(self.update_target_net_op)",
"def update_target_network(self):\n\n\t\tprint \"Updating Target DQN...\"\n\t\t\n\t\tself.update_operation.run()",
"def update(self):\n self.updateNeuronCounters()\n self.updateAstrocyteActivations()\n self.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simple helper function that groups a list into pairs. For example, [1,2,3,4,5] would return [1,2],[3,4] | def pairs(lst):
for i in range(1, len(lst), 2):
yield lst[i-1], lst[i] | [
"def split_list_in_pairs (a_list):\n if len(a_list) == 1 or not a_list:\n final_list = [a_list]\n else:\n final_list = [a_list[i:i + 2] for i in range(0, len(a_list), 2)]\n return final_list",
"def list_to_pairs(l):\n return {(l[2*i], l[2*i+1]) for i in range(len(l)/2)}",
"def pairings... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This looks at what games everyone has won and sets their currentRank field. The current algorithm is very simple just award ranks based on number of games won. You should replace this with your own ranking logic. | def setRanks_ByNumWinsOnly(tourney_id):
logging.info('in setRanks()')
#Load all finished games
finishedGames = games.Game.all().filter("winner !=", None).filter("tourney_id =", tourney_id)#.run(batch_size=1000)
#logging.info("finishedGames:")
#logging.info(finishedGames)
players_id_name_dict = getPlayersIDNam... | [
"def assignRanks(self):\r\n\t\trank = 0\r\n\t\tscores = list(self._playerScores)\r\n\t\tscores.reverse()\r\n\t\tfor playerScore in scores:\r\n\t\t\tif not playerScore.has(NOT_MET) or not playerScore.value(NOT_MET):\r\n\t\t\t\trank += 1\r\n\t\t\t\tplayerScore.set(RANK, smallText(BugUtil.colorText(u\"%d\" % rank, Sco... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Basic test of parse_seat() take 1 | def test_parse_basic_seat1():
assert parse_seat("BFFFBBFRRR") == {"row": 70, "column": 7, "seat_id": 567} | [
"def test_parse_basic_seat2():\n assert parse_seat(\"FFFBBBFRRR\") == {\"row\": 14, \"column\": 7, \"seat_id\": 119}",
"def test_parse_basic_seat3():\n assert parse_seat(\"BBFFBBFRLL\") == {\"row\": 102, \"column\": 4, \"seat_id\": 820}",
"def _parse_seat(self, seat_number):\r\n seat_row, seat_lett... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Basic test of parse_seat() take 2 | def test_parse_basic_seat2():
assert parse_seat("FFFBBBFRRR") == {"row": 14, "column": 7, "seat_id": 119} | [
"def test_parse_basic_seat3():\n assert parse_seat(\"BBFFBBFRLL\") == {\"row\": 102, \"column\": 4, \"seat_id\": 820}",
"def test_parse_basic_seat1():\n assert parse_seat(\"BFFFBBFRRR\") == {\"row\": 70, \"column\": 7, \"seat_id\": 567}",
"def _parse_seat(self, seat_number):\r\n seat_row, seat_lett... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Basic test of parse_seat() take 3 | def test_parse_basic_seat3():
assert parse_seat("BBFFBBFRLL") == {"row": 102, "column": 4, "seat_id": 820} | [
"def test_parse_basic_seat2():\n assert parse_seat(\"FFFBBBFRRR\") == {\"row\": 14, \"column\": 7, \"seat_id\": 119}",
"def test_parse_basic_seat1():\n assert parse_seat(\"BFFFBBFRRR\") == {\"row\": 70, \"column\": 7, \"seat_id\": 567}",
"def _parse_seat(self, seat):\n row_numbers, seat_letters = s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Basic test of find_max_seat_id() | def test_find_max_seat_id():
data = [
{"seat_id": 100},
{"seat_id": 101},
{"seat_id": 99},
]
assert find_max_seat_id(data) == 101 | [
"def highest_seat_id(raw_seat_string):\n\n seat_list = raw_seat_string.split('\\n')\n\n return max(list(map(find_seat, seat_list)))",
"def get_highest_seat_id(seat_ids):\n\n return max(seat_ids)",
"def highest_seat_id(seat_list):\n highest_id = 0\n for seat_id in seat_list:\n if highest_id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test of find_missing_seat_id() where there's a result | def test_find_missing_seat_id_pass():
data = [
{"seat_id": 80},
{"seat_id": 81},
{"seat_id": 82},
{"seat_id": 84},
{"seat_id": 85},
{"seat_id": 86},
]
assert find_missing_seat_id(data) == 83 | [
"def test_find_missing_seat_id_fail():\n data = [\n {\"seat_id\": 80},\n {\"seat_id\": 81},\n {\"seat_id\": 82},\n {\"seat_id\": 85},\n {\"seat_id\": 86},\n ]\n assert not find_missing_seat_id(data)",
"def find_missing_id(seat_list):\n highest_id = highest_seat_id(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test of find_missing_seat_id() where there's not result | def test_find_missing_seat_id_fail():
data = [
{"seat_id": 80},
{"seat_id": 81},
{"seat_id": 82},
{"seat_id": 85},
{"seat_id": 86},
]
assert not find_missing_seat_id(data) | [
"def test_find_missing_seat_id_pass():\n data = [\n {\"seat_id\": 80},\n {\"seat_id\": 81},\n {\"seat_id\": 82},\n {\"seat_id\": 84},\n {\"seat_id\": 85},\n {\"seat_id\": 86},\n ]\n assert find_missing_seat_id(data) == 83",
"def find_missing_id(seat_list):\n h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split data intro training and validation sets. | def split_data_into_training_and_validation(self, data):
training_dataset = self.get_data_from_indices(data, np.arange(self.num_training_samples))
validation_dataset = self.get_data_from_indices(data, np.arange(self.num_training_samples,
... | [
"def __split_dataset(self):\n self.train, self.valid, _, _ = train_test_split(self.data, self.data, test_size=0.2)\n self.valid, self.test, _, _ = train_test_split(self.valid, self.valid, test_size=0.5)",
"def split(data, labels, train_per=0.8, dev_per=0.0, test_per=0.2):\n # Ensure proper percen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a training batch from the dataset. | def generate_training_batch(self, start_index):
assert self.training_dataset is not None
assert self.data_tags is not None
return self.get_data_from_indices(self.training_dataset,
np.arange(start_index, start_index + self.p.trainer.batch_size)) | [
"def _train_batch(self):\n\n # start epoch\n for i, (source, target) in enumerate(self.train_dataset):\n result = self._batch_iter(source, target, i)\n\n # yield\n yield result",
"def train(self, num_batches: int):",
"def trainGenerator(self,):\n return tf.d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a validation batch from the dataset. | def generate_validation_batch(self):
assert self.validation_dataset is not None
assert self.data_tags is not None
# Sample indices and get data
index_array = np.random.choice(self.num_validation_samples, self.p.trainer.batch_size)
return self.get_data_from_indices(self.v... | [
"def build_validation_iterator(dataset_name, batch_size, prepro_fn):\n dataset, dataset_info = tfds.load(\n dataset_name,\n split=tfds.Split.VALIDATION,\n as_supervised=True,\n with_info=True\n )\n n_samples = dataset_info.splits['validation'].num_examples\n steps_per_epoch =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shuffle the training and the validation datasets. This could be helpful in between the epochs for randomization. | def shuffle_datasets(self):
assert self.data_tags is not None
assert self.training_dataset is not None
assert self.validation_dataset is not None
self.training_dataset = self.shuffle_data_dictionary(self.training_dataset)
self.validation_dataset = self.shuffle_data_dictionary(sel... | [
"def shuffle(self):\n self.x['train'], self.y['train'] = self._shuffle(\n self.x['train'],\n self.y['train']\n )",
"def _shuffle_training_data(self):\n num_examples = len(self.train_x)\n shuffled_indices = torch.randperm(num_examples)\n self.train_x = self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shuffle a dictionary of the data. | def shuffle_data_dictionary(self, data_dictionary):
num_samples = np.shape(data_dictionary[self.data_tags[0]])[0]
shuffle_order = np.random.permutation(num_samples)
for data_tag in self.data_tags:
data_dictionary[data_tag] = data_dictionary[data_tag][shuffle_order]
return dat... | [
"def testShuffle(self):\n\n sl, map = self._fill(250)\n\n for n in xrange(0, 25):\n keys = map.keys()\n\n self._shuffle(keys, sl)\n self._walk(sl)\n self._step(sl)",
"def shuffle(self):\n self.x['train'], self.y['train'] = self._shuffle(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |