query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Withdraw funds from the portfolio if there is enough cash to allow it. | def withdraw_funds(self, dt, amount):
# Check that amount is positive and that there is
# enough in the portfolio to withdraw the funds
if dt < self.current_dt:
raise ValueError(
'Withdrawal datetime (%s) is earlier than '
'current portfolio datetime (... | [
"def safeWithdrawal(self):\n if self._after_dead_line():\n # each contributor can withdraw the amount they contributed if the goal was not reached\n if not self._funding_goal_reached.get():\n amount = self._balances[self.msg.sender]\n self._balances[self.ms... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Output the portfolio holdings information as a dictionary with Assets as keys and subdictionaries as values. This excludes cash. Returns `dict` The portfolio holdings. | def portfolio_to_dict(self):
holdings = {}
for asset, pos in self.pos_handler.positions.items():
holdings[asset] = {
"quantity": pos.net_quantity,
"market_value": pos.market_value,
"unrealised_pnl": pos.unrealised_pnl,
"realised... | [
"def _construct_all_holdings(self):\n d = dict((s, 0.0) for s in self.symbol_list)\n d['datetime'] = self.backtest_date\n d['cash'] = self.initial_capital\n d['commission'] = 0.0\n d['total'] = self.initial_capital\n d['buy_times'] = 0\n d['sell_times'] = 0\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the market value of the asset to the current trade price and date. | def update_market_value_of_asset(
self, asset, current_price, current_dt
):
if asset not in self.pos_handler.positions:
return
else:
if current_price < 0.0:
raise ValueError(
'Current trade price of %s is negative for '
... | [
"def update_market_value(self, daily_data:dict) -> None:\n pass",
"def update_portfolio_on_market(self, market: MarketEvent):\n self._portfolio.update_market_value(market)",
"def update_market_price(self, price: float):\n with self.__access_lock:\n if self.__valid_price(price):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a Pandas DataFrame of the Portfolio history. | def history_to_df(self):
records = [pe.to_dict() for pe in self.history]
return pd.DataFrame.from_records(
records, columns=[
"date", "type", "description", "debit", "credit", "balance"
]
).set_index(keys=["date"]) | [
"def get_portfolio_df(self):\n df = pd.DataFrame(data=self.asset_manager.asset_history)\n return df.set_index('time')",
"def get_price_history(self):\n # Connect to the database and return cursor\n database = DatabaseMySQL()\n\n # Query database.\n sql = \"Select publishe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test MSE for null model | def null_model_MSE(y_all):
y_train = y_all[y_all["yyyymm"] < TRAIN_DATE].iloc[:,1].to_numpy()
y_test = y_all[y_all["yyyymm"] >= TRAIN_DATE].iloc[:,1].to_numpy()
MSE = np.sum((np.mean(y_train) - y_test)**2) / len(y_test)
print("Null MSE: {:.6f}".format(MSE))
print("Null MSE as % of square m... | [
"def _raise_none_model(self):\n raise ValueError(\"Model is of type None! Was it not initialized?\")",
"def test_plot_mcse_no_sample_stats(models):\n idata = models.model_1\n with pytest.raises(ValueError, match=\"must contain sample_stats\"):\n plot_mcse(idata.posterior, rug=True)",
"def te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Number of stages in series. | def N_stages(self):
return 5 | [
"def num_stages(self) -> int:\n return self.pg_mesh.size(self.pipeline_axis)",
"def n_series(self):\n return self.container['n_series']",
"def num_seq_dep_stages(self):\n n_s = [0]*len(self)\n for i in range(len(self)):\n for j in range(i):\n if self.A[i,j] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turnover time (hr) calculated by batch time divided by number of trains. | def tau_turnover(self):
return self.tau_batch/self.N_trains | [
"def averageTime(self):\n \n pass",
"def _calcPlungerMoveTime(self, move_steps):\n sd = self.sim_state\n start_speed = sd['start_speed']\n top_speed = sd['top_speed']\n cutoff_speed = sd['cutoff_speed']\n slope = sd['slope']\n microstep = sd['microstep']\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return `True` if the url is a page on the website. | def is_page(self, url):
netloc = urlparse.urlparse(url).netloc.lower()
return any(map(lambda domain: netloc.endswith(domain), self.allowed_domains)) | [
"def is_valid_page(url):\n posts = get_posts_in_page(url)\n if posts:\n return True\n else:\n return False",
"def is_webpage(url):\n # Handle types.\n url = url2str(url)\n if type(url) != str:\n return False\n\n # Return true if URL is external webpage, false otherwise.\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the pka of every molecule in the reactants. The pka, as well as the id of the "pka_point" is stored in the molecule. The "pka_point" is the id of the Hydrogen most likely to be donated, or the id of the atom most likely to accept a Hydrogen. The pka is based off of the pka_point of the atom. | def pka(reactants, conditions):
if 'pkas' in conditions and 'pka_points' in conditions:
for reactant in reactants:
id_ = reactant.id
reactant.pka = conditions['pkas'][id_]
reactant.pka_point = conditions['pka_points'][id_]
return True
return False | [
"def kpoints_per_atom(self, atoms=None, kppa=1000):\n if math.fabs((math.floor(kppa ** (1 / 3) + 0.5)) ** 3 - kppa) < 1:\n kppa += kppa * 0.01\n # latt = atoms.lattice_mat\n lengths = atoms.lattice.lat_lengths()\n ngrid = kppa / atoms.num_atoms\n mult = (ngrid * lengths... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Region from Resize Returns a new set of region points based on a current width and height and the bounding box | def regionFromResize(curr_width, curr_height, bounds_width, bounds_height):
# Return
lRet = [0, 0, 0, 0]
# If the current width is larger than the bounds width
if curr_width > bounds_width:
lRet[0] = int(round((curr_width - bounds_width) / 2.0))
lRet[1] = 0
lRet[2] = int(bounds_width + round((curr_width - ... | [
"def calculate_box_region(self, width, height):\n\n left = width * self.piece_width \n top = height * self.piece_height \n right = left + self.piece_width \n bottom = top + self.piece_height \n return left, top, right, bottom",
"def region_points(x, y, width, xmin, xmax):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To Crop Resizes the current dimension so that they completely fill the boundary area, cropping off the parts on the longer dimension | def toCrop(curr_width, curr_height, bounds_width, bounds_height):
# Return
lRet = [0,0]
# Convert current width/height to floats
curr_width = float(curr_width)
curr_height = float(curr_height)
# If either width or height is smaller than the boundary box, resize up
if curr_width < bounds_width or curr_height... | [
"def crop_adjust(self):\n img = self.image_data\n data = np.asarray(img)\n \n data_out = np.empty((self.numRows, self.numCols))\n \n data_out = data[self.row:self.row+self.numRows:, self.col:self.col+self.numCols:, :]\n\n self.image_data = Image.fromarray(data_out, '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To Fit Resizes the current dimensions so that they are no bigger than the boundary | def toFit(curr_width, curr_height, bounds_width, bounds_height):
# Return
lRet = [0,0]
# Convert current width/height to floats
curr_width = float(curr_width)
curr_height = float(curr_height)
# If either width or height is smaller than the boundary box, resize up
if curr_width < bounds_width and curr_height... | [
"def scaleFitWindow(self):\n e = 2.0 # So that no scrollbars are generated.\n w1 = self.width() * 0.65 - e\n h1 = self.height() * 0.65 - e\n a1 = w1 / h1\n # Calculate a new scale value based on the pixmap's aspect ratio.\n w2 = self.canvas.image.width() - 0.0\n h2 ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the scrollbar size. | def updatescroll(self):
if self.node:
#self.update_idletasks() # Required, else dimension of content may not have been computed ?
forgetit, forgetit, x1, forgetit = self.bbox(ALL)
self.sizetree = self.node.sizetree() + (self.winfo_height() / self.nodeheight) - 1
self.configure(scrollregion =... | [
"def update(self, content_size):\n self.content_size = content_size\n\n # Compute scrolling bar length\n size = max(1, int(math.floor(self.h * self.h / content_size)))\n do_redraw = self.size != size\n\n if size < self.h:\n self.size = size # New scrolling bar length\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the full tree. Notice that it is speeder to update only some Nodes (with Node.update() or Node.updatetree() and then tree.draw()), if you know which Nodes have changed. | def updatetree(self):
if self.node:
self.node.update()
self.draw() | [
"def update(self, state: State):\n\n for child in self.root.children:\n if child.state == state:\n self.root = child\n break\n else:\n self.root = Monte_Carlo_Tree.Node(state)",
"def update_node(self, node):",
"def update(self) -> None:\n\t\t# Cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deselect all selected Nodes. | def deselectall(self):
if self.selection:
for node in self.selection[:]: node.deselect() | [
"def unselect_all(self):",
"def unselectAll(self):\n\t\tself.tree.UnselectAll()",
"def deselect_all(self):\n for item in self.queue():\n item.set_checked(False)",
"def deactivate_all(self):\n\t self.active_nodes = [False for i in range(self.nodes)]",
"def deselect_all(self):\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the area of predicted ellipses Arguments | def ellipse_area(preds, target):
# unpack target = (target, mask)
target, mask = target
if preds.size(2) != 4:
raise ValueError('Prediction must be 4-dimensional (x, y, r1, r2), '
f'but got preds.shape[2] = {preds.size(2)}')
areas = preds[:, :, 2] * preds[:, :, 3] * math... | [
"def calculate_area(pred: Tensor, label: Tensor, num_classes: int = 2):\r\n # convert the label to onehot\r\n label = F.one_hot(label, 2).permute(0, 3, 1, 2).float() # N * C * H * W ,\r\n pred = F.softmax(pred, dim=1).float() # N * C * H * W\r\n inter = label * pred\r\n\r\n label_area = torch.sum(l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wrapper of fit method, keep track of index of in self.task list where the results will be put back to | def wrap_fit(task, data, index):
result_queue.put((task.fit(data), index)) | [
"def _parallelFitTasks(est, train, eva, validation, epm):\n modelIter = est.fitMultiple(train, epm)\n def singleTask():\n index, model = next(modelIter)\n model1 = model.transform(validation, epm[index])\n metric = eva.evaluate(model1)\n return index, metric\n return [singleTask... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fit a prediction task using previously saved task file and data file | def fit_from_files(task_file, data_file, verbose=True):
print_fitting_time = 1
if verbose: print '[FitFromFile] Called with \n\ttask: {}\n\tdata: {}'.format(task_file, data_file)
assert os.path.exists(task_file)
assert os.path.exists(data_file)
task = Predictor.pickle_load(task_file)
data = Mi... | [
"def predict(self, datafile):",
"def fit_predict(self):\n self.best_model = self.get_model(self.best_params, 'full')\n self.best_y_pred_future = self.predict(self.best_model, self.best_params, 'future')",
"def fit_predict(self):\n # if self.best_params['use_date_featurizer']:\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the value to which the specified key is mapped, or 1 if this map contains no mapping for the key | def get(self, key: int) -> int:
if key not in self.map:
return -1
return self.map[key] | [
"def get(self, key: int) -> int:\n \n if key not in self.keys:\n return -1\n \n for x in self.map:\n if x[0] == key:\n return x[1]",
"def get(self, key: int) -> int:\n if key in self.hashmap.keys():return self.hashmap[key]\n else:retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the mapping of the specified value key if this map contains a mapping for the key | def remove(self, key: int) -> None:
if key in self.map:
del self.map[key] | [
"def delete(self, key):\n self.map.pop(key, None)",
"def remove(self, key: int) -> None:\n location = self.hash(key)\n value = self.get(key)\n print(key, value, self.hash_map[location])\n if value != -1:\n self.hash_map[location].remove([key, value])",
"def remove_v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the value to which the specified key is mapped, or 1 if this map contains no mapping for the key | def get(self, key: int) -> int:
if key in self.hashmap.keys():return self.hashmap[key]
else:return -1 | [
"def get(self, key: int) -> int:\n \n if key not in self.keys:\n return -1\n \n for x in self.map:\n if x[0] == key:\n return x[1]",
"def get(self, key: int) -> int:\n if key not in self.map:\n return -1\n return self.map[k... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve an existing timed role for a member | async def get(cls, member: discord.Member, role: discord.Role) -> Optional["TempRole"]:
data = await config.member(member).get_raw(str(role.id), default=None)
if data is None:
return None
return cls(member, role=role, **data) | [
"def role():",
"async def _get_role(self, role_id, guild):\n\n return get(guild.roles, id=role_id)",
"def get_role(self):\n memberships = Membership.objects.filter(person = self)\n try:\n role = memberships.order_by('-importance_to_person')[0] # we could just .exclude(importance_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save any changes made to the given role | async def save(self):
await config.member(self.member).set_raw(str(self.role.id), value=self.as_dict) | [
"async def setModRole(self, ctx, role: discord.Role):\n await self._save_mod_role(ctx.guild, role.id)\n await ctx.send(\"Done\")",
"def update(self, role):\n model = models.load('Role', role)\n model.account_id = self.account_id\n\n return self.client.update_role(model)",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply this timed role to the assigned member | async def apply_role(self, *, reason: str = None):
if self.role not in self.member.roles:
try:
await self.member.add_roles(self.role, reason=reason)
except discord.HTTPException:
pass | [
"async def mute(self, ctx, member: discord.Member, *, time:TimeConverter = None):\r\n\r\n if member.top_role >= ctx.author.top_role:\r\n return await ctx.send(\"you can't mute that person\")\r\n\r\n role = discord.utils.get(ctx.guild.roles, name=\"Muted\")\r\n await member.add_roles(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the email address and password match a row in the people table, insert a new session and return it. | def maybe_start_new_session_after_checking_email_and_password(cls,
pgconn, email_address, password):
cursor = pgconn.cursor()
cursor.execute(textwrap.dedent("""
insert into webapp_sessions
(person_uuid)
select person_uuid
from people
... | [
"def ensure_user_in_database():\n if 'email' in login_session:\n user_exists = session.query(exists().where(User.email == login_session['email'])).scalar()\n if not user_exists:\n user = User(\n id=login_session['userid'],\n picture=login_session['picture'],... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the email address and confirmation_code match a row in the people table, and the confirmation_code_set field isn't too far in the past, then insert a new session and return it. The max_age_confirmation_code should be a datetime.timedelta. Also, update the confirmation_code to NULL and the confirmation_code_set to NU... | def maybe_start_new_session_after_checking_email_and_confirmation_code(
cls, pgconn, email_address, confirmation_code,
max_age_confirmation_code):
qry = textwrap.dedent("""
with updated_person as (
update people
set confirmation_code = NULL,
... | [
"def maybe_start_new_session_after_checking_email_and_password(cls,\n pgconn, email_address, password):\n\n cursor = pgconn.cursor()\n\n cursor.execute(textwrap.dedent(\"\"\"\n insert into webapp_sessions\n (person_uuid)\n select person_uuid\n from pe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a nickname to the task. | def add_nickname(self, name):
if not(name in self.nicknames):
self.nicknames.append(name) | [
"def add_nickname(self, nickname):\n if 'Nicknames' not in self.properties:\n self.properties['Nicknames'] = []\n if (len(self.properties['Nicknames']) == 1 and self.properties['Nicknames'][0].startswith('Temp')):\n self.properties['Nicknames'][0] = nickname.title()\n else... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Choose which reward to use as the icon. | def set_icon(self, icon):
icon = icon.title()
if icon in self.rewards:
self.icon = icon | [
"def EventContentMissionExcelAddRewardIcon(builder, RewardIcon):\n return AddRewardIcon(builder, RewardIcon)",
"def AttendanceRewardExcelAddRewardIcon(builder, RewardIcon):\n return AddRewardIcon(builder, RewardIcon)",
"def get_icon(self):\n if self.verb == \"C\" or self.verb == \"A\" or self.verb ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove a task from the list. | def remove_task(self, task):
for i, item in enumerate(self.tasks):
if item is task:
del self.tasks[i] | [
"def remove_task(self, task):\n entry = self.entry_finder.pop(task)\n entry[-1] = self._removed",
"def remove_task(self, task_name):\n return self.__redis__.srem('taskList', task_name)",
"def remove(self, task):\r\n entry = self.entry_finder.pop(task)\r\n entry[-1] = self.REMO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a nickname to a stop. | def add_nickname(self, nickname):
if 'Nicknames' not in self.properties:
self.properties['Nicknames'] = []
if (len(self.properties['Nicknames']) == 1 and self.properties['Nicknames'][0].startswith('Temp')):
self.properties['Nicknames'][0] = nickname.title()
else:
... | [
"def add_nickname(self, name):\n if not(name in self.nicknames):\n self.nicknames.append(name)",
"def nickname(self, new_nickname):\r\n self.set({\"nickname\": new_nickname})",
"def nickname(self, nickname):\n\n self._nickname = nickname",
"def addStop(self, name, distanceToNex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Add a given feature. If obj isn't specified, geometry and properties can be set as arguments directly. | def add_stop(self, obj=None, geometry=None, properties=None):
properties = properties or {}
if isinstance(obj, Stop):
# instead of creating copy, the original feat should reference the same one that was added here
feat = obj._data
elif isinstance(obj, dict):
f... | [
"def add_features(self, obj, annotation):\n if annotation['problem']:\n obj.add(folia.Feature, subset='problem', cls=annotation['problem'])\n if annotation['pos']:\n obj.add(folia.Feature, subset='pos', cls=annotation['pos'])",
"def add_object(self, obj):\n ygrid, xgrid ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find a stop within the map by its name or nickname. | def find_stop(self, stop_name):
stops_found = []
stop_name = stop_name.replace('’', "'")
if '\n' in stop_name:
raise StopNotFound
for stop in self:
if (stop.properties['Stop Name'].title() == stop_name.title()) or (stop_name.title() in stop.properties['Nicknames']... | [
"def __find_workplace (label):\n from data import workplace as mod\n workplaces = mod.load ( )\n \n for workplace in workplaces.get_all ( ):\n if label == workplace.label:\n return workplace\n else:\n raise Exception ('Aplikacija ne pozna delovisca: ' + label)",
"def find_stop_near(place_name):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new stop to the map. | def new_stop(self, coordinates, name): # TODO Add check for being in the map range
name = name.replace('’', "'")
if ((self._data['bounds'][0] < coordinates[1] < self._data['bounds'][2]) and (self._data['bounds'][1] < coordinates[0] < self._data['bounds'][3])) or ((self._data['bounds'][2] < coordinates... | [
"def addStop(self, name, distanceToNext):\r\n if self.startLocation is None:\r\n self.startLocation = Location(name, None, 0)\r\n else:\r\n currStop = self.startLocation\r\n while currStop.next is not None:\r\n currStop = currStop.next\r\n cur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check for and reset only old stops in the map. This should get deprecated by moving the last edit to the map properties. | def reset_old(self):
stops_reset = False
for stop in self:
if stop.properties['Last Edit'] != int(self.now().strftime("%j")):
stop._map = self
stop.reset()
stops_reset = True
else:
try:
if stop.pr... | [
"def reset_all(self):\n for i, stop in enumerate(self):\n stop._map = self\n stop.reset()",
"def stops_from_db(self, geofence_helper):\n pass",
"def _early_stop(self, meters):\n return False",
"def _on_hass_stop(_: Event) -> None:\n cancel_update_stale()",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset all the stops in the map. | def reset_all(self):
for i, stop in enumerate(self):
stop._map = self
stop.reset() | [
"def reset(self):\n for tlight in self.trafficLights:\n self.trafficLights[tlight].reset()",
"def reset_map(self):\n self.map_buffer = ''\n self.elements = []\n self.load_map()",
"def reset_map(self):\n self.x = None\n self.X = None\n self.y = None\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove a stop from the map. | def remove_stop(self, stop):
for i, item in enumerate(self):
if item.properties == stop.properties:
del self[i]
break | [
"def remove(self, start, stop):\n # delete from our map structure\n if start in self.map:\n del self.map[start]\n # delete any of these coordinates in our all_coords data structure\n for i in range(start, stop + 1):\n if i in self.all_coords:\n del se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modification of pygeoj.load to work with the ResearchMap class. | def load(filepath=None, data=None, **kwargs):
return ResearchMap(filepath, data, **kwargs) | [
"def _load_geo(self):\n super()._load_geo()",
"def load_from_geojson(self, filename_or_url):",
"def load_geo_reference():\n return json.load(open(str(paths.file_geo_reference)))",
"def _load_geo(self):\n geo_path = os.path.join(self.subjects_dir, self.subj_id, 'surf',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modification of pygeoj.new to work with the ResearchMap class. | def new():
return ResearchMap() | [
"def __init__(self, locmap):\n self.locmap = locmap",
"def __init__(self, indicator, georecord, domain, GEOS_point=None, place=None):\n\n self.indicator = indicator\n self.georecord = georecord\n self.domain = domain\n\tself.markers = []\n\n if GeoLevel.objects.filter(parent=geo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert the np.ndarray `values` into a complete balanced tree. Assumes `values` is sorted ascending. Returns a list `t` of the same length in which t[i] > t[2i+1] and t[i] < t[2i+2] for all i. | def _treeify(values):
if len(values) == 1: # this case causes problems later
return values
tree = np.empty_like(values)
# Tree indices work as follows:
# 0 is the root
# 2n+1 is the left child of n
# 2n+2 is the right child of n
# So we now rearrange ... | [
"def _treeify(values):\n if len(values) == 1: # this case causes problems later\n return values\n tree = np.empty_like(values)\n\n # The first step is to remove the bottom row of leaves, which might not be exactly full\n last_full_row = int(np.log2(len(values) + 1) - 1)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert an occurrence of `value` into the btree. | def insert(self, value):
i = 0
n = len(self._tree)
while i < n:
cur = self._tree[i]
self._counts[i] += 1
if value < cur:
i = 2 * i + 1
elif value > cur:
i = 2 * i + 2
else:
return
... | [
"def insert(self, value):\r\n self._root = self._rec_insert(self._root, value)",
"def insert(self, value):\n i = 0\n n = len(self._tree)\n while i < n:\n cur = self._tree[i]\n self._counts[i] += 1\n if value < cur:\n i = 2 * i + 1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the rank and count of the value in the btree. | def rank(self, value):
i = 0
n = len(self._tree)
rank = 0
count = 0
while i < n:
cur = self._tree[i]
if value < cur:
i = 2 * i + 1
continue
elif value > cur:
rank += self._counts[i]
... | [
"def rank(self):\n return self.n.cardinality()",
"def rank(self, current_order_by_value: Comparable, current_row_number: int) -> int:",
"def rank(self):\n return 0",
"def node_count(self) -> int:\n return int(self.graph_tuple_stats.node_count or 0)",
"def rank(self) -> tskit.Rank:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the concordance index (Cindex) between two series of event times. The first is the real survival times from the experimental data, and the other is the predicted survival times from a model of some kind. The concordance index is a value between 0 and 1 where, 0.5 is the expected result from random prediction... | def concordance_index(event_times, predicted_event_times, event_observed=None):
event_times = np.array(event_times, dtype=float)
predicted_event_times = np.array(predicted_event_times, dtype=float)
# Allow for (n, 1) or (1, n) arrays
if event_times.ndim == 2 and (event_times.shape[0] == 1 or
... | [
"def c_index(prediction, T, C, prediction_type = 'risk'):\n \n if prediction_type == 'risk':\n risk = prediction\n prediction = None\n \n elif prediction_type == 'survival_time':\n # normalize\n prediction = prediction / np.max(prediction)\n # convert to risk\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle all pairs that exited at the same time as truth[first_ix]. | def handle_pairs(truth, pred, first_ix):
next_ix = first_ix
while next_ix < len(truth) and truth[next_ix] == truth[first_ix]:
next_ix += 1
pairs = len(times_to_compare) * (next_ix - first_ix)
correct = 0
tied = 0
for i in range(firs... | [
"def _handle_pairs(truth, pred, first_ix, times_to_compare):\n next_ix = first_ix\n while next_ix < len(truth) and truth[next_ix] == truth[first_ix]:\n next_ix += 1\n pairs = len(times_to_compare) * (next_ix - first_ix)\n correct = np.int64(0)\n tied = np.int64(0)\n for i in range(first_ix,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read a region from the slide Return a numpy RBG array | def read_slide(slide, x, y, level, width, height, as_float=False):
im = slide.read_region((x, y), level, (width, height))
im = im.convert('RGB') # drop the alpha channel
if as_float:
im = np.asarray(im, dtype=np.float32)
else:
im = np.asarray(im)
assert im.shape == (height, width, 3... | [
"def read_image(path):\n img = ndimage.imread(path, mode=\"RGB\") \n return img",
"def loadROI(ROI_path):\r\n data = np.load(ROI_path)\r\n roi = data['arr_0'].all()\r\n \r\n return roi",
"def read_seaice_mask(file=r'C:\\Users\\apbarret\\Documents\\data\\sea_ice_index\\Arctic_region_mask_Mei... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return tissue pixels for an image | def find_tissue_pixels(image):
img_RGB = np.array(image)
img_HSV = rgb2hsv(img_RGB)
background_R = img_RGB[:, :, 0] > 203
background_G = img_RGB[:, :, 1] > 191
background_B = img_RGB[:, :, 2] > 201
tissue_RGB = np.logical_not(background_R & background_G & background_B)
tissue_S = img_HSV[:, ... | [
"def test_tiled():\n size = [25, 25]\n img = Image.new('RGB', (10, 10))\n img.putpixel((5, 5), (0, 255, 0))\n\n parameters = {'data': [img], 'size': size}\n\n tiled = images.tiled(parameters)\n\n assert_equal(tiled.size, tuple(size))\n assert_equal(tiled.getpixel((5, 5)), (0, 255, 0))\n asse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if there is any tumor pixel in the 128x128 centre | def check_patch_centre(patch_mask, patch_centre):
# get patch size
patch_size = patch_mask.shape[0]
# get the offset to check the 128x128 centre
offset = int((patch_size - patch_centre) / 2)
# sum the pixels in the 128x128 centre for the tumor mask
sum_cancers = np.sum(patch_mask[offset:offse... | [
"def miss_pixel(patch):\n return np.argwhere(patch == -100).shape[0] > 0",
"def count_masked_pixel(skymap):\n return len(skymap[skymap == 1.0])",
"def _is_blank(im):\n \n # Take the r% center\n r = 0.2\n h1 = int(float(im.shape[0]) * r)\n h2 = im.shape[0] - h1\n w1 = int(float(im.sha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Selects the right resource bundles for learner workers based off of cf. | def _get_learner_bundles(cf: AlgorithmConfig) -> List[Dict[str, int]]:
if cf.num_learner_workers > 0:
if cf.num_gpus_per_learner_worker:
learner_bundles = [
{"GPU": cf.num_learner_workers * cf.num_gpus_per_learner_worker}
]
... | [
"def _bundle_is_feasible(self, bundle):\n is_feasible = True\n reason = ''\n # 1. Build a mapping from resource-specific info to resource record\n res_to_record_mapping = self._res_man.get_res_to_record_mapping()\n # 2. Check feasibility of zones\n zones = bundle.copy_zones... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new algorithm instance from a given checkpoint. | def from_checkpoint(
checkpoint: Union[str, Checkpoint],
policy_ids: Optional[Container[PolicyID]] = None,
policy_mapping_fn: Optional[Callable[[AgentID, EpisodeID], PolicyID]] = None,
policies_to_train: Optional[
Union[
Container[PolicyID],
Ca... | [
"def from_checkpoint(cls, checkpoint: Checkpoint) -> \"XGBoostPredictor\":\n with checkpoint.as_directory() as path:\n bst = xgboost.Booster()\n bst.load_model(os.path.join(path, MODEL_KEY))\n preprocessor_path = os.path.join(path, PREPROCESSOR_KEY)\n if os.path.ex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recovers an Algorithm from a state object. The `state` of an instantiated Algorithm can be retrieved by calling its `get_state` method. It contains all information necessary to create the Algorithm from scratch. No access to the original code (e.g. configs, knowledge of the Algorithm's class, etc..) is needed. | def from_state(state: Dict) -> "Algorithm":
algorithm_class: Type[Algorithm] = state.get("algorithm_class")
if algorithm_class is None:
raise ValueError(
"No `algorithm_class` key was found in given `state`! "
"Cannot create new Algorithm."
)
... | [
"def __getstate__(self) -> Dict:\n # Add config to state so complete Algorithm can be reproduced w/o it.\n state = {\n \"algorithm_class\": type(self),\n \"config\": self.config,\n }\n\n if hasattr(self, \"workers\"):\n state[\"worker\"] = self.workers.lo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a Unified logger with the default prefix. | def default_logger_creator(config):
return UnifiedLogger(config, logdir, loggers=None) | [
"def create_logger() -> logging.Logger:\n pass # TODO: Replace with implementation!",
"def default_logger_creator(config):\n if config['multiagent']['policies_to_train'][0] == '0':\n agent_path = os.path.join(EXPERIMENT_PATH, \"player0\")\n elif config['multiagent']['polic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of remote worker IDs to fetch metrics from. Specific Algorithm implementations can override this method to use a subset of the workers for metrics collection. | def _remote_worker_ids_for_metrics(self) -> List[int]:
return self.workers.healthy_worker_ids() | [
"def get_compute_worker_ids(self) -> List[str]:\n entries = self._compute_worker_api.get_docker_worker_registry_entries()\n return [entry.id for entry in entries]",
"def get_worker_id_list(self):\r\n return self._workers_id",
"def workers(self):\n return self.worker_list",
"def get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a default Policy class to use, given a config. This class will be used by an Algorithm in case the policy class is not provided by the user in any single or multiagent PolicySpec. | def get_default_policy_class(
cls,
config: AlgorithmConfig,
) -> Optional[Type[Policy]]:
return None | [
"def get_policy_class(name: str):\n if name not in POLICIES:\n return None\n\n path = POLICIES[name]\n module = importlib.import_module(\"ray.rllib.algorithms.\" + path)\n\n if not hasattr(module, name):\n return None\n\n return getattr(module, name)",
"def normal_policy_class():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluates current policy under `evaluation_config` settings. Uses the AsyncParallelRequests manager to send frequent `sample.remote()` requests to the evaluation RolloutWorkers and collect the results of these calls. Handles worker failures (or slowdowns) gracefully due to the asynch'ness and the fact that other eval R... | def _evaluate_async(
self,
duration_fn: Optional[Callable[[int], int]] = None,
) -> dict:
# How many episodes/timesteps do we need to run?
# In "auto" mode (only for parallel eval + training): Run as long
# as training lasts.
unit = self.config.evaluation_duration_uni... | [
"def _should_create_evaluation_rollout_workers(cls, eval_config: \"AlgorithmConfig\"):\n run_offline_evaluation = (\n eval_config.off_policy_estimation_methods\n and not eval_config.ope_split_batch_by_episode\n )\n return not run_offline_evaluation and (\n eval_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try to restore failed workers if necessary. Algorithms that use custom RolloutWorkers may override this method to disable default, and create custom restoration logics. | def restore_workers(self, workers: WorkerSet):
# If `workers` is None, or
# 1. `workers` (WorkerSet) does not have a local worker, and
# 2. `self.workers` (WorkerSet used for training) does not have a local worker
# -> we don't have a local worker to get state from, so we can't recover
... | [
"def worker_recover(name, workers=None, profile=\"default\"):\n if workers is None:\n workers = []\n return _bulk_state(\"modjk.bulk_recover\", name, workers, profile)",
"def restore_task_settings(restore_data):\n # only broadcast if there are workers\n if len(util.get_all_worker_names()):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Default single iteration logic of an algorithm. Collect onpolicy samples (SampleBatches) in parallel using the Algorithm's RolloutWorkers (.remote). Concatenate collected SampleBatches into one train batch. | def training_step(self) -> ResultDict:
# Collect SampleBatches from sample workers until we have a full batch.
with self._timers[SAMPLE_TIMER]:
if self.config.count_steps_by == "agent_steps":
train_batch = synchronous_parallel_sample(
worker_set=self.worke... | [
"def train_loop(self):\n pass",
"def train_process(self):\n raise NotImplementedError",
"def run(self):\n\n mconns: Dict[str, cb_bin_client.MemcachedClient] = {} # State kept across scatter_gather() calls.\n backoff_cap: int = self.opts.extra.get(\"backoff_cap\", 10)\n while ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return policy for the specified id, or None. | def get_policy(self, policy_id: PolicyID = DEFAULT_POLICY_ID) -> Policy:
return self.workers.local_worker().get_policy(policy_id) | [
"def get_policy_by_id(self, id):\n for service, policy_list in self.remote_store.get_policy_list().items():\n for policy in policy_list:\n if policy.id == id:\n return policy",
"def get(self, req, policy_id):\n policy = self.rpc_client.policy_get(req.cont... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a dictionary of policy ids to weights. | def get_weights(self, policies: Optional[List[PolicyID]] = None) -> dict:
return self.workers.local_worker().get_weights(policies) | [
"def get_policy_weights(self) -> List[np.ndarray]:\n return self._neural_net.get_weights()",
"def init_weights(rule, voters):\n if (rule == \"per_multiplication_offset\" or\n rule == \"per_nash\" or\n rule == \"per_equality\" or\n rule == \"per_phragmen\"):\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set policy weights by policy id. | def set_weights(self, weights: Dict[PolicyID, dict]):
self.workers.local_worker().set_weights(weights) | [
"def policy_id(self, policy_id):\n\n self._policy_id = policy_id",
"def policyid(self, policyid):\n self._policyid = policyid",
"def policy_id(self, policy_id):\n self._policy_id = policy_id",
"def update_policy(self, policy_id, policy):\n raise exception.NotImplemented() # pragma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exports policy model with given policy_id to a local directory. | def export_policy_model(
self,
export_dir: str,
policy_id: PolicyID = DEFAULT_POLICY_ID,
onnx: Optional[int] = None,
) -> None:
self.get_policy(policy_id).export_model(export_dir, onnx) | [
"def export_policy_checkpoint(\n self,\n export_dir: str,\n policy_id: PolicyID = DEFAULT_POLICY_ID,\n ) -> None:\n policy = self.get_policy(policy_id)\n if policy is None:\n raise KeyError(f\"Policy with ID {policy_id} not found in Algorithm!\")\n policy.expo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exports Policy checkpoint to a local directory and returns an AIR Checkpoint. | def export_policy_checkpoint(
self,
export_dir: str,
policy_id: PolicyID = DEFAULT_POLICY_ID,
) -> None:
policy = self.get_policy(policy_id)
if policy is None:
raise KeyError(f"Policy with ID {policy_id} not found in Algorithm!")
policy.export_checkpoint(e... | [
"def make_checkpoint(self):\n try:\n # Locate the checkpoint directory.\n checkpoint_dir = os.path.join(self.config[consts.EXPORT_DIR],\n \"checkpoints\",\n \"experiment_%09d\" % self.id,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports a policy's model with given policy_id from a local h5 file. | def import_policy_model_from_h5(
self,
import_file: str,
policy_id: PolicyID = DEFAULT_POLICY_ID,
) -> None:
self.get_policy(policy_id).import_model_from_h5(import_file)
# Sync new weights to remote workers.
self._sync_weights_to_workers(worker_set=self.workers) | [
"def load_policy(self, source, templatefile, key):\n self._logger.info(\n f\"Loading policy model from {source} and templates from {templatefile} to {key}\"\n )\n model = self._load_model(source)\n templates = pd.read_hdf(templatefile, \"table\")\n self._policies[key] =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns env_id and creator callable given original env id from config. | def _get_env_id_and_creator(
env_specifier: Union[str, EnvType, None], config: AlgorithmConfig
) -> Tuple[Optional[str], EnvCreator]:
# Environment is specified via a string.
if isinstance(env_specifier, str):
# An already registered env.
if _global_registry.contains(... | [
"def get_env_creator(env_id):\n if not _global_registry.contains(ENV_CREATOR, env_id):\n raise ValueError(f\"Environment id {env_id} not registered in Tune\")\n return _global_registry.get(ENV_CREATOR, env_id)",
"def auto_env(env_id, **kwargs):\n if env_id in ENV_BUILDER_REGISTRY:\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Synchronizes the filter stats from `workers` to `central_worker`. .. and broadcasts the central_worker's filter stats back to all `workers` (if configured). | def _sync_filters_if_needed(
self,
*,
central_worker: RolloutWorker,
workers: WorkerSet,
config: AlgorithmConfig,
) -> None:
if central_worker and config.observation_filter != "NoFilter":
FilterManager.synchronize(
central_worker.filters,
... | [
"def _sync_weights_to_workers(\n self,\n *,\n worker_set: WorkerSet,\n ) -> None:\n # Broadcast the new policy weights to all remote workers in worker_set.\n logger.info(\"Synchronizing weights to workers.\")\n worker_set.sync_weights()",
"def synchronize(\n loc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sync "main" weights to given WorkerSet or list of workers. | def _sync_weights_to_workers(
self,
*,
worker_set: WorkerSet,
) -> None:
# Broadcast the new policy weights to all remote workers in worker_set.
logger.info("Synchronizing weights to workers.")
worker_set.sync_weights() | [
"def set_weights(self, weights: Dict[PolicyID, dict]):\n self.workers.local_worker().set_weights(weights)",
"def update_model_weights():\n content = request.json\n weights = content['weights']\n num_party = content['num_party']\n logging.info(\"Num workers involved = {}\".format... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merges a complete Algorithm config dict with a partial override dict. Respects nested structures within the config dicts. The values in the partial override dict take priority. | def merge_algorithm_configs(
cls,
config1: AlgorithmConfigDict,
config2: PartialAlgorithmConfigDict,
_allow_unknown_configs: Optional[bool] = None,
) -> AlgorithmConfigDict:
config1 = copy.deepcopy(config1)
if "callbacks" in config2 and type(config2["callbacks"]) is d... | [
"def override_options(\n config: DictLike,\n selected_options: Tuple[Any, ...],\n set_of_possible_options: Tuple[Iterable[Tuple[str, Any]], ...],\n config_containing_override: Optional[DictLike] = None,\n) -> DictLike:\n if config_containing_override is None:\n config_containing_override = con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Env validator function for this Algorithm class. Override this in child classes to define custom validation behavior. | def validate_env(env: EnvType, env_context: EnvContext) -> None:
pass | [
"def validator(self):\n pass",
"def validate_env(self) -> None:\n errors = []\n\n self.user_name = env.str('USER_NAME')\n if not self.user_name:\n errors.append('USER_NAME environment variable needs to be set to your MyQ user name')\n\n self.password = env.str('PASSWO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports a model from import_file. | def import_model(self, import_file: str):
# Check for existence.
if not os.path.exists(import_file):
raise FileNotFoundError(
"`import_file` '{}' does not exist! Can't import Model.".format(
import_file
)
)
# Get the for... | [
"def importModel(model_name):\n module_path = os.path.join(path, \"models\")\n module_path = os.path.join(module_path, model_name + \".py\")\n model = importClass(model_name, model_name, module_path)\n return model",
"def load_model(self, filename):\r\n pass",
"def load_model(self, filename):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns current state of Algorithm, sufficient to restore it from scratch. | def __getstate__(self) -> Dict:
# Add config to state so complete Algorithm can be reproduced w/o it.
state = {
"algorithm_class": type(self),
"config": self.config,
}
if hasattr(self, "workers"):
state["worker"] = self.workers.local_worker().get_stat... | [
"def getstate(self):\r\n return SparseGP.getstate(self) + [self.init]",
"def get_state(self):\n return self.problem.get_current_state()",
"def _getAlgorithmState(self,traj):\n state = {}\n state['lastStepSize'] = copy.deepcopy(self.counter['lastStepSize' ].get(traj,None))\n state['gr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a checkpoint info or object to a proper Algorithm state dict. The returned state dict can be used inside self.__setstate__(). | def _checkpoint_info_to_algorithm_state(
checkpoint_info: dict,
policy_ids: Optional[Container[PolicyID]] = None,
policy_mapping_fn: Optional[Callable[[AgentID, EpisodeID], PolicyID]] = None,
policies_to_train: Optional[
Union[
Container[PolicyID],
... | [
"def __getstate__(self) -> Dict:\n # Add config to state so complete Algorithm can be reproduced w/o it.\n state = {\n \"algorithm_class\": type(self),\n \"config\": self.config,\n }\n\n if hasattr(self, \"workers\"):\n state[\"worker\"] = self.workers.lo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a MultiAgentReplayBuffer instance if necessary. | def _create_local_replay_buffer_if_necessary(
self, config: PartialAlgorithmConfigDict
) -> Optional[MultiAgentReplayBuffer]:
if not config.get("replay_buffer_config") or config["replay_buffer_config"].get(
"no_local_replay_buffer"
):
return
return from_confi... | [
"def build_replay_buffer(agent, batch_size, steps_per_loop):\n buf = tf_uniform_replay_buffer.TFUniformReplayBuffer(\n data_spec=agent.policy.trajectory_spec,\n batch_size=batch_size,\n max_length=steps_per_loop)\n return buf",
"def LocalReplayMultiagent(replay_buffers, train_batch_size, min_size... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs one training iteration (self.iteration will be +1 after this). Calls `self.training_step()` repeatedly until the minimum time (sec), sample or training steps have been reached. | def _run_one_training_iteration(self) -> Tuple[ResultDict, "TrainIterCtx"]:
# In case we are training (in a thread) parallel to evaluation,
# we may have to re-enable eager mode here (gets disabled in the
# thread).
if self.config.get("framework") == "tf2" and not tf.executing_eagerly():... | [
"def start_training(self):\n i = 0\n for _ in range(self.train_steps):\n print(f\"Start Training Step {i + 1}\")\n self.model.learn(total_timesteps=self.total_time_steps)\n self.model.save(self.save_path)\n print(f\"Finished Training Step {i + 1}\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs one training iteration and one evaluation step in parallel. First starts the training iteration (via `self._run_one_training_iteration()`) within a ThreadPoolExecutor, then runs the evaluation step in parallel. In autoduration mode (config.evaluation_duration=auto), makes sure the evaluation step takes roughly the... | def _run_one_training_iteration_and_evaluation_in_parallel(
self,
) -> Tuple[ResultDict, "TrainIterCtx"]:
with concurrent.futures.ThreadPoolExecutor() as executor:
train_future = executor.submit(lambda: self._run_one_training_iteration())
# Pass the train_future into `self._r... | [
"def _run_one_training_iteration(self) -> Tuple[ResultDict, \"TrainIterCtx\"]:\n # In case we are training (in a thread) parallel to evaluation,\n # we may have to re-enable eager mode here (gets disabled in the\n # thread).\n if self.config.get(\"framework\") == \"tf2\" and not tf.execu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs offline evaluation via `OfflineEvaluator.estimate_on_dataset()` API. This method will be used when `evaluation_dataset` is provided. | def _run_offline_evaluation(self):
assert len(self.workers.local_worker().policy_map) == 1
parallelism = self.evaluation_config.evaluation_num_workers or 1
offline_eval_results = {"off_policy_estimator": {}}
for evaluator_name, offline_evaluator in self.reward_estimators.items():
... | [
"def evaluate(self, dataset):\n\t\tpass",
"def evaluate(self, dataset):\n return self.model.evaluate(dataset.X_val, dataset.y_val)",
"def run_evaluation(\n self,\n training_set,\n validation_set,\n test_set,\n progress_tracker: ProgressTracker,\n train_summary_wr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines whether we need to create evaluation workers. Returns False if we need to run offline evaluation (with ope.estimate_on_dastaset API) or when local worker is to be used for | def _should_create_evaluation_rollout_workers(cls, eval_config: "AlgorithmConfig"):
run_offline_evaluation = (
eval_config.off_policy_estimation_methods
and not eval_config.ope_split_batch_by_episode
)
return not run_offline_evaluation and (
eval_config.evalua... | [
"def _workers_available(self) -> bool:\n total_compute_power = sum(self.client.nthreads().values())\n if len(self.futures) < total_compute_power:\n return True\n return False",
"def has_worker(self) -> bool:\n return False",
"def evaluationManagerExists():\n\n pass",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Record the framework and algorithm used. | def _record_usage(self, config):
record_extra_usage_tag(TagKey.RLLIB_FRAMEWORK, config["framework"])
record_extra_usage_tag(TagKey.RLLIB_NUM_WORKERS, str(config["num_workers"]))
alg = self.__class__.__name__
# We do not want to collect user defined algorithm names.
if alg not in ... | [
"def dump_core(self):\n raise AssertionError(\"Core Dump function not implemented\")",
"def main(self):\n pass",
"def send_framework_info(framework: str):\n t = tm.Telemetry()\n t.send_event('mo', 'framework', framework)",
"def main():\r\n parser = get_parser()\r\n config = parser.parse_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take features and labels and expand them into labelled examples for the model. | def expand_features_and_labels(x_feat, y_labels):
x_expanded = []
y_expanded = []
for x, y in zip(x_feat, y_labels):
for segment in x:
x_expanded.append(segment)
y_expanded.append(y)
return x_expanded, y_expanded | [
"def batch_features_labels(features, labels, batch_size):\n for start in range(0, len(features), batch_size):\n end = min(start + batch_size, len(features))\n #print(labels[start:end])\n yield features[start:end], labels[start:end]",
"def batch_features_labels(features, labels, batch_size)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given units, return the number of days as a float. | def __get_number_of_day(units):
multiplier = DAYS_IN_A_YEAR
if units:
if units.lower().startswith("w"):
multiplier = DAYS_IN_A_WEEK
elif units.lower().startswith("m"):
multiplier = DAYS_IN_A_MONTH
return multiplier | [
"def calculate_seconds_in_days(days):\n return int(days * 86400)",
"def get_nr_days(start, end, duration):\n return duration.days",
"def total_days(self):\n return self.total_microseconds() / 86400000000",
"def get_number_days(self):\r\n return 1",
"def daysinunit(self, unit):\n\t\tretur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw N samples for the discrete probability mass function PM that is defined over the support X. X ... Support of RV np.array([...]) PM ... P(X) np.array([...]) N ... number of samples scalar | def sample_discrete_pmf(X, PM, N):
assert np.isclose(np.sum(PM), 1.0)
assert all(0.0 <= p <= 1.0 for p in PM)
y = np.zeros(N)
cumulativePM = np.cumsum(PM) # build CDF based on PMF
offsetRand = np.random.uniform(0, 1) * (1 / N) # offset to circumvent numerical issues with cumulativePM
comb ... | [
"def prob1(n):\n\n # create a giant draw from a normal distribution\n random_draws = np.random.normal(loc= 0, scale = 1, size = n)\n\n # mask the values\n mask = random_draws > 3\n\n return np.sum(mask)/float(n)",
"def random_mass(pdf, pdf_comp, mmin, mmax, nsample=1):\n\n if not isinstance(mmin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show contour plot for bivariate Gaussian with given mu and cov in the range specified. mu ... mean [mu1, mu2] cov ... covariance matrix [[cov_00, cov_01], [cov_10, cov_11]] xmin, xmax, ymin, ymax ... range for plotting | def plot_gauss_contour(mu, cov, xmin, xmax, ymin, ymax, title):
npts = 500
deltaX = (xmax - xmin) / npts
deltaY = (ymax - ymin) / npts
stdev = [0, 0]
stdev[0] = np.sqrt(cov[0][0])
stdev[1] = np.sqrt(cov[1][1])
x = np.arange(xmin, xmax, deltaX)
y = np.arange(ymin, ymax, deltaY)
... | [
"def plotCov(mu, C, axis):\n xx1 = [mu[0,0]-0.2,mu[0,0]+0.2]\n xx2 = [mu[1,0]-0.2,mu[1,0]+0.2]\n X1,X2 = meshgrid(linspace(xx1[0],xx1[1],50), linspace(xx2[0],xx2[1],50))\n f = zeros(shape(X1))\n Cinv = linalg.inv(C)\n CinvDet = linalg.det(Cinv)\n if CinvDet > 10**15:\n print \"The follow... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the likelihood of X for bivariate Gaussian specified with mu and cov. X ... vector to be evaluated np.array([[x_00, x_01], ..., [x_n0, x_n1]]) mu ... mean [mu1, mu2] cov ... covariance matrix [[cov_00, cov_01],[cov_10, cov_11]] | def likelihood_bivariate_normal(X, mu, cov):
dist = multivariate_normal(mu, cov)
P = dist.pdf(X)
return P | [
"def estimate_gaussian_params(X):\n mu = np.mean(X, axis=0)\n sigma = np.cov(X.T)\n\n return mu, sigma",
"def correlated_gaussian_loglikelihood(xs, means, cov):\n lu,piv=sl.lu_factor(cov)\n\n lambdas=np.diag(lu)\n\n ndim=xs.shape[0]\n \n ds=(xs-means)*sl.lu_solve((lu,piv), xs-means)/2.0\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the end of day stock CSV data into cuDF dataframe Arguments | def process(self, inputs):
df = cudf.read_csv(self.conf['path'])
# extract the year, month, day
ymd = df['DTE'].astype('str').str.extract(r'(\d\d\d\d)(\d\d)(\d\d)')
# construct the standard datetime str
df['DTE'] = ymd[0].str.cat(ymd[1],
'-').st... | [
"def _load_data(self):\n data_file = self._get_data_file()\n tmp_file = data_file+'_temp'\n\n if os.path.isfile(data_file):\n df = pd.read_csv(data_file)\n df2 = df.iloc[[0, -1]]\n first_date = self._convert_date_str_to_datetime(df2.at[0,'date'])\n last_date = self._convert_date_str_to_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find all combinations of the specified length from a sequence. | def combinations(sequence, length, NULL=object()):
if length <= 0:
combos = [NULL]
else:
combos = []
for i, item in enumerate(sequence, 1):
rem_items = sequence[i:]
rem_combos = combinations(rem_items, length-1)
combos.extend(item if combo is N... | [
"def AllCombinations(data, comblength):\n return [c for c in itertools.combinations(data, comblength)]",
"def possible_motifs_by_length(length, base_set=\"ACGU\"):\n args = [base_set for i in xrange(length)]\n for permutation in itertools.product(*args):\n yield \"\".join(permutation)",
"def gen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
takes a Binary String Tree and returns the sum of the lengths of all the leaves. BST > num | def total_len(BST):
if isinstance(BST,tuple):
return total_len(BST[0]) + total_len(BST[1])
else:
return len(BST) | [
"def tree_size(tree) -> int:\n return sum(x.size for x in jax.tree_leaves(tree))",
"def count_leaves(tree):\n if is_leaf(tree):\n return 1\n else:\n branch_counts = [count_leaves(b) for b in tree]\n return sum(branch_counts)",
"def _size(root: _BSTNode) -> int:\n return _s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
takes a BST and returns a single long tuple whose items are the leaves of the tree. BST > str | def flatten(BST):
leaves = ()
if isinstance(BST,tuple):
return flatten(BST[0]) + flatten(BST[1])
else:
leaves = leaves + (BST,)
return leaves | [
"def get_leaves(tree):\n tree = Tree(tree, format=1)\n midpoint = tree.get_midpoint_outgroup()\n tree.set_outgroup(midpoint)\n tree_style = TreeStyle()\n tree_style.show_leaf_name = False\n nodes = tree.search_nodes(name=\"#1\")[0]\n leaves = sorted(['_'.join(leaf.name.split('_')[:2]) for leaf ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a selection, return the resulting record's PK field's value | async def get_pk_value(self, selection):
record = await self.get_one(selection)
return record[self.primary_key] | [
"def select_one(cls, pk):\n with sqlite3.connect(cls.dbpath) as conn:\n conn.row_factory = sqlite3.Row\n curs = conn.cursor()\n sql = f\"\"\"SELECT * FROM {cls.tablename} WHERE pk =?;\"\"\"\n curs.execute(sql, (pk,)) #don't forget to put a comma after single value ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get object id by str or Condition Immediately return if value is str. | async def get_object_id(self, value):
if isinstance(value, str):
return value
elif isinstance(value, Condition):
return await self.get_pk_value(value)
else:
raise SelectError(f"Selection must be of type {Condition} or {str}") | [
"def get_object_from_ident(cls, value: str):\n return get_object_or_404(cls, **filter_from_ident(value))",
"def getid(obj):\n try:\n return obj.id\n except AttributeError:\n return obj",
"def default_get_identifier(obj_or_string):\n if isinstance(obj_or_string, six.string_types):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return true if string contains a char that appears exactly x times | def has_n_same(string, n):
all_chars = {}
for char in string: # sum up count of each char
all_chars.setdefault(char, 0)
all_chars[char] += 1
for char, count in all_chars.items(): # check how many appeared n times
if count == n:
return True
return False | [
"def _spaceEfficientHasRepeatCharacters(check_string):\n for i in range(len(check_string)):\n for j in range(len(check_string)):\n if check_string[i] == check_string[j] and i != j:\n return True\n return False",
"def have_n_letters(box_id: str, n: int) ->... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return product of boxes with 2 same chars and boxes with 3 same chars | def get_checksum(boxlist):
twosames = threesames = 0
for boxname in boxlist:
if has_n_same(boxname, 2):
twosames += 1
if has_n_same(boxname, 3):
threesames += 1
return twosames * threesames | [
"def checksum(box_ids: List[str]) -> int:\n contain_double = 0\n contain_triple = 0\n for identifier in box_ids:\n if have_n_letters(identifier, 2):\n contain_double += 1\n if have_n_letters(identifier, 3):\n contain_triple += 1\n return contain_double * contain_tripl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the string of shared characters between the correct boxes | def find_shared_chars_of_neighbours(boxlist):
for b1_pos, b1_name in enumerate(boxlist):
for b2_name in boxlist[b1_pos:]: # skip boxes that have been compared already
shared_chars = []
misses = 0
for pos, char in enumerate(b1_name):
if b2_name[pos] == cha... | [
"def differByOneChar(boxid1, boxid2):\n index = 0\n diffChars = 0\n result = \"\"\n while index < len(boxid1):\n if boxid1[index] != boxid2[index]:\n diffChars += 1\n if diffChars > 1: \n break\n else:\n result += boxid1[index]\n index... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check first 4 bytes of file to see if they are '0x7f''E''L''F' check to see if 32bit check to see if little endian return True if all conditions hold return False if any do not | def should_i_even_bother(file_bytes):
if file_bytes[E_MAG[0]:E_MAG[1]] == (str(0x7f) + "ELF"):
if file_bytes[E_BIT[0]] == 1:
if file_bytes[E_END[0]] == 1:
return True #this is a 32-bit little-endian ELF file
return False #this is not a 32-bit little-endian ELF file | [
"def check_32bit(pe): \n bits = True\n if not hex(pe.FILE_HEADER.Machine) == '0x14c':\n bits = False\n return bits",
"def autodetect_endian_and_sanity_check_su(file):\n pos = file.tell()\n if isinstance(file, io.BytesIO):\n file.seek(0, 2)\n size = file.tell()\n file.see... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It does not check if the user is validated so we suposse that we already did that step. Creates (in case it does not exist) a new user by using google login. | def create_google_user(self, payload, user_data):
if not User.objects.filter(email=payload['email']).exists():
u = User()
u.generate_token()
u.email = payload['email']
u.name = payload['given_name'] or ''
u.surname = payload['family_name'] or ''
... | [
"def create_user(self, request):\n g_user = endpoints.get_current_user()\n if not g_user:\n raise endpoints.UnauthorizedException('Authorization required')\n if User.query(User.name == request.username).get():\n raise endpoints.ConflictException(\n \"A User ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates if the request actually comes from Google. | def google_validate(self, token):
try:
payload = client.verify_id_token(token, GOOGLE_USER_ID)
if payload['iss'] not in ['accounts.google.com', 'https://accounts.google.com'] or payload['aud'] != GOOGLE_USER_ID:
return False
else:
return payloa... | [
"def bad_url_check_account(self, google_ads_account_id):\n pass",
"def validate_response(self, url, response): \n\n\t\tif response['status'] not in [self.RESPONSE_STATUS_OK, self.RESPONSE_STATUS_ZERO_RESULTS]:\n\t\t\terror_detail = ('Request to URL %s failed with response code: %s' %(url, response['status']))\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds a pipeline from a string list of augmentations. | def build_augmentation_pipeline(aug_list):
AUGMENTATIONS = {
'leadlag': LeadLag(),
'penoff': PenOff(),
'addtime': AddTime(),
'cumsum': CumulativeSum(),
'basepoint': Basepoint()
}
pipeline = Pipeline([
(tfm_str, AUGMENTATIONS[tfm_str]) for tfm_str in aug_list
... | [
"def _make_augmentation_pipeline(augmentation_list):\n # Dictionary of augmentations\n AUGMENTATIONS = {\n \"leadlag\": _LeadLag(),\n \"ir\": _InvisibilityReset(),\n \"addtime\": _AddTime(),\n \"cumsum\": _CumulativeSum(),\n \"basepoint\": _BasePoint(),\n }\n\n # Asser... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies augmentations to the data if specified in list format with keys corresponding to AUGMENTATIONS.keys(). This will build a sklearn pipeline from the augmentation list, as such, each augmentation must operate a fit and a transform method. | def apply_augmentation_list(data, aug_list):
pipeline = build_augmentation_pipeline(aug_list)
# Transform
data_tfmd = pipeline.fit_transform(data)
return data_tfmd | [
"def _make_augmentation_pipeline(augmentation_list):\n # Dictionary of augmentations\n AUGMENTATIONS = {\n \"leadlag\": _LeadLag(),\n \"ir\": _InvisibilityReset(),\n \"addtime\": _AddTime(),\n \"cumsum\": _CumulativeSum(),\n \"basepoint\": _BasePoint(),\n }\n\n # Asser... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the sum for all inputs multiplied by its weight | def weighted_sum(self, inputs):
weighted_sum = 0
for i in range(self.num_inputs):
weighted_sum += self.weights[i]*inputs[i]
return weighted_sum | [
"def sum(self, inputs):\r\n return sum(val * self.weights[i] for i, val in enumerate(inputs))",
"def calculate_weighted_sum(\n inputs: np.ndarray, weights: np.ndarray, bias: np.ndarray\n) -> np.ndarray:\n return np.sum(inputs * weights) + bias",
"def weighted_sum(W, X):\n\n if len(W) != len(X):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a classification threshold of either 0 or 1 we use 0.5 as a threshold here for ease of understanding | def threshold(self, value):
threshold = 0.5
if value >= threshold:
return 1
else:
return 0 | [
"def adjusted_classes(pred_prob, threshold):\n return [1 if y >= threshold else 0 for y in pred_prob]",
"def _threshold_for_binary_predict(estimator):\n if hasattr(estimator, \"decision_function\") and is_classifier(estimator):\n return 0.0\n else:\n # predict_proba threshold\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if link between nodes u and v is eligible Eligibility allows us to ignore some nodes/links for link prediction. | def eligible(self, u, v):
return self.eligible_node(u) and self.eligible_node(v) and u != v | [
"def eligible_node(self, v):\n if self.eligible_attr is None:\n return True\n return self.G.nodes[v][self.eligible_attr]",
"def can_reach_support(self, target):\n return self.territory.adjacent_to(target) and \\\n target.accessible_by_piece_type(self)",
"def availab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if node v is eligible Eligibility allows us to ignore some nodes/links for link prediction. | def eligible_node(self, v):
if self.eligible_attr is None:
return True
return self.G.nodes[v][self.eligible_attr] | [
"def eligible(self, u, v):\n return self.eligible_node(u) and self.eligible_node(v) and u != v",
"def _eligible(self, name):\n\n # includes and excludes only are allowed at the top level of vartrees\n if \".\" in name:\n name = name.split(\".\")[0]\n\n if name in self._mm_cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get list of eligible nodes Eligibility allows us to ignore some nodes/links for link prediction. | def eligible_nodes(self):
return [v for v in self.G if self.eligible_node(v)] | [
"def eligible_edges(self):\n if len(self.edges) == 4:\n return [self.edges[0], self.edges[2]]\n return []",
"def eligible_edges(self):\n return self.edges",
"def eligible(self):\n return self._eligible",
"def available_to_link():\n ok = lambda i: len(G[nodes[i]]) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of available parsing modules | def list_parsers(self, *args):
print('==== Available parsing modules: ====\n')
for parser in sorted(self.parse_modules):
print(self.parse_modules[parser].name.ljust(16) + \
': ' + self.parse_modules[parser].desc)
sys.exit(0) | [
"def parse_and_return_modules(self):\n statements.add_validation_fun('reference_3', ['deviation'], self._add_i_deviation)\n statements.add_validation_fun('reference_3', ['deviation'], self._add_d_info)\n statements.add_validation_fun('reference_3', ['deviate'], self._remove_d_info)\n\n #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |