query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Function for loading the features and labels associated with the training dataset. | def _loadTrain(self, features, labels):
self.trainX_, self.trainY_, self.trainLabel_ = self.__load(features, labels) | [
"def load_features_and_labels(features_dir, labels_dir):\n # load labels\n labels = pd.read_csv(glob.glob('{}/*.csv'.format(labels_dir))[0])\n labels = labels.sort_values(by='bookingID')\n\n # load features\n features = load_features(features_dir)\n\n return features, labels",
"def load_features... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for loading the features and labels associated with the testing dataset. | def _loadTest(self, features, labels):
self.testX_, self.testY_, self.testLabel_ = self.__load(features, labels) | [
"def load_features_and_labels(train_partition, test_partition, training_feature_file,\n test_feature_file, preprocessor='tokenized', vectorizer=None, \n feature_outfile_name=None):\n train_labels_path = \"{script_dir}/../data/labels/{train}/labels.{train}.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for loading the features and labels associated with the validation dataset. | def _loadValid(self, features, labels):
self.validX_, self.validY_, self.validLabel_ = self.__load(features, labels) | [
"def load_features_and_labels(train_partition, test_partition, training_feature_file,\n test_feature_file, preprocessor='tokenized', vectorizer=None, \n feature_outfile_name=None):\n train_labels_path = \"{script_dir}/../data/labels/{train}/labels.{train}.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles displaying recipe categories | def categories():
return render_template('categories.html', recipe_categories=USERS[session['username']].recipe_categories) | [
"def render_categories(self, categories):",
"def category(request):\n\n return render(request, \"core/category_list.html\", {\n \"category_list\": Category.objects.all()\n })",
"def our_categories(request):\n\n # Render the HTML template categories.html with the data in the context variable.\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inserts a book into the book table | def insert_book(self, title, author, year, isbn):
self.cursor.execute("INSERT INTO Book VALUES(NULL, ?, ?, ?, ?)",
(title, author, year, isbn))
self.connection.commit() | [
"def insert_book(title, author, year, isbn):\n connection = sqlite3.connect(\"books.db\")\n cursor = connection.cursor()\n cursor.execute(\"INSERT INTO Book VALUES(NULL, ?, ?, ?, ?)\", (title, author, year, isbn))\n connection.commit()\n connection.close()",
"def insert_books():\n for _, row in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates a book from the book database | def update(self, id, title, author, year, isbn):
self.cursor.execute("UPDATE Book SET Title = ?, Author = ?, Year = ?, \
ISBN = ? WHERE Id = ?",
(title, author, year, isbn, id))
self.connection.commit() | [
"def updateBook():\n id = request.form.get(\"id\")\n addBookForm = AddEditBookForm(request.form)\n newISBN = addBookForm.book_ISBN.data\n newTitle = addBookForm.book_title.data\n newAuthor = addBookForm.book_author.data\n requests.put(API_IP + \"book/\"+id,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a UI from a SQL table and return a ``Panel`` | def create_tables(name, role, doc, options, connection):
if role == 'data_samples':
print(f'create data_samples={name}')
data_table = TabsDynamicData(doc, options, connection, name, role, creator_fn=process_data_samples)
panel = Panel(child=data_table.get_ui(), title=name, name=f'data_sample... | [
"def makeTableWidget(self):\n from collective.table.browser.table import TableWidget\n context = self.portal.table\n widget = TableWidget(context, None)\n widget.fieldName = 'table'\n return widget",
"def create_layout(datatable, table_df):\n return html.Div(\n id='dat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the next update from the queue. If no update is found, block the process until one is received. If a stop signal is sent, try to gracefully stop the thread. | def __receive_next_update(self) -> telegram.Update:
# Pop data from the queue
try:
data = self.queue.get(timeout=self.cfg.telegram["conversation_timeout"])
except queuem.Empty:
# If the conversation times out, gracefully stop the thread
self.__graceful_stop(St... | [
"def receive_next_update(self) -> telegram.Update:\n # Pop data from the queue\n data = \"\"\n try:\n data = self.queue.get(timeout=self.cfg.telegram[\"conversation_timeout\"])\n except queuem.Empty:\n # If the conversation times out, gracefully stop the thread\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the next update from the queue. If no update is found, block the process until one is received. If a stop signal is sent, try to gracefully stop the thread. | def receive_next_update(self) -> telegram.Update:
# Pop data from the queue
data = ""
try:
data = self.queue.get(timeout=self.cfg.telegram["conversation_timeout"])
except queuem.Empty:
# If the conversation times out, gracefully stop the thread
self.__... | [
"def __receive_next_update(self) -> telegram.Update:\n # Pop data from the queue\n try:\n data = self.queue.get(timeout=self.cfg.telegram[\"conversation_timeout\"])\n except queuem.Empty:\n # If the conversation times out, gracefully stop the thread\n self.__gra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Continue getting updates until the regex finds a match in a message, then return the first capture group. | def __wait_for_regex(self, regex: str, cancellable: bool = False) -> Union[str, CancelSignal]:
log.debug("Waiting for a regex...")
while True:
# Get the next update
update = self.__receive_next_update()
# If a CancelSignal is received...
if isinstance(upda... | [
"def _recvregex(self, regex, exact=False, group=None, **kwargs):\n\n if isinstance(regex, (str, unicode)):\n regex = re.compile(regex)\n\n if exact:\n pred = regex.match\n else:\n pred = regex.search\n\n data = self.recvpred(pred, **kwargs)\n if group is None:\n return dat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Continue getting updates until a precheckoutquery is received. The payload is checked by the core before forwarding the message. | def __wait_for_precheckoutquery(self,
cancellable: bool = False) -> Union[telegram.PreCheckoutQuery, CancelSignal]:
log.debug("Waiting for a PreCheckoutQuery...")
while True:
# Get the next update
update = self.__receive_next_update()
... | [
"async def answer_pre_checkout_query(\n self,\n pre_checkout_query_id: int,\n error_message: str,\n *,\n request_id: str = None,\n request_timeout: int = None,\n skip_validation: bool = False\n ) -> Ok:\n _constructor = AnswerPre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Continue getting updates until a successfulpayment is received. | def __wait_for_successfulpayment(self,
cancellable: bool = False) -> Union[telegram.SuccessfulPayment, CancelSignal]:
log.debug("Waiting for a SuccessfulPayment...")
while True:
# Get the next update
update = self.__receive_next_update()
... | [
"def awaiting_payment(self):",
"def do_payment(self, *args):\n print('do_payment function called')\n\n # scans a qr-code and returns either the qr-code or False\n qrcode = qr.QrCode.scan()\n\n # takes the qr-code and checks if a lightning invoice is in it\n # if this is the case... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Continue getting updates until a photo is received, then return it. | def __wait_for_photo(self, cancellable: bool = False) -> Union[List[telegram.PhotoSize], CancelSignal]:
log.debug("Waiting for a photo...")
while True:
# Get the next update
update = self.__receive_next_update()
# If a CancelSignal is received...
if isinst... | [
"def photo_info(self) -> List[protocol.PhotoInfo]:\n if not self._photo_info:\n self.logger.debug(\"Photo list was empty. Lazy-loading photo list now.\")\n result = self.load_photo_info()\n if isinstance(result, concurrent.futures.Future):\n result.result()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Continue getting updates until an inline keyboard callback is received, then return it. | def __wait_for_inlinekeyboard_callback(self, cancellable: bool = False) \
-> Union[telegram.CallbackQuery, CancelSignal]:
log.debug("Waiting for a CallbackQuery...")
while True:
# Get the next update
update = self.__receive_next_update()
# If a CancelSigna... | [
"def keyboard_input(self) -> None:\n with Listener(on_press=self.press, on_release=self.release) as listener: # set keys to be read immediately\n listener.join()",
"def get_input(self, timeout):\n while True:\n if self.led_callback != None:\n self.led_callback.u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select an user from the ones in the database. | def __user_select(self) -> Union[db.User, CancelSignal]:
log.debug("Waiting for a user selection...")
# Find all the users in the database
users = self.session.query(db.User).order_by(db.User.user_id).all()
# Create a list containing all the keyboard button strings
keyboard_butto... | [
"def select_user(user_id):\n return session.query(User).filter(User.id == user_id).first()",
"def get_user(identifier, value):\n user = get_db().execute(\n 'SELECT * FROM user WHERE {} = ?'.format(identifier),\n (value,)\n ).fetchone()\n\n return user",
"def select_user(self):\n\t\tsel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
User menu to order products from the shop. | def __order_menu(self):
log.debug("Displaying __order_menu")
# Get the products list from the db
products = self.session.query(db.Product).filter_by(deleted=False).all()
# Create a dict to be used as 'cart'
# The key is the message id of the product list
cart: Dict[List[d... | [
"def __products_menu(self):\n log.debug(\"Displaying __products_menu\")\n # Get the products list from the db\n products = self.session.query(db.Product).filter_by(deleted=False).all()\n # Create a list of product names\n product_names = [product.name for product in products]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display the status of the sent orders. | def __order_status(self):
log.debug("Displaying __order_status")
# Find the latest orders
orders = self.session.query(db.Order) \
.filter(db.Order.user == self.user) \
.order_by(db.Order.creation_date.desc()) \
.limit(20) \
.all()
# Ensure ... | [
"def show_orders(self):\n\n data = cur.execute(\"\"\"SELECT * FROM orders\"\"\").fetchall()\n print(tabulate(data, headers=[\"Order ID\", \"Status\", \"Customer\", \"Address\", \"Delivery Method\"]))",
"def order_update_status():\n result = order_obj.order_update_status(request.forms) \n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send information about the bot. | def __bot_info(self):
log.debug("Displaying __bot_info")
self.bot.send_message(self.chat.id, self.loc.get("bot_info")) | [
"async def _botinfo(self, ctx):\n embed = discord.Embed(title=\"Bot Information\", color=discord.Color.green(),\n description=\"\")\n embed.add_field(name=\"Creation Date\",\n value=\"%s\" % discord.utils.snowflake_time(ctx.bot.user.id).strftime(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display the admin menu to select a product to edit. | def __products_menu(self):
log.debug("Displaying __products_menu")
# Get the products list from the db
products = self.session.query(db.Product).filter_by(deleted=False).all()
# Create a list of product names
product_names = [product.name for product in products]
# Insert... | [
"def edit_product(request, product_id):\n # only allow super user access\n if not request.user.is_superuser:\n messages.error(\n request,\n \"You must be logged in as KOR admin to do this\"\n )\n return redirect(reverse('home'))\n\n product = get_object_or_404(Pro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display the latest transactions, in pages. | def __transaction_pages(self):
log.debug("Displaying __transaction_pages")
# Page number
page = 0
# Create and send a placeholder message to be populated
message = self.bot.send_message(self.chat.id, self.loc.get("loading_transactions"))
# Loop used to move between pages
... | [
"def show_transactions():\n\n if not g.user:\n flash(\"Access unauthorized.\", \"danger\")\n return redirect(\"/\")\n\n user = g.user\n all_transactions = Transaction.query.filter(Transaction.user_id == user.id).all()\n return render_template('transactions_list.html', all_transactions=all_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a .csv file containing the list of all transactions. | def __transactions_file(self):
log.debug("Generating __transaction_file")
# Retrieve all the transactions
transactions = self.session.query(db.Transaction).order_by(db.Transaction.transaction_id.asc()).all()
# Create the file if it doesn't exists
try:
with open(f"tran... | [
"def makeCSV(self):\r\n with open(\"upload.csv\", \"w\") as f:\r\n f.write(self.makeString() + \"\\n\" )\r\n for student in self.studentList:\r\n f.write(student.makeString() + \"\\n\")",
"def get_transactions_csv(self, include_investment=False):\n\n # Specifying... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add an administrator to the bot. | def __add_admin(self):
log.debug("Displaying __add_admin")
# Let the admin select an administrator to promote
user = self.__user_select()
# Allow the cancellation of the operation
if isinstance(user, CancelSignal):
return
# Check if the user is already an admi... | [
"async def add_admin(ctx: dc.Context):\n if not ctx.message.mentions:\n await ctx.message.channel.send(\n embed=dc.ErrorEmbed(\n \"Argument Error\",\n \"No mentions found.\",\n \"Syntax: [add-admin] @user_1 @user_2 .. @user_n\",\n ctx.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a frame from the camera and a destination, figure out which direction to take next | def get_next_direction(current_frame, scanner, code):
# ### thresholding. susceptible to glare, solve with masking tape?
thresh = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY)
# success, thresh = cv2.threshold(thresh, BW_THRESHOLD, 255, cv2.THRESH_BINARY)
# if not success:
# print "Could not threshold fra... | [
"def get_direction(self, destination:int):\n if int(destination) - int(self.position) > 0 :\n return \"forward\"\n if int(destination) - int(self.position) < 0 :\n return \"reverse\"\n return \"stop\"",
"def choose_direction(self):\n\n # for getting the neighbours... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a frame from the camera, figure out the line error | def get_line_error(im):
### Crop the picture
height = len(im)
width = len(im[0])
im = im[height/CROP_RATIO:-height/CROP_RATIO, width/CROP_RATIO:-width/CROP_RATIO]
### thresholding. susceptible to glare, solve with masking tape?
thresh = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
success, thresh = cv2.thresho... | [
"def error_check(frame_tp):\n deriv_frame_tp = np.diff(frame_tp)\n error_len_th = np.mean(deriv_frame_tp)+np.std(deriv_frame_tp)*6\n\n error_frames = np.abs(deriv_frame_tp)>error_len_th\n if np.any(error_frames):\n print(\"Error in timepoints detected in frames\", np.where(error_frames)[0],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a frame from the camera, figure out the desired speed and current line error | def compute_speed_and_line_error(current_frame, scanner, code):
next_direction = get_next_direction(current_frame, scanner, code)
if next_direction == 'STOP':
return STOP
line_error = get_line_error(current_frame)
if line_error is None:
return None
return (2, line_error) | [
"def calc_acc_frame(velocity, step_size, frame, vel_start_frame):\n #The offset required due to the velocities starting a vel_start_frame\n acc_offset = frame - vel_start_frame + 1\n if ((acc_offset) < step_size):\n raise IndexError(\"Acceleration cannot be calculated for this frame\")\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a Student instance with given name and the number of scores to associate with the given Student. | def __init__(self, name: str, number: float):
self._name = name
self._scores = [0] * number | [
"def __init__(self, name, surname):\n\t\t\n\t\tself.grades = {}\n\t\tself.attendance = 0\n\t\t\n\t\tif not (isinstance(name, str) and isinstance(surname, str)):\n\t\t\tname, surname = \"None\", \"None\"\n\t\tself.name, self.surname = name, surname",
"def __init__(self, name, skill):\n \n super(Stude... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the average score associated with this Student. | def get_average(self) -> float:
return sum(self._scores) / len(self._scores) | [
"def avg_score(self):\r\n return np.average(self.scores)",
"def getAverage(self):\n return sum(self.scores) / len(self.scores)",
"def average_scorecons(self):\n return statistics.mean(self.scores)",
"def get_avg_score(self):\n return self.evaluations.aggregate(Avg('score'))",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor creates a number with the given numerator and denominator and reduces it to lowest terms. | def __init__(self, numerator: int, denominator: int):
self._numerator = numerator
self._denominator = denominator
self._reduce() | [
"def __init__(self, numerator, denominator=1):\n gcd1 = math.gcd(numerator, denominator)\n\n if denominator < 0:\n self.numerator = -(int(numerator/gcd1))\n self.denominator = abs(int(denominator/gcd1))\n elif denominator == 0:\n self.numerator = 1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the current pin. | def get_pin(self) -> str:
return self._pin | [
"def getPin(self):\n\t\treturn self.pin",
"def getPin(self):\r\n return self.pin",
"def pin(self):\n return self.__pin",
"def pin(self):\n return self._pin_num",
"def pin(self) -> int:",
"def pin_name(self):\n return self.__pinName",
"async def get_pin_thread(self) -> int:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the amount is valid, subtract it from the balance and returns None; otherwise, returns an error message. | def withdraw(self, amount):
if amount < 0:
return "Amount must be >= 0"
elif self._balance < amount:
return "Insufficient funds"
else:
self._balance -= amount
return None | [
"def test_fail_balance_negative(self):\n self.bundle.transactions[3].value -= 1\n\n validator = BundleValidator(self.bundle)\n\n self.assertFalse(validator.is_valid())\n\n self.assertListEqual(\n validator.errors,\n\n [\n 'Bundle has invalid balance (expected 0, actual -1).',\n ],\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes, deposits, and returns the interest. | def compute_interest(self) -> float:
interest = self._balance * SavingsAccount.RATE
self.deposit(interest)
return interest | [
"def computeInterest(self):\r\n interest = self.balance * SavingsAccount.RATE\r\n self.deposit(interest)\r\n return interest",
"def computeInterest(self):\n\t\tinterest = self.balance * savingAccount.RATE\n\t\tself.deposit(interest)\n\t\treturn interest",
"def computeInterest(self):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This request returns all the colors in an image as RGB values. | def color(self, image):
response = self._send_request("color", files=dict(image=image))
return response[self._layer]['colors'] | [
"def get_colors(img):\n return [ c[1] for c in img.getcolors(img.size[0]*img.size[1]) ]",
"def get_colors(self, url):\n fd = urlopen(url)\n f = io.BytesIO(fd.read())\n im = Image.open(f)\n palette = im.quantize(colors=len(self.lights)).getpalette()\n return self.extract_colors(palette, len(self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create instances of each available layer. | def __init__(self):
for layer in self._layer_class_map:
setattr(self, layer, self._layer_class_map[layer]()) | [
"def init_layers(self):\n\n # get caching layers activated\n caching_layers = G3WCachingLayer.objects.all()\n for caching_layer in caching_layers:\n self.add_layer(str(caching_layer), caching_layer)",
"def _create_layers(self):\n assert not self._locked, \"ObservationEncoder... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set value to the tensor. | def set_value(self, indices, val):
assert len(indices) == 3, indices
if self.model_tensor is None:
raise ValueError("Please set the tensor")
self.model_tensor[indices[0], indices[1], indices[2]] = val
return val | [
"def set_node_value(node: Node, value: np.ndarray):\n if node.type != 'Const':\n raise Exception('Can\\'t set value for non-constant node {}'.format(node.name))\n data_type = np.float32\n if node.out_port(0).is_data_type_defined():\n data_type = node.out_port(0).get_data_type()\n node.out_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a list of indices (with possible repeats), run optimization and return stats. | def best_value_many_indices(self, indices_list, **kwargs):
indices_list = [tuple(x) for x in indices_list]
stats = {indices: [] for indices in set(indices_list)}
for indices in indices_list:
stats[indices].append(self.best_value_indices(indices=indices, **kwargs))
... | [
"def scipy_optimize_from_indices(\n muygps: MuyGPS,\n batch_indices: np.ndarray,\n batch_nn_indices: np.ndarray,\n test: np.ndarray,\n train: np.ndarray,\n train_targets: np.ndarray,\n loss_method: str = \"mse\",\n verbose: bool = False,\n) -> np.ndarray:\n crosswise_dists = crosswise_dis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute an online update given a precomputed minibatch of data, and a model tensor. | def compute_online_update(rating_value, mb_np_orig,
model_tensor_orig,
idx_set,
users_get_value=None,
n_repeats=1,
hotfix_update_hypers=None,
plot_charts=Fals... | [
"def create_client_update_fn():\n\n @tf.function\n def client_update(model,\n dataset,\n initial_weights,\n client_optimizer,\n client_weight_fn=None):\n \"\"\"Updates client model.\n\n Args:\n model: A `tff.learning.Model`.\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Seeds the given output Image with random pixels from the source Image. | def __seed_output_image(self, src_image: Image, out_image: Image) -> None:
src_pixel_array = src_image[:, :].reshape((src_image.area, 3))
src_index_array = np.random.choice(np.arange(src_image.area), out_image.area)
out_image[:, :] = np.take(src_pixel_array, src_index_array, axis=0).reshape(out_... | [
"def random_image(x, y, out):\n\n pixels = []\n for pixel in range(0, x*y):\n pixels.append(random_pixel())\n\n new_image(x, y, out, pixels)",
"def randomize_pixels(image):\n shape_ = image.size()\n image_flat = image.view(-1, image.size(-1))\n shuffled_image = shuffle(image_flat)\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the given pixel in the specified layer of the output Pyramid using the colour of a pixel from the source Pyramid with the closest neighbourhood to the output pixel. | def __render_output_pixel(self, src_pyramid: Pyramid, out_pyramid: Pyramid, level: int, out_point: Point) -> None:
if level == self.__levels - 1:
distances = self.__make_distance_matrix(src_pyramid[level], out_pyramid[level], self.__neighbourhood_padding[level], out_point, True)
else:
... | [
"def render_pixel(self, x, y, colour):\n # can't use the below as too slow\n self.renderer.fill((5 * x, 5 * y, 4, 4), sdl2.ext.Color(*colour))",
"def render(self, config, input_rgba, coord):\n stack_rgba = [numpy.zeros(chan.shape, chan.dtype) for chan in input_rgba]\n \n for lay... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a matrix containing the weighted squared difference of the pixel values between each window in the source Image and the window extracted from the output Image at the specified Point with the given padding. | def __make_distance_matrix(self, src_image: Image, out_image: Image, padding: int, out_point: Point, causal: bool) -> np.ndarray:
# Extract the reference window and for the neighbourhood matching.
out_window = out_image.extract(out_point, padding, 'wrap')
out_filled = out_image.filled(out_point,... | [
"def padding(self):\n pad = self.ntiles - self.windowsize\n return (int((pad - 1)/2.), int((pad + 1)/2.))",
"def weighted_sum_extraction(cutout, trace, psf, ron = 12, gain = 1.2):\n ###NEW VERSION BELOW\n # width = len(cutout[0]) #we have square cutout\n # #buffer area on either ends of the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the mouse_over variable and returns the button's action value when clicked. | def update(self, mouse_pos, mouse_up):
if self.rect.collidepoint(mouse_pos):
self.mouse_over = True
if mouse_up:
return self.action
else:
self.mouse_over = False | [
"def button_hovered(self):\n\n mouse_pos = self.mouse_pos()\n return self.option_buttons.get_clicked(mouse_pos)",
"def update_button_hover_status(self):\n for button in self.playing_buttons:\n button.update(self.mousePos)",
"def mouse_press(self, btn, x, y, modifiers):",
"def h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws element onto a surface | def draw(self, surface):
surface.blit(self.image, self.rect) | [
"def draw(self,surface):\n if self.form==0:\n pygame.draw.circle(surface,self.color,self.position,self.radius,self.width)\n if self.form==1:\n pygame.draw.rect(surface,self.color,list(self.position)+list(self.size),self.width)\n if self.form==2:\n pygame.draw.li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles game loop until an action is return by a button in the buttons sprite renderer. | def game_loop(screen, buttons):
while True:
mouse_up = False
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
mouse_up = True
screen.fill(BLACK)
for button in buttons:
ui_... | [
"def _game_loop(self):\n self._keyboard_pressing()\n self._ship_action()\n self._torpedos_action()\n self._asteroids_action()\n self._check_lost_game()\n self._check_won_game()\n self._check_quit_game()",
"def callback_game_loop(self) -> None:\n self._goal_g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
handle a keypress space > take a screen shot tab > start/stop recording a screencast escape > quit | def onKeypress(self, keycode):
# space
if keycode == 32:
self._captureManager.writeImage('screenshot.png')
# tab
elif keycode == 9:
if not self._captureManager.isWritingVideo:
self._captureManager.startWritingVideo('screencast.avi')
... | [
"def onKeypress(self,keycode):\n if keycode==32:#space\n self._captureManager.writeImage('screennshot.png')\n elif keycode==9:#tab\n if not self._captureManager.isWritingVideo:\n self._captureManager.startWritingVideo('scrrencast.avi')\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert octal string to binary string. | def oct2bin(x):
return bin(int(x, 8))[2:] | [
"def test_binary_string_to_octal_string():\n obj = pmisc.binary_string_to_octal_string\n if sys.hexversion < 0x03000000:\n ref = (\n \"\\\\1\\\\0\\\\2\\\\0\\\\3\\\\0\\\\4\\\\0\\\\5\\\\0\\\\6\\\\0\\\\a\\\\0\"\n \"\\\\b\\\\0\\\\t\\\\0\\\\n\\\\0\\\\v\\\\0\\\\f\\\\0\\\\r\\\\0\\\\16\\\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert octal string to decimal number. | def oct2dec(x):
return int(x, 8) | [
"def octal_transform(self,string):\n octa_rx = r'(((?<=[+/%*^])|(?<=\\s)|(?<=^))[-]?0+[1-9][0-9]*)'\n while re.search(octa_rx,string):\n inst = next(re.finditer(octa_rx,string))\n start = inst.start()\n end = inst.end()\n number = inst.group()\n c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert octal string to hexadecimal string. | def oct2hex(x):
return hex(int(x, 8))[2:] | [
"def int2hex(n: int) -> str:",
"def ascii_to_hex(input_string: str) -> str:\n return input_string.encode().hex()",
"def hexify(s):\n return (\"%02x\"*len(s)) % tuple(map(ord, s))",
"def print_as_hex(s):\n print(\":\".join(\"{0:x}\".format(ord(c)) for c in s))",
"def octal(self):\r\n return \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert hexadecimal string to octal string. | def hex2oct(x):
return oct(int(x, 16))[_oct_index:] | [
"def oct2hex(x):\n return hex(int(x, 8))[2:]",
"def octal_transform(self,string):\n octa_rx = r'(((?<=[+/%*^])|(?<=\\s)|(?<=^))[-]?0+[1-9][0-9]*)'\n while re.search(octa_rx,string):\n inst = next(re.finditer(octa_rx,string))\n start = inst.start()\n end = inst.end... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the first identifier for the next month. | def _next_yymm_id(self, identifier: Identifier) -> Optional[Identifier]:
next_yymm_id = None
if identifier.year is not None and \
identifier.month is not None:
new_year = identifier.year
new_month = identifier.month + 1
new_num = 1
if new_m... | [
"def _get_nextMonth(self):\n return self + (self.monthDays - self.day + 1)",
"def next_month(self):\n year = self.year\n month = self.month\n if month == 12:\n year += 1\n month = 1\n else:\n month += 1\n return AgiloCalendar(month=month, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get previous consecutive Identifier relative to provided Identifier. | def _previous_id(self, identifier: Identifier) -> Optional['Identifier']:
previous_id = None
if identifier.year is not None and \
identifier.month is not None and \
identifier.num is not None:
new_year = identifier.year
new_month = identifier.month... | [
"def getPreviousElement(self,currentId):\n\tids = self.getObjectIds()\n\tpreviousId = None\n\tfor id in ids:\n\t if id == currentId:\n\t\treturn previousId\n\t else:\n\t\tpreviousId = id\n\treturn None",
"def previous(self):\n if self.letter == ALPHABET[0]:\n return None\n i = ALPHA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse arXiv .abs file. | def parse_abs_file(filename: str) -> DocMetadata:
try:
with open(filename, mode='r', encoding='latin-1') as absf:
raw = absf.read()
except FileNotFoundError:
raise AbsNotFoundException
except UnicodeDecodeError as e:
# TODO: log this
... | [
"def load(filename):\n o = open(filename)\n s = o.read()\n a = ArffFile.parse(s)\n o.close()\n return a",
"def parser(path):\n\t\n\tdata = Arff()\n\tdata.read_arff(path)\n\t\n\treturn data",
"def read_abinit(filename='abinit.in'):\n\n from ase import Atoms, units\n\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a specific version of a paper's abstract metadata. | def _get_version(self, identifier: Identifier,
version: Optional[int] = None) -> DocMetadata:
parent_path = self._get_parent_path(identifier=identifier,
version=version)
path = os.path.join(parent_path,
(f'{iden... | [
"def get_abstract(paper):\n link = paper[\"link\"]\n try:\n abstract = (\n BeautifulSoup(requests.get(link).text, features=\"html.parser\")\n .find(\"div\", {\"id\": \"Abs1-content\"})\n .text\n )\n paper[\"abstract\"] = abstract\n except Exception as E... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the absolute parent path of the provided identifier. | def _get_parent_path(self, identifier: Identifier,
version: Optional[int] = None) -> str:
parent_path = os.path.join(
(self.latest_versions_path if not version
else self.original_versions_path),
('arxiv' if not identifier.is_old_id or identifier.arch... | [
"def get_parent_url(self, identifier, node_details=None):\n return structures_module.nodes.get_parent_url(self.khoros_object, identifier, node_details)",
"def get_parent(file_path: str):\n return str(Path(file_path).parent)",
"def get_parent_path(self):\n return os.path.abspath(os.path.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the version entries from the arXiv .abs file. | def _parse_version_entries(arxiv_id: str, version_entry_list: List) \
-> Tuple[int, List[VersionEntry], str]:
version_count = 0
version_entries = list()
for parsed_version_entry in version_entry_list:
version_count += 1
date_match = RE_DATE_COMPONENTS.match(pa... | [
"def parse_abs_file(filename: str) -> DocMetadata:\n try:\n with open(filename, mode='r', encoding='latin-1') as absf:\n raw = absf.read()\n except FileNotFoundError:\n raise AbsNotFoundException\n except UnicodeDecodeError as e:\n # TODO: log thi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get list of dissemination formats. | def get_dissemination_formats(docmeta: DocMetadata,
format_pref: Optional[str] = None,
add_sciencewise: bool = False) -> List:
return current_session().get_dissemination_formats(docmeta,
format_pref,
... | [
"def formats(self):\n logger.debug(\"Get formats\")\n return self._raw_api.formats.get()",
"def get_download_formats(self):\r\n return self.get_all_formats()",
"def list_formats(cls):\n\n return [x.name for x in pkg_resources.iter_entry_points('iotile_analytics.save_format')]",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the closest mesh triangles ids from a transomr position | def closestTriangleToTransform(transform, meshName):
faceVertices, points = meshData.getMeshData(meshName)
vertexFaces = meshData.getMeshVertexFaces(faceVertices)
point = np.array(cmds.xform(transform, q=1, ws=1, t=1), dtype=np.double)
return meshData.getClosestTriangle(point, points, vertexFaces, faceV... | [
"def closest_points_on_mesh(self, points):\n dist, ind_mesh = trimesh.proximity.ProximityQuery(self.mesh).vertex(points)\n self.log.debug('Distance to mesh {}'.format(dist))\n ind_coord = self.trimesh_to_coord[ind_mesh]\n assert (self.coords[ind_coord] == self.mesh.vertices[ind_mesh]).al... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the skinweights form the skincluster, create a skintransforms node and connect it to drive the transforms | def createSkinTansformNode(skinCluster, transforms):
node = cmds.createNode('skinTransforms')
influences = cmds.listConnections('{}.matrix'.format(skinCluster), s=1, d=0)
for i, jnt in enumerate(influences):
cmds.connectAttr('{}.worldMatrix[0]'.format(jnt), '{}.matrix[{}]'.format(node,i))
m ... | [
"def get_skin_data(skin_cluster):\n # Create skin cluster function set\n skin_cluster_node = to_m_object(skin_cluster)\n skin_cluster_fn = OpenMayaAnim.MFnSkinCluster(skin_cluster_node)\n \n # Get MPlugs for weights\n weight_list_plug = skin_cluster_fn.findPlug(\"weightList\")\n weights_plug = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changes the value of var to value, in target card json target | def doEdit(var, value, target):
currentValue = target.get(var, "")
newValue = Simplifier.simplify(str(value).replace(f"{{{var}}}", str(currentValue)))
target[var] = newValue | [
"def set_value_directly(self, client, var_value):\n pass",
"def set_data_value(var, value):\n\n substitute(data, var, value)",
"def set_value(self, var_value):\n pass",
"def update_card(card, card_data):\n card.name = card_data[\"name\"]\n card.hero = card_data[\"playerClass\"]\n car... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a numeric PIN with length digits | def get_pin(length=6):
pin = str(random.sample(range(10 ** (length - 1), 10 ** length), 1)[0])
print("pin "+pin)
return pin | [
"def __generate_pin(cls) -> str:\n return str(randbelow(10 ** cls.PIN_DIGITS)).zfill(cls.PIN_DIGITS)",
"def randomPin(length):\n return ''.join(secrets.choice(string.digits) for i in range(length))",
"def _get_pin(self, length=5):\n return str(random.sample(range(10**(length-1), 10**length), 1)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fixture for DataFrame of ints which are constant per column | def int_frame_const_col():
df = DataFrame(
np.tile(np.arange(3, dtype="int64"), 6).reshape(6, -1) + 1,
columns=["A", "B", "C"],
)
return df | [
"def fixture_int_dataframe() -> pd.DataFrame:\n return pd.DataFrame({\"a\": [-1, 0, 1]})",
"def test_get_integer_dataframe():\n dfg = DataFrameGenerator()\n df = dfg.get_integer_dataframe(10, 5)\n assert df.shape == (10, 5), \"Wrong size dataframe generated\"\n assert list(df.columns) == [\"Integer... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logs a message, preserving the progress bar correct output format. | def log_message(self, message: str) -> None:
from tqdm import tqdm
tqdm.write(message, file=self.tqdm_kwargs.get("file", None)) | [
"def progress(message):\n\tprint_(message, 3, inline=True)",
"def log(self, msg):\n\n print(f'{self.prefix} - {msg}')",
"def log(self, level: int, message: str):\n\n log.log(level, message)\n\n if self.command:\n self.command.write(level, text=message)",
"def log_message(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encode the sequence as a list of floats using the provided vocab. | def encode_dna_as_floats(sequence: Iterable[str],
vocab: str = dc_constants.VOCAB,
offset: int = 0) -> Optional[Iterable[float]]:
ids = []
for base in sequence:
if base not in vocab:
return None
base_id = float(vocab.index(base) + offset)
ids.appe... | [
"def __data_to_vector(vocab_list, input_set):\n out = [0] * len(vocab_list)\n\n for word in input_set:\n if word in vocab_list:\n # Calculate word frequency\n out[vocab_list.index(word)] += 1\n return out",
"def savefloatlist(doc, pnode, name, value):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the sequence with GAP_OR_PAD and GAP_OR_PAD tokens removed. | def get_sequence_without_gaps_or_padding(sequence: str) -> str:
return sequence.replace(dc_constants.GAP_OR_PAD,
'').replace(dc_constants.GAP_OR_PAD, '') | [
"def ungapped(self):\n s = self.sequence\n for sGapChar in GAP_CHARACTERS:\n s = s.replace(sGapChar, '')\n return s",
"def cleangaps(self):\n \n \n if self.type == 'prot':\n gapchars = 'x-?'\n elif self.type == 'dna':\n gapchars = 'n-?' \n else:\n rais... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns start and end coordinates of label in the reference genome. Querying the reference genome for these coordinates will produce the label sequence. We need to add 1 to either start or end depending on the orientation of the reference. | def get_label_start_end(
label_base_positions: Iterable[int],
strand: bed_pb2.BedRecord.Strand) -> Tuple[Optional[int], Optional[int]]:
# Gap and padding tokens may have a position of -1, since they are not
# actually present in the reference. Remove all instances of -1, since we do
# not want to consider... | [
"def get_refseq_pos(self, preyid):\n\n prey_start_aa = string.atoi(self.ivv_to_refseq.val_accord_hd(\n preyid, \"Prey Region Start (AA)\"))\n prey_end_aa = string.atoi(self.ivv_to_refseq.val_accord_hd(\n preyid, \"Prey Region End (AA)\"))\n refseqid = self.get_refseq(preyi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets subreads/encoded field from example as a string. | def get_encoded_subreads_from_example(example):
return example.features.feature['subreads/encoded'].bytes_list.value[0] | [
"def get_field(self, bib_entry, field):\n output = bib_entry.fields[field] if field in bib_entry.fields else \"\"\n return self.strip_braces(output)",
"def _get_field_for_example(data, example_id, field):\n matches_id = data[\"cifar10_test_test_idx\"] == example_id\n return data[matches_id][field]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the subreads/shape field from example as a list of int64. | def get_subreads_shape_from_example(example):
assert len(example.features.feature['subreads/shape'].int64_list.value) == 3
return example.features.feature['subreads/shape'].int64_list.value[:] | [
"def get_int64_list(feature_name,\n example):\n return get_feature(feature_name, example).int64_list",
"def get_encoded_subreads_from_example(example):\n return example.features.feature['subreads/encoded'].bytes_list.value[0]",
"def __getAllFieldIDsFromFieldIDAndSizeAsIntList(self, fieldID, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the subreads/num_passes field from example as a list of int64. | def get_num_passes_from_example(example):
assert len(
example.features.feature['subreads/num_passes'].int64_list.value) == 1
return example.features.feature['subreads/num_passes'].int64_list.value[0] | [
"def getRefReads(self):# -> int\n return self.refReads",
"def list_of_runnums (ins, exp) :\n try : expruns = experiment_info.experiment_runs(ins, exp)\n #if exp == 'xcs83814' : return []\n except : return []\n\n return [int(rec['num']) for rec in expruns]\n #runs = experiment_info.experiment... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets label/encoded field from example as a string. | def get_encoded_label_from_example(example):
return example.features.feature['label/encoded'].bytes_list.value[0] | [
"def label_from_example(example):\n val = example.features.feature['label'].int64_list.value\n if val:\n return int(val[0])\n else:\n return None",
"def get_label_field(self):\n\n return self.label_field",
"def get_label(issue):\n\t# if exists then return else return empty string\n\tlabels = iss... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the label/shape field from example as a list of int64. | def get_label_shape_from_example(example):
assert len(example.features.feature['label/shape'].int64_list.value) == 1
return example.features.feature['label/shape'].int64_list.value[:] | [
"def get_int64_list(feature_name,\n example):\n return get_feature(feature_name, example).int64_list",
"def label_from_example(example):\n val = example.features.feature['label'].int64_list.value\n if val:\n return int(val[0])\n else:\n return None",
"def provide_label(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets deepconsensus_input/encoded field from example as a string. | def get_encoded_deepconsensus_input_from_example(example):
return example.features.feature[
'deepconsensus_input/encoded'].bytes_list.value[0] | [
"def get_encoded_label_from_example(example):\n return example.features.feature['label/encoded'].bytes_list.value[0]",
"def get_encoded_subreads_from_example(example):\n return example.features.feature['subreads/encoded'].bytes_list.value[0]",
"def deepconsensus_input_to_example(\n deepconsensus_input: dee... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns tf.Example created from the given DeepConsensusInput proto. | def deepconsensus_input_to_example(
deepconsensus_input: deepconsensus_pb2.DeepConsensusInput,
example_height: int,
inference: bool,
counters: Optional[Dict[str, metrics.Metrics.counter]] = None,
) -> Optional[tf.train.Example]:
if not deepconsensus_input.subreads:
if counters and counters['exampl... | [
"def get_encoded_deepconsensus_input_from_example(example):\n return example.features.feature[\n 'deepconsensus_input/encoded'].bytes_list.value[0]",
"def parse_preprocessed_example(example_proto):\n features = {\n 'spec': tf.VarLenFeature(dtype=tf.float32),\n 'spectrogram_hash': tf.FixedLenFeatu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add external padding to bases, PW, IP, and cigar. | def pad_bases_pw_ip_cigar(read: deepconsensus_pb2.Subread,
padded_len: int) -> None:
pad_amt = padded_len - len(read.bases)
if pad_amt > 0:
str_padding = dc_constants.GAP_OR_PAD * pad_amt
list_padding = [dc_constants.GAP_OR_PAD_INT] * pad_amt
read.bases = read.bases + str_paddi... | [
"def _add_padding(input_str):\r\n padding_len = AES.block_size - len(input_str) % AES.block_size\r\n return input_str + padding_len * chr(padding_len)",
"def add_padding(im, pad):\n\n return np.pad(im, pad_width=((pad, pad), (pad, pad), (0, 0)), mode='symmetric')",
"def _pad(payload):\n\t\tleng... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the max passes for bases/PW/IP. | def get_max_passes(example_height: int) -> int:
return (example_height - 5) // 4 | [
"def most_secure_password():\n passwords = []\n secure = {}\n query = Login.select(Login)\n for row in query:\n passwords.append(row.password)\n\n one_small_char_pattern = \"[a-z]+\" #1\n one_big_char_pattern = \"[A-Z]+\" #2\n one_digit_pattern = \"\\d+\" #1 \n eights_digits_pattern... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
How many IPs are allowed by the blacklist? >>> example_blacklist = RangeSet.from_file(data_path(__file__, 'example.txt')) >>> print(example_blacklist) 02, 48 >>> part_2(example_blacklist, total_ips_count=10) | def part_2(ranges: 'RangeSet', total_ips_count: int = 1 << 32) -> int:
allowed_count = total_ips_count - len(ranges)
print(f"part 2: there are total {allowed_count} allowed IPs")
return allowed_count | [
"def loadMaxIPlist(self, filename):\r\n #I need to put this in a try/catch block later \r\n \r\n maxIPlist=10\r\n linecount=0 \r\n iplist=[]\r\n with open(filename, 'r') as infile:\r\n element = infile.readline()\r\n while element:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logical disjunction of two ranges. Contains items present in either. However if the two ranges are disjunct (no common items), `None` is returned. >>> Range(10, 20) | Range(1, 3) >>> Range(10, 20) | Range(1, 9) Range(1, 20) >>> Range(10, 20) | Range(1, 10) Range(1, 20) >>> Range(10, 20) | Range(1, 14) Range(1, 20) >>> ... | def __or__(self, other):
if not isinstance(other, Range):
raise TypeError(
f"unsupported operand types for |: "
f"{type(self).__name__!r} and {type(other).__name__!r}"
)
if self == other:
return Range(self.vmin, self.vmax)
elif... | [
"def ranges_overlap(start1, end1, start2, end2):\n return start1 <= end2 and end1 >= start2",
"def overlap(start1, end1, start2, end2):\n return not (end1 < start2 or end2 < start1)",
"def isdisjoint(self, other: Union[Rangelike, Iterable[Rangelike]]) -> bool:\n # convert to RangeSet\n other... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the donor_participant of this AllOfCreateClaimResponseClaim. | def donor_participant(self) -> Object:
return self._donor_participant | [
"def donor_participant(self, donor_participant: Object):\n\n self._donor_participant = donor_participant",
"def participant(self) -> AllOfCancelClaimRequestParticipant:\n return self._participant",
"def participant(self) -> AllOfAcknowledgeClaimRequestParticipant:\n return self._participant... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the donor_participant of this AllOfCreateClaimResponseClaim. | def donor_participant(self, donor_participant: Object):
self._donor_participant = donor_participant | [
"def participant(self, participant: AllOfCancelClaimRequestParticipant):\n if participant is None:\n raise ValueError(\"Invalid value for `participant`, must not be `None`\") # noqa: E501\n\n self._participant = participant",
"def donor_participant(self) -> Object:\n return self._... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the resolution_period_end of this AllOfCreateClaimResponseClaim. | def resolution_period_end(self) -> datetime:
return self._resolution_period_end | [
"def resolution_period_end(self, resolution_period_end: datetime):\n if resolution_period_end is None:\n raise ValueError(\"Invalid value for `resolution_period_end`, must not be `None`\") # noqa: E501\n\n self._resolution_period_end = resolution_period_end",
"def period_end(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the resolution_period_end of this AllOfCreateClaimResponseClaim. | def resolution_period_end(self, resolution_period_end: datetime):
if resolution_period_end is None:
raise ValueError("Invalid value for `resolution_period_end`, must not be `None`") # noqa: E501
self._resolution_period_end = resolution_period_end | [
"def completion_period_end(self, completion_period_end: datetime):\n\n self._completion_period_end = completion_period_end",
"def period_end(self, period_end):\n\n self._period_end = period_end",
"def resolution_period_end(self) -> datetime:\n return self._resolution_period_end",
"def exp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the completion_period_end of this AllOfCreateClaimResponseClaim. | def completion_period_end(self) -> datetime:
return self._completion_period_end | [
"def completion_period_end(self, completion_period_end: datetime):\n\n self._completion_period_end = completion_period_end",
"def period_end(self):\n return self._period_end",
"def resolution_period_end(self) -> datetime:\n return self._resolution_period_end",
"def expected_last_period_en... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the completion_period_end of this AllOfCreateClaimResponseClaim. | def completion_period_end(self, completion_period_end: datetime):
self._completion_period_end = completion_period_end | [
"def period_end(self, period_end):\n\n self._period_end = period_end",
"def completion_period_end(self) -> datetime:\n return self._completion_period_end",
"def resolution_period_end(self, resolution_period_end: datetime):\n if resolution_period_end is None:\n raise ValueError(\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the last_modified of this AllOfCreateClaimResponseClaim. | def last_modified(self) -> datetime:
return self._last_modified | [
"def last_modified_time(self) -> str:\n return pulumi.get(self, \"last_modified_time\")",
"def last_modified_date_time(self):\n if \"lastModifiedDateTime\" in self._prop_dict:\n return datetime.strptime(self._prop_dict[\"lastModifiedDateTime\"].replace(\"Z\", \"\"), \"%Y-%m-%dT%H:%M:%S.%f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the last_modified of this AllOfCreateClaimResponseClaim. | def last_modified(self, last_modified: datetime):
if last_modified is None:
raise ValueError("Invalid value for `last_modified`, must not be `None`") # noqa: E501
self._last_modified = last_modified | [
"def last_modified(self, last_modified):\n\n self._last_modified = last_modified",
"def last_modified(self, last_modified):\n self._last_modified = last_modified",
"def last_modified_by(self, last_modified_by):\n\n self._last_modified_by = last_modified_by",
"def last_modified_date(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes an annotation on file according to the darkflow format. | def write_as_frcnn(annotation: pd.DataFrame,
path_to_annotations: str,
image_id: str):
annotation.to_csv(os.path.join(path_to_annotations, '..', 'annotations.txt'),
header=None,
index=None,
mode='a',
... | [
"def writeAnnotations(b, f, ld, n=0):\n \n if args.format.lower() == 'kitti':\n writeKitty(b, os.path.join(ld, \"%06d.txt\" % n))\n elif args.format.lower() == 'voc':\n writeVOC(b, ld, f)\n elif args.format.lower() == 'darknet':\n writeDarknet(b, os.path.join(ld, \"%06d.txt\" % n))"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an offset, plaintext, and oracle, forges a block with the proper padding. | def forge_block(offset, plaintext, oracle):
b_size, _, _ = challenge_12.determine_block_stats(oracle)
new_padding = b"A" * (b_size - offset)
payload = new_padding + challenge_09.pkcs7(plaintext, b_size)
ciphertext = oracle(payload)
return challenge_07.as_blocks(ciphertext, b_size)[1] | [
"def forge_padding_block(oracle):\n b_size, pt_size, padding = challenge_12.determine_block_stats(oracle)\n new_padding = b\"A\" * padding\n\n return challenge_07.as_blocks(oracle(new_padding), b_size)[-1]",
"def pad(plain_text):\n number_of_bytes_to_pad = block_size - len(plain_text) % block_size\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an oracle, forges a block with all PKCS7 padding (which occurs when the length of a plaintext is an integer multiple of the block size) | def forge_padding_block(oracle):
b_size, pt_size, padding = challenge_12.determine_block_stats(oracle)
new_padding = b"A" * padding
return challenge_07.as_blocks(oracle(new_padding), b_size)[-1] | [
"def forge_block(offset, plaintext, oracle):\n b_size, _, _ = challenge_12.determine_block_stats(oracle)\n new_padding = b\"A\" * (b_size - offset)\n payload = new_padding + challenge_09.pkcs7(plaintext, b_size)\n ciphertext = oracle(payload)\n\n return challenge_07.as_blocks(ciphertext, b_size)[1]",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the file from fin and saves the file in wav format in fout | def convert_to_wav(fin, fout):
temp = subprocess.run(["ffmpeg",
"-i",
fin,
fout],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE) | [
"def decode_to_wav(self, filename):\n pass",
"def addWav(self, fp):\n assert os.path.exists(fp) == True\n self.wav = fp",
"def convert_wav(src_wav, dst_wav, subtype='PCM_16'):\n assert os.path.exists(src_wav), \"{} not exists!\".format(src_wav)\n data, sr = soundfile.read(src_wav)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set the message data business_id to a specific value | def step_impl_the_ru_is_set_to(context, business_id):
context.bdd_helper.message_data["business_id"] = business_id | [
"def business_id(self, business_id):\n self._business_id = business_id",
"def business_id(self, business_id):\n\n self._business_id = business_id",
"def business_phone(self, business_phone):\n\n self._business_phone = business_phone",
"def business_key(self, business_key):\n\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Import a submission from deviantArt. Ignores flash content. Uses a combination of the DA backend and HTML scraping. | def import_submission(self, submission: praw.objects.Submission) -> dict:
try:
if self.regex_direct.match(urlsplit(submission.url).netloc):
r = requests.head(submission.url, headers=self.headers)
mime_text = r.headers.get('Content-Type')
mime = mimepar... | [
"def scrape_submission(submission_url):\n\n\t'''\n\tScrape Data\n\t'''\n\n\t# Get submission dict\n\tsubmission_dict = reddit.extract_post_data(submission_url=submission_url)\n\n\t# Get list of comments_dicts\n\tsubmission_object = submission_dict.get('submission_object')\n\tcomments_dict = reddit.extract_post_comm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Post event to all rulesets | def all_events_request():
result = []
message = json.loads(request.stream.read().decode('utf-8'))
for ruleset_name in host.list_rulesets():
result.append(host.post(ruleset_name, message))
return jsonify(result) | [
"def post_events(ruleset_name):\n message = json.loads(request.stream.read().decode('utf-8'))\n result = host.post(ruleset_name, message)\n return jsonify(result)",
"def register_rules_set(self, rules_set):\n self.rules_set = rules_set",
"def update_rule_list(self):\n self.rules = self.ru... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set ruleset state sid | def set_state_sid_request(ruleset_name, sid):
message = json.loads(request.stream.read().decode('utf-8'))
message['sid'] = sid
result = host.patch_state(ruleset_name, message)
return jsonify(result) | [
"def sid(self, sid):\n self._sid = sid",
"def set_state(self, niface, state):\n self.d.set_state(niface, state)",
"def state_id(self, state_id):\n self._state_id = state_id",
"def state_id(self, state_id):\n\n self._state_id = state_id",
"def state_id(self, s):\n pass",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get ruleset state sid | def get_state_sid_request(ruleset_name, sid):
result = host.get_state(ruleset_name, sid)
return jsonify(result) | [
"def survey_state_id(self):\n return self._get('survey_state')",
"def state_id(self, s):\n pass",
"def state_id(self):\n return self._state_id",
"def get_sid(self):\n return self.sid",
"def sid(self):\n return self._sid",
"def sid(self):\n return self.data[''].sid... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Post events to the ruleset | def post_events(ruleset_name):
message = json.loads(request.stream.read().decode('utf-8'))
result = host.post(ruleset_name, message)
return jsonify(result) | [
"def _do_rule_processing(self, line, events):\n\n for rule in self.rules:\n match = rule.regexp.search(line)\n if match:\n events.append(Event(self, rule.handler, LogMatch(line, match)))\n if rule.quick:\n break",
"def PostEvent(*args, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Post sid events to the ruleset | def post_sid_events(ruleset_name, sid):
message = json.loads(request.stream.read().decode('utf-8'))
message['sid'] = sid
result = host.post(ruleset_name, message)
return jsonify(result) | [
"def post_events(ruleset_name):\n message = json.loads(request.stream.read().decode('utf-8'))\n result = host.post(ruleset_name, message)\n return jsonify(result)",
"def _srsp_event_set(self, zpi_cmd):\r\n if zpi_cmd not in self._srsp_events:\r\n self._srsp_events[zpi_cmd] = threading.E... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function populates an instance of DeadlineTab with the UI controls that make up the submission dialog. This tab is instantiated by Katana every time the user selects "Tabs > Thinkbox > Submit to Deadline" from the menu bar in Katana. Essentially, this function serves as a deferred __init__ implementation for the t... | def PopulateSubmitter( gui ):
global submissionInfo
print( "Grabbing submitter info..." )
try:
stringSubInfo = CallDeadlineCommand( [ "-prettyJSON", "-GetSubmissionInfo", "Pools", "Groups", "MaxPriority", "UserHomeDir", "RepoDir:submission/Katana/Main", "RepoDir:submission/Integration/Main", ], useD... | [
"def _create_tabbed_pages(self):\n\n notebook = self.top.get_object('notebook')\n notebook_ref = self.top.get_object('notebook_ref')\n\n self._add_tab(notebook, self.primtab)\n self._add_tab(notebook_ref, self.reftab)\n self.track_ref_for_deletion(\"primtab\")\n self.track_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Augments a staged job info submission file with the appropriate properties for the Pipeline Tool settings. | def ConcatenatePipelineSettingsToJob( jobInfoPath, batchName ):
global submissionInfo
jobWriterPath = os.path.join( submissionInfo["RepoDirs"]["submission/Integration/Main"], "JobWriter.py" )
scenePath = NodegraphAPI.GetSourceFile()
argArray = ["-ExecuteScript", jobWriterPath, "Katana", "--write", "--sc... | [
"def generate_job_info_file(**kwargs):\n\tif kwargs['renderLayer']:\n\t\tjob_info_file_suffix = \"_%s_deadlineJobInfo.txt\" % kwargs['renderLayer']\n\telse:\n\t\tjob_info_file_suffix = \"_deadlineJobInfo.txt\"\n\tjob_info_file = temp_file(kwargs['scene'], suffix=job_info_file_suffix)\n\n\twith open(job_info_file, '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grabs a status message from the JobWriter that indicates which pipeline tools have settings enabled for the current scene. | def RetrievePipelineToolStatus( raiseOnExitCode=False ):
global submissionInfo
scenePath = NodegraphAPI.GetSourceFile()
jobWriterPath = os.path.join(submissionInfo["RepoDirs"]["submission/Integration/Main"], "JobWriter.py")
argArray = ["-ExecuteScript", jobWriterPath, "Katana", "--status", "--scene-pa... | [
"def settings_status(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"settings_status\")",
"def get_status(self) -> Text:\n store = self.metadata_store\n return store.get_pipeline_status(self)",
"def SubToolSetStatus(SubtoolIndex, Value) -> int:\n pass",
"def runner_status():\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modifies the Pipeline Tool status label UI element with the supplied message | def UpdatePipelineToolStatusLabel( gui, statusMessage ):
gui.pipelineToolStatusLabel.setText( statusMessage ) | [
"def set_status_label(self, msg):\n self.status_label.setText('<b>{}</b>'.format(msg))",
"def updateStatus(self, message):\n self.statusArea.setText(message + \"\\n\")",
"def set_status_text(self, message, field=0):\n logging.info(\"setting field: %s to string: %s\" % (field, message))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generic error handling when the a pipeline tools script run via deadline command returns a nonzero exit code. Generates a technical error message for a given subprocess.CalledProcessError instance and displays it in the Katana console. Similarly, a humanreadable error message is presented to the user in a modal dialog.... | def HandlePipelineToolsCalledProcessError( exc ):
errorMsg = StringIO()
errorMsg.write( "Pipeline Tools encountered an error - the command:" )
errorMsg.write( os.linesep * 2 )
errorMsg.write( exc.cmd )
errorMsg.write( os.linesep * 2 )
errorMsg.write( "return a non-zero (%d) exit code" % exc.retu... | [
"def handle_build_error(error):\n sys.stderr.write('Error running command `%s`. Returned %s.\\n' % (\n ' '.join(error.argv), str(error.error_code)))",
"def print_unable_to_run(exc: \"CalledProcessError\"):\n _print(str(exc), level=MessageLevel.QUIET)",
"def set_launch_failed(self):\n self.diagno... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens the a dialog for viewing and modifying the job's pipeline tool settings. The dialog is launched in a deadline command subprocess. All settings are maintained by the JobWriter using a combination of the application name and the scene path. | def OpenIntegrationWindow( raiseOnExitCode=False ):
global submissionInfo
integrationPath = os.path.join( submissionInfo["RepoDirs"]["submission/Integration/Main"], "IntegrationUIStandAlone.py" )
scenePath = NodegraphAPI.GetSourceFile()
if not scenePath:
raise SceneNotSavedError()
argArray ... | [
"def shotWinUI(*args):\n### ---------- should check for current project\n if cmds.window(\"shotWin\", exists = True):\n cmds.deleteUI(\"shotWin\")\n\n widgets[\"win\"] = cmds.window(\"shotWin\", t= \"Charlex Shot Manager\", w=1000, h=560, s=False)\n widgets[\"mainCLO\"] = cmds.columnLayout(w=1000, h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the path to DeadlineCommand. | def GetDeadlineCommand( useDeadlineBg=False ):
deadlineBin = ""
try:
deadlineBin = os.environ[ 'DEADLINE_PATH' ]
except KeyError:
# if the error is a key error it means that DEADLINE_PATH is not set. however Deadline command may be in the PATH or on OSX it could be in the file /Users/Shared/... | [
"def _get_cmd_line_file_path(self):\n return join(self._active_output_dir, \"cmd_line\")",
"def command_path(\n sibling_ctx: click.core.Context,\n command: click.core.Command,\n) -> str:\n command_path_list = sibling_ctx.command_path.split()\n command_path_list[-1] = command.name\n return ' ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |