query
stringlengths
9
3.4k
document
stringlengths
9
87.4k
metadata
dict
negatives
listlengths
4
101
negative_scores
listlengths
4
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
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()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def put(self, book_id):\n a_book = query_book_by_id(book_id)\n if a_book is None:\n return 'Book does not exit', 404\n body = request.get_json()\n a_book.parse_body(body)\n db.session.add(a_book)\n db.session.commit()\n return a_book.serialize(), 200", ...
[ "0.7573654", "0.72800773", "0.724804", "0.71230936", "0.7046375", "0.70066255", "0.6929183", "0.6876896", "0.6876203", "0.68481857", "0.6840768", "0.6555312", "0.6484862", "0.6337583", "0.6248639", "0.62454295", "0.62454295", "0.6211745", "0.6150676", "0.61380297", "0.6113835...
0.7472767
1
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_samples_{name}_main_panel') elif role == 'data_tabular': print(f'create data_tabular={name}') data_table = TabsDynamicData(doc, options, connection, name, role, creator_fn=process_data_tabular) panel = data_table.get_ui() elif role == 'data_graph': print(f'create data_graph={name}') data_table = TabsDynamicData(doc, options, connection, name, role, creator_fn=process_data_graph) panel = data_table.get_ui() else: raise NotImplementedError(f'role not implemented={role}') assert isinstance(panel, Panel), f'unexpected type={type(panel)}' # handle the table preamble here metadata_name = get_metadata_name(name) metadata = get_table_data(connection, metadata_name) preamble = metadata.get('table_preamble') if preamble is not None and len(preamble[0]) > 0: # we have a preamble for our table. Add a ``Div`` widget to y_axis the preamble child = column(Div(text=preamble[0]), panel.child, sizing_mode='stretch_both') panel.update(child=child) print(f'table={name} created!') return panel
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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_panel(self):\n return\n # return Panel(self)", "def...
[ "0.6599751", "0.60347813", "0.6001966", "0.59753203", "0.5832454", "0.58038557", "0.5691837", "0.568478", "0.558809", "0.55831575", "0.5527184", "0.5521518", "0.55198944", "0.5481038", "0.5476279", "0.54733795", "0.5462939", "0.54569745", "0.54461217", "0.54309857", "0.542044...
0.62888616
1
Generate the reporting from a SQL database and configuration.
def report(sql_database_path, options, doc=None): options.db_root = sql_database_path connection = sqlite3.connect(sql_database_path) root = os.path.dirname(sql_database_path) if not options.embedded: output_file(os.path.join(root, 'index.html'), title=os.path.basename(root)) if doc is None: doc = curdoc() doc.title = os.path.basename(root) tabs = TabsDynamicHeader(doc, options, connection, creator_fn=functools.partial( create_tables, doc=doc, options=options, connection=connection)) if options.embedded: doc.add_root(tabs.get_ui()) else: show(tabs) return doc
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main():\n\n app_config = load_config()\n database_connection = mysql.connector.connect(**app_config[\"database\"])\n panelists = retrieve_all_panelist_appearance_counts(database_connection)\n show_years = retrieve_all_years(database_connection)\n\n rendered_report = render_report(show_years=show...
[ "0.6794699", "0.66871136", "0.65021914", "0.62209666", "0.61934847", "0.60308546", "0.5982817", "0.59790987", "0.592974", "0.5917811", "0.59072703", "0.5890908", "0.5875626", "0.58747375", "0.5855787", "0.5842963", "0.5797533", "0.5772772", "0.5766548", "0.5740692", "0.573329...
0.5793379
17
Gracefully stop the worker process
def stop(self, reason: str = ""): # Send a stop message to the thread self.queue.put(StopSignal(reason)) # Wait for the thread to stop self.join()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def stop_force(self):\n if self._worker:\n self._worker.stop_immediate()", "def stop(self):\n # print \"process shutdown complete\"", "def _gracefully_stop(self):\n pass", "def stop(self):\n debug(\"CBA4.__worker_thread.stop()\")\n self.__run = False\n ...
[ "0.8016386", "0.7890734", "0.78806144", "0.7801088", "0.7657094", "0.7623798", "0.7623798", "0.7623798", "0.7623798", "0.7623798", "0.7623798", "0.76114714", "0.7605681", "0.75831264", "0.7580056", "0.75631684", "0.7506741", "0.746279", "0.7421699", "0.7421699", "0.7421699", ...
0.0
-1
Update the user data.
def update_user(self) -> db.User: log.debug("Fetching updated user data from the database") self.user = self.session.query(db.User).filter(db.User.user_id == self.chat.id).one_or_none() return self.user
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_user():", "async def update(self):\n self.data = await self.api.user.get()", "def update_user_data(self, new_user: User):\n self.user_data.update_user_data(new_user)", "def update_user():\n #TODO user update \n pass", "def update(self, user: U) -> None:\n ...", "def ...
[ "0.8453508", "0.8318778", "0.8220215", "0.8076822", "0.7558734", "0.7450923", "0.72408086", "0.72176486", "0.720254", "0.7171292", "0.7140886", "0.7136574", "0.7135001", "0.7109253", "0.70718855", "0.70602965", "0.7050676", "0.70275545", "0.6921391", "0.6852711", "0.6821397",...
0.6807245
22
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(StopSignal("timeout")) # Check if the data is a stop signal instance if isinstance(data, StopSignal): # Gracefully stop the process log.debug("Waiting for a specific message...") self.__graceful_stop(data) # Return the received update return data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 ...
[ "0.75623107", "0.61685276", "0.5938287", "0.591084", "0.58862364", "0.5823619", "0.5713644", "0.56726706", "0.5642151", "0.5579003", "0.55334973", "0.5469232", "0.54662484", "0.5425067", "0.54067975", "0.54012185", "0.53892756", "0.5383263", "0.537932", "0.53742594", "0.53650...
0.778689
0
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.__graceful_stop(StopSignal("timeout")) # Check if the data is a stop signal instance if isinstance(data, StopSignal): # Gracefully stop the process log.debug("Waiting for a specific message...") self.__graceful_stop(data) # Return the received update return data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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...
[ "0.77863574", "0.61682695", "0.59378856", "0.5911545", "0.5886102", "0.5824382", "0.5714152", "0.5673009", "0.56416255", "0.5580509", "0.5534133", "0.54715234", "0.5465117", "0.54249656", "0.5407767", "0.5402611", "0.53896356", "0.53829896", "0.5379179", "0.5373928", "0.53666...
0.7561312
1
Continue getting updates until until one of the strings contained in the list is received as a message.
def __wait_for_specific_message(self, items: List[str], cancellable: bool = False) -> Union[str, CancelSignal]: log.debug("Waiting for a specific message...") while True: # Get the next update update = self.__receive_next_update() log.debug(f"get command {update.message.text}") log.debug(f"get command list {items}") # If a CancelSignal is received... if isinstance(update, CancelSignal): # And the wait is cancellable... if cancellable: # Return the CancelSignal return update else: # Ignore the signal continue # Ensure the update contains a message if update.message is None: continue # Ensure the message contains text if update.message.text is None: continue # Check if the message is contained in the list if update.message.text not in items: continue # Return the message text return update.message.text
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def handl_update(updates):\n for update in updates[\"result\"]:\n text = update[\"message\"][\"text\"]\n chat = update[\"message\"][\"chat\"][\"id\"]\n items = db.get_item(chat)\n if text == \"/done\":\n keyboard = build_keyboard(items)\n send_message(\"Sélectio...
[ "0.63190633", "0.6146581", "0.6050368", "0.59897554", "0.5915279", "0.58745605", "0.57445425", "0.5734721", "0.5697445", "0.5672764", "0.5622075", "0.55866826", "0.55780554", "0.55602586", "0.5549589", "0.55215335", "0.5500802", "0.5496615", "0.5496615", "0.54910165", "0.5484...
0.61539835
1
Continue getting updates until until one of the strings contained in the list is received as a message.
def wait_for_specific_message(self, items: List[str], cancellable: bool = False) -> Union[str, CancelSignal]: log.debug("Waiting for a specific message...") while True: # Get the next update update = self.__receive_next_update() try: log.debug(f"get command {update.message.text}") log.debug(f"get command list {items}") except: log.debug(f"update.message.text is None") # If a CancelSignal is received... if isinstance(update, CancelSignal): # And the wait is cancellable... if cancellable: # Return the CancelSignal return update else: # Ignore the signal continue # Ensure the update contains a message if update.message is None: # @todo подумать как отделить команды из основного меню и команды из второго меню if not update.callback_query is None: log.debug(f"get second command {update.callback_query.data}") return update continue # Ensure the message contains text if update.message.text is None: continue # Check if the message is contained in the list if update.message.text not in items: continue # Return the message text return update.message.text
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def handl_update(updates):\n for update in updates[\"result\"]:\n text = update[\"message\"][\"text\"]\n chat = update[\"message\"][\"chat\"][\"id\"]\n items = db.get_item(chat)\n if text == \"/done\":\n keyboard = build_keyboard(items)\n send_message(\"Sélectio...
[ "0.6316987", "0.61527497", "0.6050467", "0.5988231", "0.59152", "0.58755267", "0.57460624", "0.5736165", "0.5697131", "0.56726414", "0.5621541", "0.5587972", "0.5576721", "0.5558328", "0.555187", "0.552112", "0.549891", "0.54971206", "0.54971206", "0.5490253", "0.54853934", ...
0.61454093
2
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(update, CancelSignal): # And the wait is cancellable... if cancellable: # Return the CancelSignal return update else: # Ignore the signal continue # Ensure the update contains a message if update.message is None: continue # Ensure the message contains text if update.message.text is None: continue # Try to match the regex with the received message match = re.search(regex, update.message.text) # Ensure there is a match if match is None: continue # Return the first capture group return match.group(1)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getMatch(reMatch,group=0):\n if reMatch: return reMatch.group(group)\n else: return ''", "def recvregex(self, regex):\n if isinstance(regex, str):\n regex = re.compile(regex)\n buf = ''\n match = None\n\n while not match:\n buf += d(self.recv(1))\n ...
[ "0.629262", "0.62774885", "0.6136326", "0.61299783", "0.6032749", "0.6029412", "0.59464234", "0.5920094", "0.57432276", "0.57361436", "0.5642497", "0.56279725", "0.5584992", "0.55632395", "0.5546507", "0.5532469", "0.54971576", "0.5486865", "0.54025245", "0.53982574", "0.5376...
0.69942236
0
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() # If a CancelSignal is received... if isinstance(update, CancelSignal): # And the wait is cancellable... if cancellable: # Return the CancelSignal return update else: # Ignore the signal continue # Ensure the update contains a precheckoutquery if update.pre_checkout_query is None: continue # Return the precheckoutquery return update.pre_checkout_query
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def answer_pre_checkout_query(self, pre_checkout_query_id: base.String, ok: base.Boolean,\n error_message: typing.Union[base.String, None] = None) -> base.Boolean:\n payload = generate_payload(**locals())\n result = await self.request(api.Methods.ANSWER_PR...
[ "0.6297387", "0.52683717", "0.51722956", "0.51680756", "0.5077127", "0.50706697", "0.5068419", "0.50682193", "0.5056422", "0.5022585", "0.4991616", "0.4961541", "0.49071103", "0.49062324", "0.48711935", "0.4865397", "0.48612118", "0.48573983", "0.48536915", "0.4841989", "0.48...
0.7185964
0
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() # If a CancelSignal is received... if isinstance(update, CancelSignal): # And the wait is cancellable... if cancellable: # Return the CancelSignal return update else: # Ignore the signal continue # Ensure the update contains a message if update.message is None: continue # Ensure the message is a successfulpayment if update.message.successful_payment is None: continue # Return the successfulpayment return update.message.successful_payment
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def awaiting_payment(self):", "def webhook_payment_successful(self, event):\n\n intent = event.data.object\n p_id = intent.id\n pack = intent.metadata.pack\n save_detail = intent.metadata.save_detail\n\n billing_details = intent.charges.data[0].billing_details\n shipping...
[ "0.7672672", "0.6573215", "0.65442157", "0.6435054", "0.6081593", "0.60590357", "0.60243624", "0.6005645", "0.59923875", "0.5971794", "0.5949517", "0.59342396", "0.5882962", "0.58690065", "0.5868896", "0.5814729", "0.5801393", "0.5796031", "0.5784956", "0.5747631", "0.5716991...
0.67208254
1
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 isinstance(update, CancelSignal): # And the wait is cancellable... if cancellable: # Return the CancelSignal return update else: # Ignore the signal continue # Ensure the update contains a message if update.message is None: continue # Ensure the message contains a photo if update.message.photo is None: continue # Return the photo array return update.message.photo
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_img(self):\n img_old = self.img\n #Ensure at least one image has been captured\n attempts = 0\n while img_old == None:\n print(\"Wating to capture first image...\")\n time.sleep(1)\n img_old = self.img\n attempts = attempts + 1\n ...
[ "0.65705794", "0.6327374", "0.63064396", "0.60424834", "0.5937122", "0.5898389", "0.5863462", "0.582088", "0.58116835", "0.57911056", "0.5773972", "0.57718194", "0.5729892", "0.57232875", "0.5681439", "0.5619149", "0.5587965", "0.5579192", "0.5574852", "0.5565938", "0.5523706...
0.78513974
0
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 CancelSignal is received... if isinstance(update, CancelSignal): # And the wait is cancellable... if cancellable: # Return the CancelSignal return update else: # Ignore the signal continue # Ensure the update is a CallbackQuery if update.callback_query is None: continue # Answer the callbackquery self.bot.answer_callback_query(update.callback_query.id) # Return the callbackquery return update.callback_query
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def detectKeyboard(self):\n self.runKeyboard()\n time.sleep(0.2)\n searching = True\n while searching:\n for dev in self.keyboards:\n if self.hitsKeyboards[dev] != False:\n return(dev, self.map(self.hitsKeyboards[dev]))\n time....
[ "0.635834", "0.61028296", "0.57839763", "0.572346", "0.57095325", "0.57065344", "0.56824297", "0.5674951", "0.5604688", "0.5577965", "0.5554134", "0.5550242", "0.5487043", "0.54515177", "0.54401964", "0.54355025", "0.54113567", "0.54003197", "0.53757066", "0.5371119", "0.5356...
0.6559372
0
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_buttons = [[self.loc.get("menu_all_cancel")]] # Add to the list all the users for user in users: keyboard_buttons.append([user.identifiable_str()]) # Create the keyboard keyboard = telegram.ReplyKeyboardMarkup(keyboard_buttons, one_time_keyboard=True) # Keep asking until a result is returned while True: # Send the keyboard self.bot.send_message(self.chat.id, self.loc.get("conversation_admin_select_user"), reply_markup=keyboard) # Wait for a reply reply = self.__wait_for_regex("user_([0-9]+)", cancellable=True) # Propagate CancelSignals if isinstance(reply, CancelSignal): return reply # Find the user in the database user = self.session.query(db.User).filter_by(user_id=int(reply)).one_or_none() # Ensure the user exists if not user: self.bot.send_message(self.chat.id, self.loc.get("error_user_does_not_exist")) continue return user
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def select_user(user_id):\n return session.query(User).filter(User.id == user_id).first()", "def get_user_by_id(self, user_id):\n query = \"SELECT * FROM users WHERE user_id = %s\"\n self.cursor.execute(query,[user_id])\n result = self.cursor.fetchone()\n return result", "def sel...
[ "0.75827193", "0.699098", "0.6802506", "0.6733667", "0.67225665", "0.6699956", "0.65688473", "0.648302", "0.6470143", "0.6464637", "0.6432358", "0.6409055", "0.63881916", "0.6382047", "0.6382047", "0.6382047", "0.6382047", "0.63656896", "0.6337928", "0.6337304", "0.63207024",...
0.7315355
1
Function called from the run method when the user is an administrator. Administrative bot actions should be placed here.
def __admin_menu(self): log.debug("Displaying __admin_menu") self.menu = TelegramMenu("config/comunda_admin_menu.bpmn", self, "MenuStart") self.menu.admin_menu("MenuStart", "menu_admin_main_txt") return
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def admin(ctx):\n info = await(bot.application_info())\n mention = info.owner.mention\n message = \"My administrator is the glorious {}. Fear them, for they are mighty.\".format(mention)\n await(ctx.send(message))", "async def admin(self, ctx):\n if ctx.message.author.top_role.name.lower() =...
[ "0.75844574", "0.7409877", "0.71615165", "0.6955135", "0.68585837", "0.6853824", "0.6839778", "0.67531025", "0.6739723", "0.6719039", "0.6716561", "0.6714989", "0.6699009", "0.66858125", "0.6648104", "0.6636272", "0.6636272", "0.66090745", "0.6602627", "0.65490353", "0.653424...
0.5894155
84
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[db.Product, int]] = {} # Initialize the products list for product in products: # If the product is not for sale, don't display it if product.price is None: continue # Send the message without the keyboard to get the message id message = product.send_as_message(w=self, chat_id=self.chat.id) # Add the product to the cart cart[message['result']['message_id']] = [product, 0] # Create the inline keyboard to add the product to the cart inline_keyboard = telegram.InlineKeyboardMarkup( [[telegram.InlineKeyboardButton(self.loc.get("menu_add_to_cart"), callback_data="cart_add")]] ) # Edit the sent message and add the inline keyboard if product.image is None: self.bot.edit_message_text(chat_id=self.chat.id, message_id=message['result']['message_id'], text=product.text(w=self), reply_markup=inline_keyboard) else: self.bot.edit_message_caption(chat_id=self.chat.id, message_id=message['result']['message_id'], caption=product.text(w=self), reply_markup=inline_keyboard) # Create the keyboard with the cancel button inline_keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(self.loc.get("menu_all_cancel"), callback_data="cart_cancel")]]) # Send a message containing the button to cancel or pay final_msg = self.bot.send_message(self.chat.id, self.loc.get("conversation_cart_actions"), reply_markup=inline_keyboard) # Wait for user input while True: callback = self.__wait_for_inlinekeyboard_callback() # React to the user input # If the cancel button has been pressed... if callback.data == "cart_cancel": # Stop waiting for user input and go back to the previous menu return # If a Add to Cart button has been pressed... elif callback.data == "cart_add": # Get the selected product, ensuring it exists p = cart.get(callback.message.message_id) if p is None: continue product = p[0] # Add 1 copy to the cart cart[callback.message.message_id][1] += 1 # Create the product inline keyboard product_inline_keyboard = telegram.InlineKeyboardMarkup( [ [telegram.InlineKeyboardButton(self.loc.get("menu_add_to_cart"), callback_data="cart_add"), telegram.InlineKeyboardButton(self.loc.get("menu_remove_from_cart"), callback_data="cart_remove")] ]) # Create the final inline keyboard final_inline_keyboard = telegram.InlineKeyboardMarkup( [ [telegram.InlineKeyboardButton(self.loc.get("menu_all_cancel"), callback_data="cart_cancel")], [telegram.InlineKeyboardButton(self.loc.get("menu_done"), callback_data="cart_done")] ]) # Edit both the product and the final message if product.image is None: self.bot.edit_message_text(chat_id=self.chat.id, message_id=callback.message.message_id, text=product.text(w=self, cart_qty=cart[callback.message.message_id][1]), reply_markup=product_inline_keyboard) else: self.bot.edit_message_caption(chat_id=self.chat.id, message_id=callback.message.message_id, caption=product.text(w=self, cart_qty=cart[callback.message.message_id][1]), reply_markup=product_inline_keyboard) self.bot.edit_message_text( chat_id=self.chat.id, message_id=final_msg.message_id, text=self.loc.get("conversation_confirm_cart", product_list=self.__get_cart_summary(cart), total_cost=str(self.__get_cart_value(cart))), reply_markup=final_inline_keyboard) # If the Remove from cart button has been pressed... elif callback.data == "cart_remove": # Get the selected product, ensuring it exists p = cart.get(callback.message.message_id) if p is None: continue product = p[0] # Remove 1 copy from the cart if cart[callback.message.message_id][1] > 0: cart[callback.message.message_id][1] -= 1 else: continue # Create the product inline keyboard product_inline_list = [[telegram.InlineKeyboardButton(self.loc.get("menu_add_to_cart"), callback_data="cart_add")]] if cart[callback.message.message_id][1] > 0: product_inline_list[0].append(telegram.InlineKeyboardButton(self.loc.get("menu_remove_from_cart"), callback_data="cart_remove")) product_inline_keyboard = telegram.InlineKeyboardMarkup(product_inline_list) # Create the final inline keyboard final_inline_list = [[telegram.InlineKeyboardButton(self.loc.get("menu_all_cancel"), callback_data="cart_cancel")]] for product_id in cart: if cart[product_id][1] > 0: final_inline_list.append([telegram.InlineKeyboardButton(self.loc.get("menu_done"), callback_data="cart_done")]) break final_inline_keyboard = telegram.InlineKeyboardMarkup(final_inline_list) # Edit the product message if product.image is None: self.bot.edit_message_text(chat_id=self.chat.id, message_id=callback.message.message_id, text=product.text(w=self, cart_qty=cart[callback.message.message_id][1]), reply_markup=product_inline_keyboard) else: self.bot.edit_message_caption(chat_id=self.chat.id, message_id=callback.message.message_id, caption=product.text(w=self, cart_qty=cart[callback.message.message_id][1]), reply_markup=product_inline_keyboard) self.bot.edit_message_text( chat_id=self.chat.id, message_id=final_msg.message_id, text=self.loc.get("conversation_confirm_cart", product_list=self.__get_cart_summary(cart), total_cost=str(self.__get_cart_value(cart))), reply_markup=final_inline_keyboard) # If the done button has been pressed... elif callback.data == "cart_done": # End the loop break # Create an inline keyboard with a single skip button cancel = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(self.loc.get("menu_skip"), callback_data="cmd_cancel")]]) # Ask if the user wants to add notes to the order self.bot.send_message(self.chat.id, self.loc.get("ask_order_notes"), reply_markup=cancel) # Wait for user input notes = self.__wait_for_regex(r"(.*)", cancellable=True) # Create a new Order order = db.Order(user=self.user, creation_date=datetime.datetime.now(), notes=notes if not isinstance(notes, CancelSignal) else "") # Add the record to the session and get an ID self.session.add(order) self.session.flush() # For each product added to the cart, create a new OrderItem for product in cart: # Create {quantity} new OrderItems for i in range(0, cart[product][1]): order_item = db.OrderItem(product=cart[product][0], order_id=order.order_id) self.session.add(order_item) # Ensure the user has enough credit to make the purchase credit_required = self.__get_cart_value(cart) - self.user.credit # Notify user in case of insufficient credit if credit_required > 0: self.bot.send_message(self.chat.id, self.loc.get("error_not_enough_credit")) # Suggest payment for missing credit value if configuration allows refill if self.cfg.ccard["credit_card_token"] != "" \ and self.cfg.appearance["refill_on_checkout"] \ and self.Price(self.cfg.ccard["min_amount"]) <= \ credit_required <= \ self.Price(self.cfg.ccard["max_amount"]): self.__make_payment(self.Price(credit_required)) # If afer requested payment credit is still insufficient (either payment failure or cancel) if self.user.credit < self.__get_cart_value(cart): # Rollback all the changes self.session.rollback() else: # User has credit and valid order, perform transaction now self.__order_transaction(order=order, value=-int(self.__get_cart_value(cart)))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 ...
[ "0.73180735", "0.72016907", "0.6804957", "0.6651566", "0.64211893", "0.6275277", "0.6244939", "0.6185193", "0.6105577", "0.59807813", "0.5963281", "0.5960109", "0.59552896", "0.5910854", "0.5890219", "0.58691454", "0.58535814", "0.58395153", "0.5799699", "0.57818246", "0.5745...
0.73403376
0
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 there is at least one order to display if len(orders) == 0: self.bot.send_message(self.chat.id, self.loc.get("error_no_orders")) # Display the order status to the user for order in orders: self.bot.send_message(self.chat.id, order.text(w=self, session=self.session, user=True)) # TODO: maybe add a page displayer instead of showing the latest 5 orders
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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...
[ "0.6624454", "0.6607733", "0.6512122", "0.6492815", "0.6353827", "0.633038", "0.61956954", "0.6176387", "0.6156388", "0.6110003", "0.6095435", "0.6048326", "0.6021349", "0.601456", "0.6001526", "0.5956618", "0.59367436", "0.5935654", "0.5873689", "0.58426803", "0.58011866", ...
0.8103798
0
Add more credit to the account.
def __add_credit_menu(self): log.debug("Displaying __add_credit_menu") # Create a payment methods keyboard keyboard = list() # Add the supported payment methods to the keyboard # Cash keyboard.append([telegram.KeyboardButton(self.loc.get("menu_cash"))]) # Telegram Payments if self.cfg.ccard["credit_card_token"] != "": keyboard.append([telegram.KeyboardButton(self.loc.get("menu_credit_card"))]) # Keyboard: go back to the previous menu keyboard.append([telegram.KeyboardButton(self.loc.get("menu_all_cancel"))]) # Send the keyboard to the user self.bot.send_message(self.chat.id, self.loc.get("conversation_payment_method"), reply_markup=telegram.ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)) # Wait for a reply from the user selection = self.__wait_for_specific_message( [self.loc.get("menu_cash"), self.loc.get("menu_credit_card"), self.loc.get("menu_all_cancel")], cancellable=True) # If the user has selected the Cash option... if selection == self.loc.get("menu_cash"): # Go to the pay with cash function self.bot.send_message(self.chat.id, self.loc.get("payment_cash", user_cash_id=self.user.identifiable_str())) # If the user has selected the Credit Card option... elif selection == self.loc.get("menu_credit_card"): # Go to the pay with credit card function self.__add_credit_cc() # If the user has selected the Cancel option... elif isinstance(selection, CancelSignal): # Send him back to the previous menu return
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_cash(self, num):\r\n self.cash += num", "def charge(self, other):\n self.credit += other\n print(\"{} Tomans has been added to your card credit and now the credit of your card is {} Tomans\".format(other,\n ...
[ "0.69172204", "0.66686106", "0.6434494", "0.63797307", "0.6366903", "0.63653505", "0.63360935", "0.62970746", "0.61494195", "0.61124676", "0.6106093", "0.6090619", "0.60866374", "0.6017041", "0.596591", "0.59351707", "0.59126014", "0.59064865", "0.58755064", "0.587065", "0.58...
0.0
-1
Add money to the wallet through a credit card payment.
def __add_credit_cc(self): log.debug("Displaying __add_credit_cc") # Create a keyboard to be sent later presets = self.cfg.ccard["payment_presets"] keyboard = [[telegram.KeyboardButton(str(self.Price(preset)))] for preset in presets] keyboard.append([telegram.KeyboardButton(self.loc.get("menu_all_cancel"))]) # Boolean variable to check if the user has cancelled the action cancelled = False # Loop used to continue asking if there's an error during the input while not cancelled: # Send the message and the keyboard self.bot.send_message(self.chat.id, self.loc.get("payment_cc_amount"), reply_markup=telegram.ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)) # Wait until a valid amount is sent selection = self.__wait_for_regex(r"([0-9]+(?:[.,][0-9]+)?|" + self.loc.get("menu_all_cancel") + r")", cancellable=True) # If the user cancelled the action if isinstance(selection, CancelSignal): # Exit the loop cancelled = True continue # Convert the amount to an integer value = self.Price(selection) # Ensure the amount is within the range if value > self.Price(self.cfg.ccard["max_amount"]): self.bot.send_message(self.chat.id, self.loc.get("error_payment_amount_over_max", max_amount=self.Price(self.cfg.ccard["max_amount"]))) continue elif value < self.Price(self.cfg.ccard["min_amount"]): self.bot.send_message(self.chat.id, self.loc.get("error_payment_amount_under_min", min_amount=self.Price(self.cfg.ccard["min_amount"]))) continue break # If the user cancelled the action... else: # Exit the function return # Issue the payment invoice self.__make_payment(amount=value)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def addMoney(self, deposit_amount):\r\n self.balance_amt = self.balance_amt + deposit_amount", "def pay(self, amt: float):\n self._money += amt", "def add_cash(self, num):\r\n self.cash += num", "def add_cash(self, delta):\n self._cash += delta", "def add_money(self, money):\n ...
[ "0.7334819", "0.7255061", "0.71674275", "0.71091676", "0.6800556", "0.679979", "0.67486334", "0.6726071", "0.6674474", "0.6597652", "0.65973526", "0.6543555", "0.6450733", "0.6426142", "0.64172155", "0.6342648", "0.63420105", "0.6317631", "0.6289854", "0.6270424", "0.6201341"...
0.59404606
46
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"))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def info(ctx):\n embed = discord.Embed(title=\"Zane Bot\", description=\"All hail the hypnotoad!\", color=0x0091C5)\n\n # give info about you here\n embed.add_field(name=\"Author\", value=\"Zanexius\")\n\n # Shows the number of servers the bot is member of.\n embed.add_field(name=\"Server coun...
[ "0.725934", "0.7055274", "0.7054091", "0.7039354", "0.6996456", "0.6912311", "0.68851507", "0.6837405", "0.68016917", "0.67736316", "0.671528", "0.6668429", "0.6624", "0.65209925", "0.64319694", "0.6400704", "0.63974255", "0.6349702", "0.63252884", "0.62954056", "0.62543094",...
0.8450503
0
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 at the start of the list the add product option, the remove product option and the Cancel option product_names.insert(0, self.loc.get("menu_all_cancel")) product_names.insert(1, self.loc.get("menu_add_product")) product_names.insert(2, self.loc.get("menu_delete_product")) # Create a keyboard using the product names keyboard = [[telegram.KeyboardButton(product_name)] for product_name in product_names] # Send the previously created keyboard to the user (ensuring it can be clicked only 1 time) self.bot.send_message(self.chat.id, self.loc.get("conversation_admin_select_product"), reply_markup=telegram.ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)) # Wait for a reply from the user selection = self.__wait_for_specific_message(product_names, cancellable=True) # If the user has selected the Cancel option... if isinstance(selection, CancelSignal): # Exit the menu return # If the user has selected the Add Product option... elif selection == self.loc.get("menu_add_product"): # Open the add product menu self.__edit_product_menu() # If the user has selected the Remove Product option... elif selection == self.loc.get("menu_delete_product"): # Open the delete product menu self.__delete_product_menu() # If the user has selected a product else: # Find the selected product product = self.session.query(db.Product).filter_by(name=selection, deleted=False).one() # Open the edit menu for that specific product self.__edit_product_menu(product=product)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __edit_product_menu(self, product: Optional[db.SwimPool] = None):\n log.debug(\"Displaying __edit_product_menu\")\n # Create an inline keyboard with a single skip button\n cancel = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(self.loc.get(\"menu_skip\"),\n ...
[ "0.6703032", "0.6085533", "0.6074324", "0.60685647", "0.60130733", "0.59926045", "0.59859747", "0.5963964", "0.594613", "0.5924462", "0.5916004", "0.5900565", "0.5900224", "0.588214", "0.58810765", "0.5868658", "0.58564746", "0.58458424", "0.58431137", "0.5818649", "0.5691315...
0.67454296
0
Add a product to the database or edit an existing one.
def __edit_product_menu(self, product: Optional[db.SwimPool] = None): log.debug("Displaying __edit_product_menu") # Create an inline keyboard with a single skip button cancel = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(self.loc.get("menu_skip"), callback_data="cmd_cancel")]]) # Ask for the product name until a valid product name is specified while True: # Ask the question to the user self.bot.send_message(self.chat.id, self.loc.get("ask_product_name")) # Display the current name if you're editing an existing product if product: self.bot.send_message(self.chat.id, self.loc.get("edit_current_value", value=escape(product.name)), reply_markup=cancel) # Wait for an answer name = self.__wait_for_regex(r"(.*)", cancellable=bool(product)) # Ensure a product with that name doesn't already exist if (product and isinstance(name, CancelSignal)) or \ self.session.query(db.Product).filter_by(name=name, deleted=False).one_or_none() in [None, product]: # Exit the loop break self.bot.send_message(self.chat.id, self.loc.get("error_duplicate_name")) # Ask for the product description self.bot.send_message(self.chat.id, self.loc.get("ask_product_description")) # Display the current description if you're editing an existing product if product: self.bot.send_message(self.chat.id, self.loc.get("edit_current_value", value=escape(product.description)), reply_markup=cancel) # Wait for an answer description = self.__wait_for_regex(r"(.*)", cancellable=bool(product)) # Ask for the product price self.bot.send_message(self.chat.id, self.loc.get("ask_product_price")) # Display the current name if you're editing an existing product if product: self.bot.send_message(self.chat.id, self.loc.get("edit_current_value", value=(str(self.Price(product.price)) if product.price is not None else 'Non in vendita')), reply_markup=cancel) # Wait for an answer price = self.__wait_for_regex(r"([0-9]+(?:[.,][0-9]{1,2})?|[Xx])", cancellable=True) # If the price is skipped if isinstance(price, CancelSignal): pass elif price.lower() == "x": price = None else: price = self.Price(price) # Ask for the product image self.bot.send_message(self.chat.id, self.loc.get("ask_product_image"), reply_markup=cancel) # Wait for an answer photo_list = self.__wait_for_photo(cancellable=True) # If a new product is being added... if not product: # Create the db record for the product # noinspection PyTypeChecker product = db.Product(name=name, description=description, price=int(price) if price is not None else None, deleted=False) # Add the record to the database self.session.add(product) # If a product is being edited... else: # Edit the record with the new values product.name = name if not isinstance(name, CancelSignal) else product.name product.description = description if not isinstance(description, CancelSignal) else product.description product.price = int(price) if not isinstance(price, CancelSignal) else product.price # If a photo has been sent... if isinstance(photo_list, list): # Find the largest photo id largest_photo = photo_list[0] for photo in photo_list[1:]: if photo.width > largest_photo.width: largest_photo = photo # Get the file object associated with the photo photo_file = self.bot.get_file(largest_photo.file_id) # Notify the user that the bot is downloading the image and might be inactive for a while self.bot.send_message(self.chat.id, self.loc.get("downloading_image")) self.bot.send_chat_action(self.chat.id, action="upload_photo") # Set the image for that product product.set_image(photo_file) # Commit the session changes self.session.commit() # Notify the user self.bot.send_message(self.chat.id, self.loc.get("success_product_edited"))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_product(self, product: Product):\n log.debug(\"Adding a new product\")\n product_parameters = product.to_db()\n try:\n with DBCursor(self.host) as cursor:\n cursor.execute(\"INSERT INTO items VALUES (?, ?, ?, ?, ?)\", (product_parameters['name'].lower(), produ...
[ "0.76615304", "0.747724", "0.7432021", "0.7285918", "0.7236936", "0.72071856", "0.7193829", "0.7124895", "0.7092477", "0.70228374", "0.7016298", "0.70120984", "0.6989899", "0.69813216", "0.69734406", "0.69442683", "0.68965477", "0.68905777", "0.68659353", "0.6864464", "0.6852...
0.63888717
59
Display a live flow of orders.
def __orders_menu(self): log.debug("Displaying __orders_menu") # Create a cancel and a stop keyboard stop_keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(self.loc.get("menu_stop"), callback_data="cmd_cancel")]]) cancel_keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(self.loc.get("menu_all_cancel"), callback_data="cmd_cancel")]]) # Send a small intro message on the Live Orders mode # Remove the keyboard with the first message... (#39) self.bot.send_message(self.chat.id, self.loc.get("conversation_live_orders_start"), reply_markup=telegram.ReplyKeyboardRemove()) # ...and display a small inline keyboard with the following one self.bot.send_message(self.chat.id, self.loc.get("conversation_live_orders_stop"), reply_markup=stop_keyboard) # Create the order keyboard order_keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(self.loc.get("menu_complete"), callback_data="order_complete")], [telegram.InlineKeyboardButton(self.loc.get("menu_refund"), callback_data="order_refund")]]) # Display the past pending orders orders = self.session.query(db.Order) \ .filter_by(delivery_date=None, refund_date=None) \ .join(db.Transaction) \ .join(db.User) \ .all() # Create a message for every one of them for order in orders: # Send the created message self.bot.send_message(self.chat.id, order.text(w=self, session=self.session), reply_markup=order_keyboard) # Set the Live mode flag to True self.admin.live_mode = True # Commit the change to the database self.session.commit() while True: # Wait for any message to stop the listening mode update = self.__wait_for_inlinekeyboard_callback(cancellable=True) # If the user pressed the stop button, exit listening mode if isinstance(update, CancelSignal): # Stop the listening mode self.admin.live_mode = False break # Find the order order_id = re.search(self.loc.get("order_number").replace("{id}", "([0-9]+)"), update.message.text).group(1) order = self.session.query(db.Order).filter(db.Order.order_id == order_id).one() # Check if the order hasn't been already cleared if order.delivery_date is not None or order.refund_date is not None: # Notify the admin and skip that order self.bot.edit_message_text(self.chat.id, self.loc.get("error_order_already_cleared")) break # If the user pressed the complete order button, complete the order if update.data == "order_complete": # Mark the order as complete order.delivery_date = datetime.datetime.now() # Commit the transaction self.session.commit() # Update order message self.bot.edit_message_text(order.text(w=self, session=self.session), chat_id=self.chat.id, message_id=update.message.message_id) # Notify the user of the completition self.bot.send_message(order.user_id, self.loc.get("notification_order_completed", order=order.text(w=self, session=self.session, user=True))) # If the user pressed the refund order button, refund the order... elif update.data == "order_refund": # Ask for a refund reason reason_msg = self.bot.send_message(self.chat.id, self.loc.get("ask_refund_reason"), reply_markup=cancel_keyboard) # Wait for a reply reply = self.__wait_for_regex("(.*)", cancellable=True) # If the user pressed the cancel button, cancel the refund if isinstance(reply, CancelSignal): # Delete the message asking for the refund reason self.bot.delete_message(self.chat.id, reason_msg.message_id) continue # Mark the order as refunded order.refund_date = datetime.datetime.now() # Save the refund reason order.refund_reason = reply # Refund the credit, reverting the old transaction order.transaction.refunded = True # Update the user's credit order.user.recalculate_credit() # Commit the changes self.session.commit() # Update the order message self.bot.edit_message_text(order.text(w=self, session=self.session), chat_id=self.chat.id, message_id=update.message.message_id) # Notify the user of the refund self.bot.send_message(order.user_id, self.loc.get("notification_order_refunded", order=order.text(w=self, session=self.session, user=True))) # Notify the admin of the refund self.bot.send_message(self.chat.id, self.loc.get("success_order_refunded", order_id=order.order_id))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 printOrders(self, event):\n \n pass", "def show_orders():\n return 'hehe'"...
[ "0.6574558", "0.648389", "0.6458056", "0.63235164", "0.6024562", "0.6000915", "0.58774596", "0.58562595", "0.5821226", "0.57926875", "0.5701339", "0.56484294", "0.56124806", "0.55923426", "0.5532213", "0.54967296", "0.5465461", "0.54616153", "0.5444044", "0.54411405", "0.5434...
0.60052794
5
Edit manually the credit of an user.
def __create_transaction(self): log.debug("Displaying __create_transaction") # Make the admin select an user user = self.__user_select() # Allow the cancellation of the operation if isinstance(user, CancelSignal): return # Create an inline keyboard with a single cancel button cancel = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(self.loc.get("menu_all_cancel"), callback_data="cmd_cancel")]]) # Request from the user the amount of money to be credited manually self.bot.send_message(self.chat.id, self.loc.get("ask_credit"), reply_markup=cancel) # Wait for an answer reply = self.__wait_for_regex(r"(-? ?[0-9]{1,3}(?:[.,][0-9]{1,2})?)", cancellable=True) # Allow the cancellation of the operation if isinstance(reply, CancelSignal): return # Convert the reply to a price object price = self.Price(reply) # Ask the user for notes self.bot.send_message(self.chat.id, self.loc.get("ask_transaction_notes"), reply_markup=cancel) # Wait for an answer reply = self.__wait_for_regex(r"(.*)", cancellable=True) # Allow the cancellation of the operation if isinstance(reply, CancelSignal): return # Create a new transaction transaction = db.Transaction(user=user, value=int(price), provider="Manual", notes=reply) self.session.add(transaction) # Change the user credit user.recalculate_credit() # Commit the changes self.session.commit() # Notify the user of the credit/debit self.bot.send_message(user.user_id, self.loc.get("notification_transaction_created", transaction=transaction.text(w=self))) # Notify the admin of the success self.bot.send_message(self.chat.id, self.loc.get("success_transaction_created", transaction=transaction.text(w=self)))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_user():", "def put(self, user_id):\n self.conn = pecan.request.db_conn\n self.conn.change_billing_owner(request.context,\n project_id=self.project_id,\n user_id=user_id)", "def changeCredit(self,user_ids,credit...
[ "0.6661192", "0.65714896", "0.65669656", "0.6544167", "0.6401612", "0.63528997", "0.6336762", "0.6264219", "0.62244713", "0.62211", "0.6150543", "0.6060516", "0.6060171", "0.60547006", "0.6043055", "0.6015317", "0.60106575", "0.5998428", "0.5996882", "0.59488016", "0.59436214...
0.0
-1
Help menu. Allows the user to ask for assistance, get a guide or see some info about the bot.
def __help_menu(self): log.debug("Displaying __help_menu") # Create a keyboard with the user help menu keyboard = [[telegram.KeyboardButton(self.loc.get("menu_guide"))], [telegram.KeyboardButton(self.loc.get("menu_contact_shopkeeper"))], [telegram.KeyboardButton(self.loc.get("menu_all_cancel"))]] # Send the previously created keyboard to the user (ensuring it can be clicked only 1 time) self.bot.send_message(self.chat.id, self.loc.get("conversation_open_help_menu"), reply_markup=telegram.ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)) # Wait for a reply from the user selection = self.__wait_for_specific_message([ self.loc.get("menu_guide"), self.loc.get("menu_contact_shopkeeper") ], cancellable=True) # If the user has selected the Guide option... if selection == self.loc.get("menu_guide"): # Send them the bot guide self.bot.send_message(self.chat.id, self.loc.get("help_msg")) # If the user has selected the Order Status option... elif selection == self.loc.get("menu_contact_shopkeeper"): # Find the list of available shopkeepers shopkeepers = self.session.query(db.Admin).filter_by(display_on_help=True).join(db.User).all() # Create the string shopkeepers_string = "\n".join([admin.user.mention() for admin in shopkeepers]) # Send the message to the user self.bot.send_message(self.chat.id, self.loc.get("contact_shopkeeper", shopkeepers=shopkeepers_string)) # If the user has selected the Cancel option the function will return immediately
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def help(update, context):\n update.message.reply_text(\n 'Do you want to request help or offer help? '\n 'Type /mainmenu command for more details.'\n )", "def help():\n print(UI.HELP)", "def help():\n print \"Help comes to those who ask\"", "def help_menu():\n print('\\n####...
[ "0.81145465", "0.8089697", "0.80051744", "0.7843313", "0.77846485", "0.77716464", "0.777118", "0.7751202", "0.7710961", "0.7703892", "0.7681212", "0.7665433", "0.7643646", "0.7633848", "0.7633848", "0.76275283", "0.7623624", "0.7623624", "0.7623624", "0.7623624", "0.76041985"...
0.75867516
21
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 while True: # Retrieve the 10 transactions in that page transactions = self.session.query(db.Transaction) \ .order_by(db.Transaction.transaction_id.desc()) \ .limit(10) \ .offset(10 * page) \ .all() # Create a list to be converted in inline keyboard markup inline_keyboard_list = [[]] # Don't add a previous page button if this is the first page if page != 0: # Add a previous page button inline_keyboard_list[0].append( telegram.InlineKeyboardButton(self.loc.get("menu_previous"), callback_data="cmd_previous") ) # Don't add a next page button if this is the last page if len(transactions) == 10: # Add a next page button inline_keyboard_list[0].append( telegram.InlineKeyboardButton(self.loc.get("menu_next"), callback_data="cmd_next") ) # Add a Done button inline_keyboard_list.append( [telegram.InlineKeyboardButton(self.loc.get("menu_done"), callback_data="cmd_done")]) # Create the inline keyboard markup inline_keyboard = telegram.InlineKeyboardMarkup(inline_keyboard_list) # Create the message text transactions_string = "\n".join([transaction.text(w=self) for transaction in transactions]) text = self.loc.get("transactions_page", page=page + 1, transactions=transactions_string) # Update the previously sent message self.bot.edit_message_text(chat_id=self.chat.id, message_id=message.message_id, text=text, reply_markup=inline_keyboard) # Wait for user input selection = self.__wait_for_inlinekeyboard_callback() # If Previous was selected... if selection.data == "cmd_previous" and page != 0: # Go back one page page -= 1 # If Next was selected... elif selection.data == "cmd_next" and len(transactions) == 10: # Go to the next page page += 1 # If Done was selected... elif selection.data == "cmd_done": # Break the loop break
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def transaction_list(request, model_class=Transaction, template_name='budget/transactions/list.html'):\n transaction_list = model_class.active.order_by('-date', '-created')\n try:\n paginator = Paginator(transaction_list, getattr(settings, 'BUDGET_LIST_PER_PAGE', 50))\n page = paginator.page(re...
[ "0.688372", "0.6692908", "0.65745246", "0.65152967", "0.6440288", "0.6437697", "0.6429272", "0.6316394", "0.628526", "0.6220077", "0.6215298", "0.61452043", "0.6122129", "0.6120994", "0.6119554", "0.60814244", "0.6068557", "0.60655093", "0.60478973", "0.60313505", "0.6014012"...
0.76497626
0
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"transactions_{self.chat.id}.csv", "x"): pass except IOError: pass # Write on the previously created file with open(f"transactions_{self.chat.id}.csv", "w") as file: # Write an header line file.write(f"UserID;" f"TransactionValue;" f"TransactionNotes;" f"Provider;" f"ChargeID;" f"SpecifiedName;" f"SpecifiedPhone;" f"SpecifiedEmail;" f"Refunded?\n") # For each transaction; write a new line on file for transaction in transactions: file.write(f"{transaction.user_id if transaction.user_id is not None else ''};" f"{transaction.value if transaction.value is not None else ''};" f"{transaction.notes if transaction.notes is not None else ''};" f"{transaction.provider if transaction.provider is not None else ''};" f"{transaction.provider_charge_id if transaction.provider_charge_id is not None else ''};" f"{transaction.payment_name if transaction.payment_name is not None else ''};" f"{transaction.payment_phone if transaction.payment_phone is not None else ''};" f"{transaction.payment_email if transaction.payment_email is not None else ''};" f"{transaction.refunded if transaction.refunded is not None else ''}\n") # Describe the file to the user self.bot.send_message(self.chat.id, self.loc.get("csv_caption")) # Reopen the file for reading with open(f"transactions_{self.chat.id}.csv") as file: # Send the file via a manual request to Telegram requests.post(f"https://api.telegram.org/bot{self.cfg.telegram['token']}/sendDocument", files={"document": file}, params={"chat_id": self.chat.id, "parse_mode": "HTML"}) # Delete the created file os.remove(f"transactions_{self.chat.id}.csv")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def print_customers(self):\n output = ''\n for i in range(len(self.customers)):\n output += f'Customer no. {self.customers[i].id} is in {self.customers[i].state[0]} section\\n'\n #print(output)\n with open('oneday.csv','a') as outfile:\n for i in range(len(self.cus...
[ "0.66963094", "0.6593577", "0.6530911", "0.6499839", "0.647537", "0.63679814", "0.63550764", "0.63113767", "0.6298641", "0.6165292", "0.615324", "0.6120086", "0.6116998", "0.61141175", "0.61109525", "0.6062832", "0.6051639", "0.60443205", "0.60440016", "0.60371464", "0.602755...
0.69846463
0
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 administrator admin = self.session.query(db.Admin).filter_by(user_id=user.user_id).one_or_none() if admin is None: # Create the keyboard to be sent keyboard = telegram.ReplyKeyboardMarkup([[self.loc.get("emoji_yes"), self.loc.get("emoji_no")]], one_time_keyboard=True) # Ask for confirmation self.bot.send_message(self.chat.id, self.loc.get("conversation_confirm_admin_promotion"), reply_markup=keyboard) # Wait for an answer selection = self.__wait_for_specific_message([self.loc.get("emoji_yes"), self.loc.get("emoji_no")]) # Proceed only if the answer is yes if selection == self.loc.get("emoji_no"): return # Create a new admin admin = db.Admin(user=user, edit_products=False, receive_orders=False, create_transactions=False, is_owner=False, display_on_help=False) self.session.add(admin) # Send the empty admin message and record the id message = self.bot.send_message(self.chat.id, self.loc.get("admin_properties", name=str(admin.user))) # Start accepting edits while True: # Create the inline keyboard with the admin status inline_keyboard = telegram.InlineKeyboardMarkup([ [telegram.InlineKeyboardButton( f"{self.loc.boolmoji(admin.edit_products)} {self.loc.get('prop_edit_products')}", callback_data="toggle_edit_products" )], [telegram.InlineKeyboardButton( f"{self.loc.boolmoji(admin.receive_orders)} {self.loc.get('prop_receive_orders')}", callback_data="toggle_receive_orders" )], [telegram.InlineKeyboardButton( f"{self.loc.boolmoji(admin.create_transactions)} {self.loc.get('prop_create_transactions')}", callback_data="toggle_create_transactions" )], [telegram.InlineKeyboardButton( f"{self.loc.boolmoji(admin.display_on_help)} {self.loc.get('prop_display_on_help')}", callback_data="toggle_display_on_help" )], [telegram.InlineKeyboardButton( self.loc.get('menu_done'), callback_data="cmd_done" )] ]) # Update the inline keyboard self.bot.edit_message_reply_markup(message_id=message.message_id, chat_id=self.chat.id, reply_markup=inline_keyboard) # Wait for an user answer callback = self.__wait_for_inlinekeyboard_callback() # Toggle the correct property if callback.data == "toggle_edit_products": admin.edit_products = not admin.edit_products elif callback.data == "toggle_receive_orders": admin.receive_orders = not admin.receive_orders elif callback.data == "toggle_create_transactions": admin.create_transactions = not admin.create_transactions elif callback.data == "toggle_display_on_help": admin.display_on_help = not admin.display_on_help elif callback.data == "cmd_done": break self.session.commit()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def addadmin(self, ctx, user: discord.Member):\n self.settings.addAdmin(user.id)\n await ctx.send(\"done\")", "def addAdmin(self, softwareProfileName, adminUsername):\n return self._sp_db_api.addAdmin(softwareProfileName, adminUsername)", "def cmd_addadmin_private(self, argument):\n ...
[ "0.7431501", "0.69612104", "0.69173306", "0.6861339", "0.6813076", "0.6811589", "0.6779468", "0.6773782", "0.67275375", "0.6693339", "0.6648171", "0.66383785", "0.66203934", "0.64802665", "0.63945043", "0.61657405", "0.6165614", "0.6116291", "0.60149425", "0.6012939", "0.6005...
0.74137247
1
Handle the graceful stop of the thread.
def __graceful_stop(self, stop_trigger: StopSignal): log.debug("Gracefully stopping the conversation") # If the session has expired... if stop_trigger.reason == "timeout": # Notify the user that the session has expired and remove the keyboard self.bot.send_message(self.chat.id, self.loc.get('conversation_expired'), reply_markup=telegram.ReplyKeyboardRemove()) # If a restart has been requested... # Do nothing. # Close the database session self.session.close() # End the process sys.exit(0)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _gracefully_stop(self):\n pass", "def stop(self):\n self._Thread__stop()", "def stop(self):\n\n self.stop_thread = True", "def stop() -> None:", "def stop(self):\n if not self._thread or self._abort:\n return\n\n self._abort = True\n self._thread.join(...
[ "0.7860334", "0.7672749", "0.74662364", "0.7418597", "0.7404036", "0.7361285", "0.73441213", "0.73351604", "0.7304599", "0.72947305", "0.7282064", "0.7271645", "0.7259077", "0.7259077", "0.7259077", "0.7259077", "0.7231936", "0.7217294", "0.7211812", "0.72087836", "0.7206629"...
0.0
-1
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 frame, skipping." # # Okay to return 'STRAIGHT' here because the thresholding error will cause the # # speed calculator to bail out and we'll skip the frame. # return 'STRAIGHT' pil_image = Image.fromarray(thresh, 'L') width, height = pil_image.size raw = pil_image.tostring() # wrap image data image = zbar.Image(width, height, 'Y800', raw) # scan the image for barcodes scanResult = scanner.scan(image) if scanResult: for symbol in image: # do something useful with results print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data report_data_to_webserver(symbol.data) if symbol.data == code: return 'STOP' # if QR code found, and QR code text is the desired destination, return stop return 'STRAIGHT' # Can be one of STRAIGHT, STOP.
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def camera_frame_directions(self) -> _BFRAME_TYPE:\n pass", "def camera_frame_directions(self) -> _BFRAME_TYPE:\n\n return self._base_frame_directions", "def get_direction(position, next_position):\n x, y = position\n next_x, next_y = next_position\n if x == next_x:\n if y < next_...
[ "0.694612", "0.6346096", "0.6220887", "0.61938536", "0.6123104", "0.606547", "0.60267913", "0.59429306", "0.5911182", "0.5875572", "0.5870038", "0.5853388", "0.5850153", "0.5848268", "0.5836786", "0.58342284", "0.5824965", "0.58235735", "0.58171266", "0.5813398", "0.5795338",...
0.6649756
1
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.threshold(thresh, BW_THRESHOLD, 255, cv2.THRESH_BINARY) if not success: print "Could not threshold frame, skipping." return None ### edge detection. constants here are magic canny = cv2.Canny(thresh, 180, 220, apertureSize = 3) ### contour detection contours, _ = cv2.findContours(canny,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) if len(contours) < 1: return None sorted_contours = sorted(contours, key=lambda x:cv2.arcLength(x,False), reverse=True) ## JUST FOR TESTING # longest contours if DEBUG_MODE: cv2.drawContours(im,sorted_contours[0:2],-1,(0,255,0),3) # draw longest contour cv2.imshow('lines',im) k = cv2.waitKey(5) if k == 27: cv2.destroyAllWindows() return None ### Find x coordinates of endpoints if len(sorted_contours) == 0: print "No contours found, skipping" return None # get points for the longest contours mask = numpy.zeros(im.shape,numpy.uint8) cv2.drawContours(mask,[sorted_contours[0]],0,255,-1) pixelpoints = numpy.transpose(numpy.nonzero(mask)) xTop_one = pixelpoints[0][1] # IMPORTANT: pixelpoints is returned in row, column format xBottom_one = pixelpoints[-1][1] ## IMPORTANT TODO: assumes points are returned sorted, need to verify if len(sorted_contours) > 1: # we have more than one contour mask = numpy.zeros(im.shape,numpy.uint8) cv2.drawContours(mask,[sorted_contours[1]],0,255,-1) pixelpoints = numpy.transpose(numpy.nonzero(mask)) xTop_two = pixelpoints[0][1] # IMPORTANT: pixelpoints is returned in row, column format xBottom_two = pixelpoints[-1][1] ## IMPORTANT TODO: assumes points are returned sorted, need to verify # average two longest contours if available if len(sorted_contours) == 1: xTop = xTop_one xBottom = xBottom_one else: xTop = (xTop_one + xTop_two) / 2 xBottom = (xBottom_one + xBottom_two) / 2 ### Calculate offset to return ### (XTop - XBottom) + (XTop - CENTER) ### CENTER = TRUE_CENTER - CENTER_OFFSET MOST_POSITIVE_VAL = 3*len(im[0])/2 + CENTER_OFFSET MOST_NEGATIVE_VAL = -3*len(im[0])/2 + CENTER_OFFSET adjusted_midpoint = len(im[0])/2 - CENTER_OFFSET #unscaled_error = xTop - xBottom + 2*(xTop - adjusted_midpoint) unscaled_error = xTop - adjusted_midpoint if unscaled_error == 0: return 0.0 if unscaled_error > 0: scaled_error = float(unscaled_error)/MOST_POSITIVE_VAL if abs(scaled_error) > 1.0: print "Warning: scaled_error value greater than 1.0: " + scaled_error return min(scaled_error, 1.0) else: scaled_error = float(unscaled_error)/abs(MOST_NEGATIVE_VAL) if abs(scaled_error) > 1.0: print "Warning: scaled_error value less than -1.0: " + scaled_error return max(scaled_error, -1.0)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_linear_track_error(self):\r\n return self._arm.get_linear_track_error()", "def error(line, data): # error function\n # Metric: Sum of squared Y-axis differences\n err = np.sum((data[:, 1] - (line[0] * data[:, 0] + line[1])) ** 2)\n return err", "def error(self) -> Sequence[float]:\n ...
[ "0.6348194", "0.6194607", "0.6192224", "0.5972827", "0.5821756", "0.58052456", "0.57963437", "0.5735557", "0.5705652", "0.5681445", "0.5633082", "0.5596675", "0.55598956", "0.5546809", "0.5519722", "0.54857236", "0.5475193", "0.54616123", "0.5458455", "0.54289025", "0.5419931...
0.67456424
0
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)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 ...
[ "0.6475174", "0.63403714", "0.5990031", "0.5899495", "0.5873651", "0.58731246", "0.5788477", "0.57712096", "0.57585996", "0.5747586", "0.57444304", "0.56175065", "0.56138253", "0.5610825", "0.56059897", "0.55898684", "0.55860823", "0.5576143", "0.5572634", "0.5566797", "0.554...
0.6958017
0
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
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, name, number):\n self._name = name\n self._scores = []", "def __init__(self, name, age, student_id, courses):\n self.name = name\n self.age = age\n self.student_id = student_id\n self.courses = courses\n\n # When adding a student, increment the\n ...
[ "0.68761146", "0.6798942", "0.660163", "0.65491754", "0.6526323", "0.64837736", "0.64603394", "0.64021593", "0.6373097", "0.61487335", "0.59534216", "0.5864722", "0.58540154", "0.5832365", "0.5794798", "0.5733008", "0.5677068", "0.5636913", "0.56352925", "0.5627736", "0.55593...
0.687974
0
Score mutator method for the ith score associated with this Student when counting from 1.
def set_score(self, score_index: int, score: float) -> None: self._scores[score_index - 1] = score
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def increase_score(self):\n self.score += 1", "def update_score(self, score: int) -> int:\n self.score += score\n return self.score", "def updateScore(score):\n return score + 1", "def setScore(self, i, score):\n self.scores[i - 1] = score", "def score(self,*val):\n ...
[ "0.70036244", "0.6742975", "0.6676984", "0.6661092", "0.6641394", "0.6575926", "0.65411323", "0.65216136", "0.6519746", "0.64972997", "0.6493494", "0.6438079", "0.63984686", "0.6353655", "0.62839943", "0.6275106", "0.6257251", "0.62530357", "0.6208738", "0.6191476", "0.619147...
0.5942013
47
Score accessor method for the ith score associated with this Student when counting from 1.
def get_score(self, score_index) -> float: return self._scores[score_index - 1]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getScore(self, i):\n return self.scores[i - 1]", "def score(self):\n return self.aggregate(Sum('score')).values()[0] or 0", "def getScore(self):\r\n return self._score", "def get_score(self):\n return self.__score", "def __get_score(self):\n for pair in zip(self.nu[se...
[ "0.7540916", "0.71304154", "0.70693535", "0.70315707", "0.701489", "0.69717175", "0.69717175", "0.69717175", "0.6944495", "0.6929674", "0.6920036", "0.6920036", "0.6920036", "0.6913361", "0.69107527", "0.6869199", "0.68118626", "0.68063027", "0.6723587", "0.6710663", "0.66818...
0.65082026
25
Calculate the average score associated with this Student.
def get_average(self) -> float: return sum(self._scores) / len(self._scores)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getAverage(self):\n return sum(self.scores) / len(self.scores)", "def get_mean_score(rating_scores):\n return sum(rating_scores) / len(rating_scores)", "def get_average(self):\n self.avg = math.floor((self.maths + self.phy + self.che) / 3, )\n self.assign_grade()\n return self....
[ "0.79639894", "0.73673606", "0.7196625", "0.71720856", "0.7162906", "0.71442413", "0.70670134", "0.7030095", "0.7030095", "0.6999512", "0.69382113", "0.69370216", "0.6887286", "0.68780196", "0.6849795", "0.6842055", "0.6833306", "0.6798177", "0.6760756", "0.6755839", "0.67513...
0.78896713
1
Determine the highest score associated with this Student.
def get_high_score(self) -> float: return max(self._scores)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def max_score(self):\n return max(self._extract_set('score') or [0])", "def max_score(self):\r\n max_score = None\r\n if self.check_if_done_and_scored():\r\n max_score = self._max_score\r\n return max_score", "def max_score(self):\r\n return self.lcp.get_max_score(...
[ "0.83337474", "0.8101874", "0.8077302", "0.7876038", "0.77509063", "0.76949257", "0.7678623", "0.7557908", "0.75277", "0.74828833", "0.74728924", "0.7361729", "0.73598534", "0.72938806", "0.7234977", "0.7211712", "0.71563286", "0.71198565", "0.7111701", "0.705322", "0.6986172...
0.7729899
5
Return a string representation of this Student.
def __str__(self): return "Name: " + self._name + "\nScores: " + \ " ".join(map(str, self._scores))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __str__(self):\n return \"student:\"+str(self.name)+\":\"+str(self.age)+\":\"+str(self.major)", "def __repr__(self):\n return '<Student {} {}>'.format(self.first_name, self.last_name)", "def __str__(self):\n return str(self.__student_name) + \" has grade \" + str(self.__grade_value) + ...
[ "0.8295279", "0.8067471", "0.80281967", "0.7977395", "0.78083307", "0.7451962", "0.74332565", "0.7343133", "0.7335651", "0.7317649", "0.72505677", "0.71951485", "0.7184829", "0.7166743", "0.71408", "0.71276385", "0.70470107", "0.7046271", "0.7036447", "0.70241964", "0.7015336...
0.6967568
26
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()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, numerator, denominator=1):\n if (type(numerator) not in(int,float)):\n raise ValueError('Numerator must be a number')\n if (type(denominator) not in(int,float)):\n raise ValueError('Denominator must be a number')\n if denominator == 0:\n if n...
[ "0.7272838", "0.71475744", "0.6812566", "0.6804737", "0.6622814", "0.6595566", "0.6460698", "0.6444287", "0.64000016", "0.6399492", "0.63688904", "0.6362692", "0.6287831", "0.62010443", "0.60404706", "0.5914123", "0.57778704", "0.5751536", "0.5651751", "0.560133", "0.5544102"...
0.7570159
0
Returns the string representation of the number.
def __str__(self) -> str: return str(self._numerator) + "/" + str(self._denominator)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def serialize_number(n):\n return str(n)", "def to_str(n: float) -> str:\n return str(n)", "def __str__(self):\n if self.is_int():\n return str(self._num)\n else:\n return \"{0:d} / {1:d}\".format(self._num, self._den)", "def num2str(num):\n require_type(is_number...
[ "0.7852776", "0.75852734", "0.7521407", "0.7276308", "0.7240839", "0.7099867", "0.6933715", "0.69164", "0.68163884", "0.6783753", "0.67737114", "0.67629415", "0.67622906", "0.6759685", "0.6732823", "0.6702986", "0.664432", "0.663952", "0.6626828", "0.66028976", "0.65981984", ...
0.0
-1
Helper to reduce the number to lowest terms. Note that the name with the "_" prefix suggests this is a private method.
def _reduce(self) -> None: divisor = self._gcd(self._numerator, self._denominator) self._numerator = self._numerator // divisor self._denominator = self._denominator // divisor
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def minuend(term):\n keys = sorted(ROMAN_NUMERALS.keys())\n _, factor = term\n next_factor = keys[keys.index(factor) + 1]\n return (1, next_factor)", "def get_minimum_completion_terms(self):\n return # osid.search.terms.DecimalTerm", "def w_smallest_factor(n): \n if n == 1: return 1 \n ...
[ "0.58530545", "0.57762897", "0.57697564", "0.5685307", "0.5636156", "0.5618494", "0.5616832", "0.5483862", "0.53706306", "0.53027964", "0.5292956", "0.5285909", "0.527761", "0.52535427", "0.5252241", "0.52403617", "0.5237393", "0.5229099", "0.5223622", "0.51947016", "0.518343...
0.51925606
20
Euclid's algorithm for greatest common divisor. Note that the name with the "_" prefix suggests this is a private method.
def _gcd(self, a, b) -> int: (a, b) = (max(a, b), min(a, b)) while b > 0: (a, b) = (b, a % b) return a
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def gcd_algo(a,b):\n i = max(a,b)\n j = min(a,b)\n\n if j == 0:\n return i\n else:\n reminder = i%j\n return gcd_algo(j, reminder)", "def GCD(a, b) -> int:\n\n if a == 0:\n return b\n\n return GCD(b % a, a)", "def gcd(x,y):\n\tif x%y == 0:\n\t\treturn y\n\treturn g...
[ "0.7671515", "0.7312333", "0.7256305", "0.724105", "0.7235655", "0.7207824", "0.71932334", "0.7182065", "0.71724474", "0.7158568", "0.7141855", "0.71127653", "0.71068764", "0.70938784", "0.70918316", "0.70913225", "0.70769143", "0.7075322", "0.70682853", "0.7053909", "0.70469...
0.6908812
53
Returns the sum of the numbers.
def __add__(self, other): new_numerator = self._numerator * other.denominator() + other.numerator() * self._denominator new_denominator = self._denominator * other.denominator() return Rational(new_numerator, new_denominator)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sum_of_numbers(numbers):\r\n return sum(numbers)", "def sum_numbers(numbers):\n sum = 0\n for number in numbers:\n sum += number\n\n return sum", "def summation(self):\n return sum(self.read_ints())", "def sum_numbers(numbers=None):\n if numbers is None:\n return sum(r...
[ "0.8825344", "0.8238869", "0.7952014", "0.7763446", "0.7756542", "0.7728122", "0.7661659", "0.75208676", "0.7503312", "0.74527943", "0.7342912", "0.73273593", "0.72723556", "0.72645986", "0.7262699", "0.7250479", "0.7220776", "0.71955884", "0.7181855", "0.71736866", "0.717216...
0.0
-1
Returns self < other.
def __lt__(self, other): extremes = self._numerator * other.denominator() means = other.numerator() * self._denominator return extremes < means
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __lt__(self, other):\n return self <= other and self != other", "def __lt__(self, other):\n return self <= other and self != other", "def __lt__(self, other):\n return self <= other and not self >= other", "def __lt__(self, other):\n return self.__cmp__(other) < 0", "def __l...
[ "0.88831526", "0.88831526", "0.88809276", "0.88266224", "0.87825954", "0.87616193", "0.8735927", "0.86838645", "0.86838645", "0.85984594", "0.8593426", "0.8587446", "0.85867065", "0.85752547", "0.85608375", "0.85526484", "0.85441566", "0.85100424", "0.85084605", "0.8507573", ...
0.79021734
98
Returns self >= other.
def __ge__(self, other): extremes = self._numerator * other.denominator() means = other.numerator() * self._denominator return extremes >= means
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __ge__(self, other):\n return other <= self", "def __gt__(self, other):\n return self >= other and self != other", "def __gt__(self, other):\n return self >= other and self != other", "def __gt__(self, other):\n return self >= other and not self <= other", "def __gt__(self, ...
[ "0.8782747", "0.8661218", "0.8661218", "0.8599558", "0.8597423", "0.85728633", "0.85680884", "0.85315", "0.852308", "0.85042644", "0.84803677", "0.84770334", "0.84770334", "0.8403545", "0.8370605", "0.8354243", "0.8347908", "0.8347908", "0.8346253", "0.832667", "0.8312259", ...
0.0
-1
Tests self and other for equality.
def __eq__(self, other): if self is other: return True elif not isinstance(other, Rational): return False else: return self._numerator == other.numerator() and \ self._denominator == other.denominator()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __eq__(self, other):\n return are_equal(self, other)", "def __eq__(self, other):\n return are_equal(self, other)", "def __eq__(self, other):\n return equal(self, other)", "def __eq__(self, other):\n return self is other", "def __eq__(self, other):\n return self is oth...
[ "0.88391733", "0.88391733", "0.88139397", "0.86130553", "0.86130553", "0.855895", "0.85263485", "0.85263485", "0.8492665", "0.84854174", "0.84620726", "0.84174746", "0.84174746", "0.839733", "0.839733", "0.839733", "0.83951354", "0.837963", "0.83764756", "0.8330343", "0.83218...
0.0
-1
Returns the string rep.
def __str__(self) -> str: result = 'Name: ' + self._name + '\n' result += 'PIN: ' + self._pin + '\n' result += 'Balance: ' + str(self._balance) return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_str_repr(self, sons_repr):\n raise NotImplementedError", "def __str__(self):\n rep = \"\"\n for row in self._marker:\n for pegs in row:\n rep += pegs + \" \"\n rep = rep[:-1]\n rep += \"\\n\"\n rep = rep[:-1]\n return rep"...
[ "0.6432497", "0.63806415", "0.6324218", "0.6302801", "0.62511474", "0.6244673", "0.62421393", "0.62186795", "0.6171946", "0.6129963", "0.6103834", "0.6085116", "0.6054438", "0.604575", "0.6018557", "0.6005429", "0.59968317", "0.59697354", "0.5946744", "0.5946734", "0.59276056...
0.0
-1
Returns the current balance.
def get_balance(self) -> float: return self._balance
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getCurrentBalance(self):\r\n return self.balance_amt", "def get_balance(self):\n print(f\"Your current balance is: ${self.balance}\")\n return self.balance", "def get_balance(self):\n return self.balance", "def get_balance(self):\n return self.balance", "def get_balan...
[ "0.90873855", "0.89610255", "0.89417535", "0.89417535", "0.8915506", "0.8888199", "0.8761176", "0.875481", "0.8727912", "0.87268084", "0.8593401", "0.84702593", "0.84124166", "0.8334445", "0.833382", "0.8242796", "0.8183094", "0.81340134", "0.81279635", "0.8112718", "0.809195...
0.87366074
8
Returns the current name.
def get_name(self) -> str: return self._name
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def curr_name(self):\n return self.name_stack[-1]", "def current_name(self):\n return self.name_set.order_by('-vote')[0]", "def _get_name(self):\n return self.name", "def get_name(self):\n\t\treturn self.__name", "def get_name(self):\n\t\treturn self.name", "def get_name(self):\n\t\t...
[ "0.839696", "0.8132477", "0.81197184", "0.81005734", "0.8076262", "0.8076262", "0.8076262", "0.80644476", "0.8061161", "0.8057956", "0.80108416", "0.80108416", "0.80108416", "0.80076075", "0.79934263", "0.79934263", "0.799236", "0.79909116", "0.79909116", "0.79909116", "0.799...
0.8039769
11
Returns the current pin.
def get_pin(self) -> str: return self._pin
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pin(self) -> int:", "async def get_pin_thread(self) -> int:\n return await self.AD.threading.get_pin_thread(self.name)", "def get_current_address(self):\n pass", "def read(self):\n if self.mode == UNAVAILABLE:\n raise IOError, \"Cannot read pin %s\"% self.__str__()\n ...
[ "0.68164206", "0.6619968", "0.64361113", "0.64119536", "0.632375", "0.6322167", "0.62348837", "0.6177347", "0.6095625", "0.6095085", "0.6087233", "0.6051547", "0.6041345", "0.6023839", "0.59682727", "0.59486204", "0.59245473", "0.59245473", "0.59241426", "0.59072316", "0.5895...
0.80345154
0
If the amount is valid, adds it to the balance and returns None; otherwise, returns an error message.
def deposit(self, amount) -> None: self._balance += amount return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def withdraw(self, amount):\n if amount < 0:\n return \"Amount must be >= 0\"\n elif self._balance < amount:\n return \"Insufficient funds\"\n else:\n self._balance -= amount\n return None", "async def test_fail_neagative_amount(self, conn, user_wi...
[ "0.6857908", "0.6527119", "0.65165645", "0.6465434", "0.62706786", "0.6237382", "0.6097923", "0.60838354", "0.60811895", "0.60721636", "0.6069746", "0.60048103", "0.6002599", "0.5988065", "0.5959793", "0.5943059", "0.5926134", "0.58786637", "0.5861162", "0.58314705", "0.57749...
0.5872688
18
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
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 ],\...
[ "0.6829546", "0.665555", "0.6612244", "0.65875065", "0.6495299", "0.6483181", "0.62700593", "0.6266016", "0.622912", "0.62264717", "0.6190278", "0.6178433", "0.603522", "0.6021789", "0.6011362", "0.5971348", "0.5929509", "0.5925402", "0.59032834", "0.5886347", "0.5868926", ...
0.7301331
0
Computes, deposits, and returns the interest.
def compute_interest(self) -> float: interest = self._balance * SavingsAccount.RATE self.deposit(interest) return interest
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def total_interest(self):\n return sum(self.table[\"interest\"])", "def total_interest(self) -> Decimal:\n return self._quantize(self.schedule(int(self.term / self.term_multiplier * self.n_periods)).total_interest)", "def investment(principal, interest):\r\n while True:\r\n principal *= (1 + ...
[ "0.6494362", "0.6311625", "0.6234926", "0.61784625", "0.61245126", "0.5884585", "0.5769434", "0.57603633", "0.5738999", "0.5728413", "0.57176214", "0.5580446", "0.5550851", "0.5508479", "0.55062574", "0.54875445", "0.54787284", "0.54710907", "0.54048574", "0.5400234", "0.5348...
0.74920017
0
Fire off the HTTP request and do some minimal processing to the response.
def _send_request(self, endpoint, data=None, files=None): if files: [f.seek(0) for f in files.values()] url = "%s/%s/%d/%s" % (Client.HOST, self._layer, Client.VERSION, endpoint) response = requests.post(url, data=data, files=files) response = json.loads(response.text) if response['status'] != "success": raise Exception(". ".join(response['response']['errors'])) return response['response']
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _process_request(self):\n if not self._requests:\n if self._stream:\n self._stream.close()\n self._stream = None\n if self._processing:\n self._processing = False\n Engine.instance().stop()\n return\n\n r...
[ "0.6980107", "0.69255376", "0.6635801", "0.6631719", "0.65877926", "0.6560936", "0.6545937", "0.6526673", "0.6461472", "0.6422519", "0.6411226", "0.6379607", "0.63789254", "0.6336954", "0.6302776", "0.6283035", "0.6252244", "0.6216583", "0.61743015", "0.61365104", "0.6128585"...
0.0
-1
Sentiment analysis as performed by the text API returns a float value between 5.0 and 5.0 with 0 being neutral in tone (or no sentiment could be extracted), 5.0 being the happiest little piece of text in the world, and 5.0 being the kind of text that really should seek anger management counseling!
def sentiment(self, text): response = self._send_request("sentiment", dict(text=text)) return response[self._layer]['sentiment']
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sentiment(text):\n words = pattern_split.split(text.lower())\n sentiments = map(lambda word: afinn.get(word, 0), words)\n if sentiments:\n # How should you weight the individual word sentiments? \n # You could do N, sqrt(N) or 1 for example. Here I use sqrt(N)\n sentiment = float(...
[ "0.7846622", "0.7837771", "0.7431363", "0.7297572", "0.71922904", "0.7188018", "0.71867007", "0.71806484", "0.71513736", "0.7127188", "0.71200186", "0.7069672", "0.706835", "0.7044086", "0.7001954", "0.70002735", "0.6977773", "0.69415396", "0.69295526", "0.68922424", "0.68787...
0.68016964
25
The tagging functions looks for the uncommon keywords in a text and uses the strongest keywords (with the help of natural language processing) to 'tag' content. This effectively allows you to algorithmically group content with related keywords together.
def tagging(self, text): response = self._send_request("tagging", dict(text=text)) return response[self._layer]['tags']
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tagging (tagged_dataset, sentence) :\n tagged = open(tagged_dataset, \"rb\")\n tagged_ingredients = pickle.load(tagged)\n\n back = nltk.DefaultTagger('COMMENT')\n unigram_tagger = nltk.UnigramTagger(tagged_ingredients,backoff=back)\n bigram_tagger = nltk.BigramTagger(tagged_ingredients, backoff=...
[ "0.6449997", "0.64192873", "0.63424283", "0.63053626", "0.6268881", "0.62442225", "0.61591655", "0.61581814", "0.6112898", "0.60951704", "0.6082316", "0.6081004", "0.6027988", "0.5993292", "0.5943568", "0.593412", "0.5901994", "0.58818734", "0.58473915", "0.5768074", "0.57671...
0.61414534
8
Location disambiguation is a technique that uses a series of clues to locate places an item of text might be referring to (or where the user creating the text is located). This is done using natural language processing where using meta data has failed to offer useful location data.
def locations(self, text): response = self._send_request("locations", dict(text=text)) return response[self._layer]['locations']
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def disambiguate_location(rawName, lang='en'):\n \n response_json = wa.request_entity_fishing_short(rawName, lang)\n \n if not response_json:\n return nan,nan\n\n if 'entities' not in response_json.keys():\n return nan,nan\n \n sorted_entities = sorted(response_json['entities'], k...
[ "0.6621246", "0.58583206", "0.58583206", "0.5737894", "0.5719332", "0.5686192", "0.5591093", "0.5517193", "0.5502572", "0.5389947", "0.5345915", "0.5325403", "0.53181684", "0.5314771", "0.5291176", "0.5287399", "0.5227006", "0.5217714", "0.5180626", "0.5164771", "0.51473796",...
0.0
-1
This call allows you to send one request to all three API functions (sentiment, tagging, and location). The response is neatly packaged JSON.
def bundle(self, text): response = self._send_request("bundle", dict(text=text)) return response[self._layer]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sentiment():\n\n request_json = request.json\n power = request_json['power']\n angle = request_json['angle']\n\n print(power, angle)\n\n resp_dict = dict()\n resp_dict['kick'] = 'ok'\n\n resp = Response(json.dumps(resp_dict), status=200)\n\n return resp", "def sentiments_endpoint(requ...
[ "0.66516685", "0.642455", "0.63272727", "0.61078084", "0.5720824", "0.56985885", "0.56763154", "0.5625992", "0.56161004", "0.56093013", "0.55476886", "0.554564", "0.5541719", "0.5520359", "0.549266", "0.54899776", "0.54874516", "0.54707843", "0.54628474", "0.5443162", "0.5431...
0.0
-1
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']
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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.lights))", "def retrieveColor(image):\n w, h, dim = image.shape\n ret = np.zeros((w, h,...
[ "0.7301836", "0.7018421", "0.683226", "0.6683104", "0.6672693", "0.6624762", "0.6596658", "0.6569393", "0.646526", "0.646526", "0.63765454", "0.63485533", "0.6336055", "0.63002443", "0.6296228", "0.625343", "0.6228482", "0.6222722", "0.62008834", "0.61840725", "0.6144083", ...
0.7611546
0
In image processing, a color histogram is a representation of the distribution of colors in an image. Histogram is not to be confused with the Color function, in that it returns color samples and positioning (as opposed to only colors).
def histogram(self, image): response = self._send_request("histogram", files=dict(image=image)) return response[self._layer]['histogram']
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def color_hist(img, nbins=32): # Note : bins_range=(0, 256) from lecture will not work\n # Compute the histogram of the colour channesl separately\n channel1_hist = np.histogram(img[:, :, 0], bins=nbins)\n channel2_hist = np.histogram(img[:, :, 1], bins=nbins)\n channel3_hist = np.histogram(img[:, :, ...
[ "0.7525601", "0.7343939", "0.7306", "0.72479075", "0.7211033", "0.7108611", "0.7085115", "0.7064498", "0.70397717", "0.70376056", "0.70325893", "0.69877666", "0.69656545", "0.69137645", "0.68814576", "0.680532", "0.67829645", "0.67117774", "0.6690855", "0.66871506", "0.668477...
0.6106918
65
This API function allows users to make attempts to parse readable text from image documents. This might be used to improve visual search techniques or autocategorize images when paired with the Tagging API function.
def ocr(self, image): response = self._send_request("ocr", files=dict(image=image)) return response[_Data._layer]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def process_images(text):\n # if text != None:\n if text is not None:\n soup = BeautifulSoup(str(text), 'html.parser')\n img = soup.img\n try:\n image = img['title']\n return image\n except (TypeError, KeyError):\n # print(img)\n pass", ...
[ "0.7120681", "0.6948957", "0.6817121", "0.6617801", "0.658289", "0.64444613", "0.64176923", "0.6401436", "0.6394596", "0.63324255", "0.62463063", "0.6240675", "0.6178922", "0.61606264", "0.61382556", "0.6072346", "0.60619056", "0.6047692", "0.60279036", "0.6019717", "0.598586...
0.5362571
81
This function allows users to identify objects within photo documents and get back the positioning of those objects relative to the document. Currently the algorithm is trained to universally identify human faces, however it can be trained to recognize anything.
def faces(self, image): response = self._send_request("faces", files=dict(image=image)) return response['objectdetection']
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_positions(self, image):\n\t\tH, W, _ = image.shape\n\t\tpos_list = self.apply_detection(image)\n\t\tdetections = {}\n\t\thasDetection = False\n\t\tfor i, L in enumerate(pos_list):\n\t\t\ttext, coordinates = L[0], L[1]\n\t\t\tfor x, y, w, h in coordinates:\n\t\t\t\tif x < 0 or y < 0 or x + w > W or \\\n\t\...
[ "0.64921784", "0.6385911", "0.6128633", "0.61109364", "0.5865325", "0.5774194", "0.5764386", "0.576332", "0.57559574", "0.57532126", "0.5725988", "0.5634258", "0.5624861", "0.5623403", "0.56156105", "0.56029713", "0.55903345", "0.5573313", "0.55719686", "0.55679655", "0.55564...
0.0
-1
This call allows you to send one request to all four API functions (color, histogram, OCR, and object detection). The response is neatly packaged JSON.
def bundle(self, image): response = self._send_request("bundle", files=dict(image=image)) return response[self._layer]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def api_call():\n\n json_str = load_input()\n output = {\n 'inputs': json_str,\n 'results': 'cool results'}\n\n return json.dumps(output), 200, {'Content-Type': 'text/plain;charset=utf-8'}", "def common_request():\n start_time = time.time()\n if not request.json or 'image' not in req...
[ "0.63698345", "0.605039", "0.59906274", "0.59650654", "0.5945807", "0.57983017", "0.57776237", "0.5719879", "0.56441814", "0.5588833", "0.5583858", "0.55494714", "0.5549459", "0.5538236", "0.5511886", "0.54965216", "0.54583126", "0.54571307", "0.5456814", "0.5424739", "0.5415...
0.0
-1
Create instances of each available layer.
def __init__(self): for layer in self._layer_class_map: setattr(self, layer, self._layer_class_map[layer]())
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build(self):\n\n layers = GiraffeLayer.get_all_structural()\n \n for layer in layers:\n\n self.add_objects_from_layer(layer)\n\n return self", "def init_layers(self):\n\n # get caching layers activated\n caching_layers = G3WCachingLayer.objects...
[ "0.676467", "0.6691837", "0.66686845", "0.64733326", "0.640632", "0.6375107", "0.6259991", "0.6259991", "0.6215809", "0.6148475", "0.6107703", "0.6078645", "0.606979", "0.60238254", "0.59650904", "0.59550387", "0.595401", "0.59325004", "0.5912907", "0.58784574", "0.5870248", ...
0.6919045
0
Get one from the tensor.
def get_value(self, indices): assert len(indices) == 3, indices if self.model_tensor is None: raise ValueError("Please set the tensor") return self.model_tensor[indices[0], indices[1], indices[2]]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getTensor(self):\n\t\treturn self.cur_tensor", "def get_tensor(name):\n if name.rfind(':') == -1:\n name += ':0'\n return tf.get_default_graph().get_tensor_by_name(name)", "def named_tensor(self, name):\n return self._tensor_name_to_result[name]", "def scalar(val: torch.Tensor):\n retu...
[ "0.71460956", "0.67891514", "0.65588135", "0.64748013", "0.6413598", "0.638628", "0.63685715", "0.62808436", "0.62593913", "0.6162621", "0.615739", "0.61546993", "0.61231315", "0.60698557", "0.60295755", "0.60068893", "0.6005453", "0.59869796", "0.59539455", "0.59465075", "0....
0.6247127
9
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
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def Update(self, value):\n self.SetValue(self.GetValue() + tf.cast(value, self.dtype))", "def Update(self, value):\n self.SetValue(self.GetValue() + tf.cast(value, self.dtype))", "def set_node_value(node: Node, value: np.ndarray):\n if node.type != 'Const':\n raise Exception('Can\\'t set value ...
[ "0.73305565", "0.73305565", "0.7164538", "0.7106505", "0.69294816", "0.6863438", "0.67309785", "0.6588569", "0.65452635", "0.6523065", "0.6523065", "0.6513894", "0.6425833", "0.6411298", "0.6411298", "0.63991857", "0.63785946", "0.6368179", "0.63664836", "0.6361774", "0.63610...
0.76344925
0
Return a function that computes the loss given model_tensor[indices].
def get_closure_loss(self, indices, key='loss'): def f(x=None, self=self, indices=indices[:], key=str(key)): if self.minibatch is None: raise ValueError("Please set the minibatch first") if self.model_tensor is None: raise ValueError("Please set the tensor") if self.hypers is None: raise ValueError("Please use gin to configure hyperparameters") if x is not None: self.set_value(indices=indices, val=x) result = loss_fcn_np(model_tensor=self.model_tensor, **self.hypers, **self.minibatch) return { 'loss': result[key] - self.to_subtract.get(key, 0.0), 'metrics': {**result, 'param': x} } return f
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def loss_fn(self, targets, outputs, model):", "def evaluate_loss(\n model,\n ds,\n loss_func_name = 'CE'\n):\n loss = 0\n if loss_func_name == 'CE':\n loss_func = tf.keras.losses.SparseCategoricalCrossentropy(\n reduction=tf.keras.losses.Reduction.SUM\n )\n else:\n raise ValueError(f'...
[ "0.70081395", "0.68642265", "0.6816249", "0.6587402", "0.64709276", "0.6390252", "0.6384351", "0.6262639", "0.6254914", "0.62301326", "0.6185378", "0.6116442", "0.61089265", "0.606172", "0.60404414", "0.5996247", "0.5978391", "0.59707904", "0.5964788", "0.59625316", "0.595526...
0.62363786
9
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)) return stats
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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...
[ "0.57875735", "0.5553495", "0.54737693", "0.54532033", "0.5412092", "0.5370195", "0.53218067", "0.52247834", "0.5223462", "0.5169793", "0.5165328", "0.5104045", "0.5101016", "0.51004094", "0.5073601", "0.50521386", "0.5042904", "0.50331867", "0.50312966", "0.5018096", "0.4991...
0.59009445
0
Given indices, use Golden Ratio search to compute the best model_tensor[indices].
def best_value_indices(self, indices, key='loss', assign_at_end=False, give_history=True): # remember the original value orig_value = self.get_value(indices=indices) # function to compute the loss loss_closure = self.get_closure_loss(indices=indices, key=key) orig_loss = loss_closure(orig_value)['loss'] # history of metrics history = [] def closure_with_history(x, give_history=give_history): """Given a value, compute the loss, store the value (optionally) and return by key.""" result = loss_closure(x) if give_history: history.append(result['metrics']) return result['loss'] params = {x: y for x, y in self.golden_params.items()} if 'smartbracket' in self.golden_params: del params['smartbracket'] params['brack'] = tuple([orig_value + t for t in self.golden_params['smartbracket']]) # running optimization best_value, best_loss, iterations = golden(closure_with_history, full_output=True, **params) # restoring the value if requested if not assign_at_end: self.set_value(indices=indices, val=orig_value) else: if best_loss < orig_loss: self.set_value(indices=indices, val=best_value) else: if not self.silent: logging.warning(f"No improvement {indices} {key} {assign_at_end}") self.set_value(indices=indices, val=orig_value) best_value = orig_value best_loss = orig_loss return { 'assigned': assign_at_end, 'history': history, 'orig_value_param': orig_value, 'best_value': best_value, 'best_loss': best_loss, 'iterations': iterations }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def score(self, indices):\n self.model.eval()\n _, prediction = self.model(self.propagation_matrix, self.features).max(dim=1)\n correct = prediction[indices].eq(self.target[indices]).sum().item()\n acc = correct / indices.shape[0]\n return acc", "def get_mrr(indices, targets, b...
[ "0.58714134", "0.572436", "0.54480314", "0.53884125", "0.5371206", "0.53582114", "0.5325242", "0.5228647", "0.5197329", "0.5135615", "0.51092374", "0.5090754", "0.50319535", "0.5003722", "0.49786648", "0.49672964", "0.49620736", "0.4949337", "0.4947537", "0.4934084", "0.49265...
0.47861862
35
Given a value, compute the loss, store the value (optionally) and return by key.
def closure_with_history(x, give_history=give_history): result = loss_closure(x) if give_history: history.append(result['metrics']) return result['loss']
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _value_loss(self, returns, value):\n\t\tvalue_loss = kls.mean_squared_error(returns, value)\n\t\treturn self.value_coef * value_loss", "def loss(self, objective, value, target, name=None):\n self[name] = Loss(objective, value, target, mask=self._mask)", "def update_loss(self, key: str, loss: torch.T...
[ "0.6277744", "0.5893046", "0.58930063", "0.5769844", "0.5739461", "0.5678636", "0.5649361", "0.56219304", "0.5600758", "0.5575944", "0.5558811", "0.5556036", "0.55385", "0.5531653", "0.55291396", "0.5521571", "0.5516635", "0.5504032", "0.54997915", "0.5477869", "0.54631454", ...
0.48552936
95
List of dictionaries > dictionary of lists.
def lstdct2dctlst(lst): keys = lst[0].keys() res = {key: [x[key] for x in lst] for key in keys} return res
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_list_of_dicts(self) -> List[Dict[str, Any]]:\n return [this.to_dict() for this in self._elements]", "def lists(self):\n return dict.items(self)", "def _defaultdict_of_lists():\n\n return collections.defaultdict(list)", "def to_listlist(list_dict):\n\n # Get headers\n headers = [...
[ "0.713634", "0.6847465", "0.6798456", "0.66922224", "0.6662882", "0.66356117", "0.66326165", "0.6599272", "0.6577951", "0.6513619", "0.6470066", "0.6470066", "0.6425155", "0.63617533", "0.6359895", "0.628654", "0.6232878", "0.62125826", "0.6202392", "0.61767447", "0.6175288",...
0.5867129
44
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=False, pbars=None, cancel_updates=False, **kwargs): # internal object IDs to update obj1 = mb_np_orig['objects_rating_v1'][idx_set] obj2 = mb_np_orig['objects_rating_v2'][idx_set] # copying the minibatch and the model tensor (will be updated) mb_np_copy = deepcopy(mb_np_orig) model_tensor_copy = deepcopy(model_tensor_orig) if not cancel_updates: # SETTING THE RATING VALUE mb_np_copy['cmp'][idx_set, 0] = rating_value # creating the updater online = FeaturelessOnlineUpdater() online.hypers['aggregate_index'] = -1 # hotfix parameter updates if hotfix_update_hypers is not None: for key, value in hotfix_update_hypers.items(): online.hypers[key] = value for key, value in kwargs.items(): online.golden_params[key] = value # setting data online.set_minibatch(mb_np_copy) online.set_model_tensor(model_tensor_copy) online.set_subtract() online.silent = True # CONFIGURATION FOR INDICES indices_lst = [] for i in range(model_tensor_orig.shape[0]): indices_lst.append((i, obj1, 0)) indices_lst.append((i, obj2, 0)) indices_lst *= n_repeats # initial value for the loss/index initial_value = {ind: online.get_closure_loss(ind)(online.get_value(ind)) for ind in set(indices_lst)} if not cancel_updates: # RUNNING OPTIMIZATION with GOLDEN RATIO result = online.best_value_many_indices(indices_lst, assign_at_end=True) # plotting if plot_charts: visualize_result_loss(result, indices_lst) visualize_byindex(result, indices_lst, initial_value) else: result = None if pbars is not None: if 'comparison' in pbars: assert len(users_get_value) == len(pbars['comparison']) for user, pbar in zip(users_get_value, pbars['comparison']): # obtaining model scores score1 = online.get_value((user, obj1, 0)) score2 = online.get_value((user, obj2, 0)) # computing the comparison comparison = 1 / (1 + np.exp(score1 - score2)) * MAX_VALUE pbar.value = comparison if 'v1' in pbars: assert len(users_get_value) == len(pbars['v1']) for user, pbar in zip(users_get_value, pbars['v1']): # obtaining model scores score1 = online.get_value((user, obj1, 0)) pbar.value = score1 if 'v2' in pbars: assert len(users_get_value) == len(pbars['v2']) for user, pbar in zip(users_get_value, pbars['v2']): # obtaining model scores score1 = online.get_value((user, obj2, 0)) pbar.value = score1 return None else: return { 'new_model_tensor': model_tensor_copy, 'new_minibatch': mb_np_copy, 'online_learner': online, 'indices_lst': indices_lst, 'result': result, }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def replica_local_fn(*args, **kwargs):\n if any(\n isinstance(arg, keras_tensor.KerasTensor)\n for arg in nest.flatten((args, kwargs))):\n update_op = None\n else:\n update_op = self.update_state(*args, **kwargs) # pylint: disable=not-callable\n update_ops = []\n ...
[ "0.6139598", "0.60502064", "0.6037282", "0.59968215", "0.5993548", "0.59875697", "0.59847033", "0.5928292", "0.58975184", "0.5886014", "0.5876047", "0.58682144", "0.58607525", "0.579297", "0.5697605", "0.56715125", "0.56684655", "0.56642056", "0.5641743", "0.563186", "0.56158...
0.6717393
0
Constructs a new RasterPixelNeighbourhoodSynthesizer object with the given TextureSynthesizer parameters and neighbourhood padding.
def __init__(self, source_image_path: str, source_image_size: Tuple[int, int], output_image_path: str, output_image_size: Tuple[int, int], neighbourhood_padding: List[int], tsvq_branching_factor: int = 0) -> None: super().__init__(source_image_path, source_image_size, output_image_path, output_image_size) self.__levels = len(neighbourhood_padding) self.__neighbourhood_padding = neighbourhood_padding self.__tsvq_branching_factor = tsvq_branching_factor assert self.__levels > 0, "At least one neighbourhood padding size must be specified." assert self.__tsvq_branching_factor >= 0, "TSVQ branching factor cannot be negative."
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setupNeighbor(self, **params):\n if not self.rank:\n logging.info('Setting up nearest neighbor searching parameters')\n\n if 'nns_freq' not in params:\n params['nns_freq'] = 10\n\n if 'nns_skin' not in params:\n radius = 0\n\n for ss in params['species']:\n if 'radius' in ss...
[ "0.5060241", "0.49463", "0.48258802", "0.47280812", "0.46252775", "0.46126506", "0.46024764", "0.457279", "0.45638797", "0.44532672", "0.44472826", "0.44013366", "0.43816498", "0.43589807", "0.43002614", "0.4286713", "0.4275962", "0.42492765", "0.4246044", "0.41933078", "0.41...
0.49128336
2
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_image.shape)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def randomize_pixels(image):\n shape_ = image.size()\n image_flat = image.view(-1, image.size(-1))\n shuffled_image = shuffle(image_flat)\n return shuffled_image.view(shape_)", "def setUp(self):\n self.image = np.random.randint(\n 0, 256, size=(10, 10, 3)).astype('uint8')", "def p...
[ "0.68415916", "0.65006113", "0.6458804", "0.63344526", "0.6230885", "0.62036294", "0.6179382", "0.5990032", "0.5980545", "0.5975108", "0.59486", "0.59019417", "0.5884772", "0.58742434", "0.58631706", "0.58573", "0.58512574", "0.5831452", "0.5810674", "0.57992274", "0.5780533"...
0.81843376
0
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: prev_distances = self.__make_distance_matrix(src_pyramid[level + 1], out_pyramid[level + 1], self.__neighbourhood_padding[level + 1], out_point // 2, False) next_distances = self.__make_distance_matrix(src_pyramid[level], out_pyramid[level], self.__neighbourhood_padding[level], out_point, True) distances = next_distances + np.kron(prev_distances, np.ones((2, 2))) candidate = np.unravel_index(np.argmin(distances), distances.shape) out_pyramid[level][out_point] = src_pyramid[level][candidate]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def render_pixel(game_map: PreGameMap, coord: Coordinate):\n if not((0 <= coord[0] < game_map.size[0]) and (0 <= coord[1] < game_map.size[1])):\n return\n terrain = TERRAIN.get(coord, None)\n if terrain == 'sea':\n game_map.display_coord(coord, 'blue')\n return\n if terrain is None...
[ "0.5802858", "0.5658782", "0.54832906", "0.54623395", "0.5383574", "0.53326017", "0.5214478", "0.520735", "0.5191128", "0.51251477", "0.50873256", "0.5066412", "0.49981758", "0.49971747", "0.49680513", "0.49348786", "0.49256635", "0.4886838", "0.48779047", "0.48769373", "0.48...
0.74728173
0
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, padding, 'wrap', causal) # Construct a 2D Gaussian kernel that matches the padding size. gaussian_1D = signal.gaussian(2 * padding + 1, std=padding) gaussian_2D = np.outer(gaussian_1D, gaussian_1D) gaussian_2X = np.extract(out_filled, gaussian_2D) # Return the weighted squared difference of each neighbourhood in the # source Image with respect to the reference window. return self._apply_distance_filter(src_image, out_window, out_filled, gaussian_2X)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def padding(self):\n pad = self.ntiles - self.windowsize\n return (int((pad - 1)/2.), int((pad + 1)/2.))", "def padding(self):\n\t\treturn self.paddings_shape_param('W')", "def convolution(img, kernel, padding=True):\n result = np.zeros_like(img)\n p_size_i = kernel.shape[0] // 2\n p_siz...
[ "0.59613675", "0.5644716", "0.55131125", "0.5483496", "0.54455864", "0.53608745", "0.53575754", "0.5356096", "0.5319758", "0.5300092", "0.52018", "0.5187523", "0.5163065", "0.5131752", "0.5121635", "0.50840497", "0.50273937", "0.500391", "0.49987105", "0.49745652", "0.4957173...
0.66690564
0
Collect chapter text, continue to the next page.
def parse(self, res): chapter_number = int( res.selector .xpath('//select[@id="chap_select"]/option[@selected]/@value') .extract_first() ) chapter = ( res.selector .xpath('//div[@id="storytextp"]') .extract_first() ) yield ChapterItem( book_id=self.book_id, chapter_number=chapter_number, chapter=chapter, ) next_onclick = ( res.selector .xpath('//button[text()="Next >"]/@onclick') .extract_first() ) if next_onclick: next_href = ( re.search('\'(?P<url>.*)\'', next_onclick) .group('url') ) next_url = res.urljoin(next_href) yield Request(next_url)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_chapter_text(location):\n chapter_output_dictionary = {}\n chapter_contents_list = []\n\n soup = Ripper(location, parser=\"html5lib\", save_path=save_path).soup\n text = soup.find(\"table\", class_=\"texttable\")\n\n for each in text.find_all(\"p\"):\n attributes = each.attrs\n ...
[ "0.6254111", "0.6226124", "0.60621554", "0.60245425", "0.6024121", "0.5917416", "0.5824434", "0.57892185", "0.57140803", "0.5646418", "0.56081015", "0.5558332", "0.5478581", "0.54719883", "0.5470737", "0.54651356", "0.5361365", "0.532996", "0.53109443", "0.5294205", "0.525057...
0.5375936
16
Accept or reject files as valid plugins.
def is_valid_file(file): return file.endswith('.py')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def plugin_valid(self, filepath):\n plugin_valid = False\n for extension in self.extensions:\n if filepath.endswith(\".{}\".format(extension)):\n plugin_valid = True\n break\n return plugin_valid", "def test_noFilesFromAccept(self):\n return se...
[ "0.65010744", "0.6104965", "0.5794032", "0.5707183", "0.5649255", "0.56050813", "0.5578996", "0.55527157", "0.55129015", "0.5468118", "0.53080404", "0.5299193", "0.5288881", "0.5282098", "0.5281953", "0.5269145", "0.5248508", "0.5243704", "0.52391577", "0.5234795", "0.5222672...
0.0
-1
Returns surface with text written on
def create_surface_with_text(text, font_size, text_rgb, bg_rgb): font = pygame.freetype.SysFont("Courier", font_size, bold=True) surface, _ = font.render(text=text, fgcolor=text_rgb, bgcolor=bg_rgb) return surface.convert_alpha()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def render_text_on_surface(text, surface, font, color=BLACK, top_padding=0, left_pading=0):\n rect = surface.get_rect()\n \n last_top = rect.top + top_padding\n for index, line in enumerate(text.split(\"\\n\")):\n text_surf = font.render(line, True, color)\n text_rect = text_surf.get_rect...
[ "0.7163597", "0.7081734", "0.69762814", "0.6956038", "0.6877182", "0.68770796", "0.68757975", "0.6862509", "0.6859123", "0.6852565", "0.66053784", "0.6594931", "0.6489052", "0.6467568", "0.64561605", "0.64365697", "0.64138114", "0.6388757", "0.6379859", "0.6376531", "0.636716...
0.68874395
4
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
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mouse_over(self):\n pass", "def update_button_hover_status(self):\n for button in self.playing_buttons:\n button.update(self.mousePos)", "def mouse_hover(self):\n self.color1 = self.color # Color changes\n position = pygame.mouse.get_pos() # Get mouse position\n ...
[ "0.63936216", "0.62173915", "0.618309", "0.6071253", "0.60500014", "0.5977573", "0.583766", "0.57638043", "0.56980425", "0.5674184", "0.5642134", "0.5620496", "0.5582014", "0.5577019", "0.55757505", "0.5544018", "0.55341464", "0.55198807", "0.55091316", "0.5495941", "0.545860...
0.6484619
0
Draws element onto a surface
def draw(self, surface): surface.blit(self.image, self.rect)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def draw(self, surface):\r\n if self.visible:\r\n surface.blit(self.image, (self.x, self.y))", "def draw(self, surface):\n surface.blit(self.image, self.rect)", "def draw(self, surface):\n surface.blit(self.image, self.rect)", "def draw(self, surface):\n\n\t\tsurface.blit(self...
[ "0.8029322", "0.7931684", "0.7931684", "0.7848772", "0.77393", "0.7583257", "0.75462705", "0.74494654", "0.73914146", "0.73739934", "0.7322107", "0.728858", "0.71618783", "0.7161633", "0.7157818", "0.71283376", "0.7125859", "0.7120794", "0.7112475", "0.7098524", "0.7094169", ...
0.7984203
1
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_action = button.update(pygame.mouse.get_pos(), mouse_up) if ui_action is not None: return ui_action screen.blit(img, imgrect) buttons.draw(screen) pygame.display.flip()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def callback_game_loop(self) -> None:\n self._goal_generate()\n self._update()\n self.reset()\n\n while self._player != self._goal:\n self._update()\n action = self._action_callback(\n self._player.np,\n self._goal.np,\n ...
[ "0.65111536", "0.6462207", "0.6459699", "0.6442829", "0.6415537", "0.64030033", "0.63696444", "0.635908", "0.6352003", "0.63030666", "0.62873745", "0.6223671", "0.62234336", "0.61902213", "0.61875373", "0.6147553", "0.61422455", "0.61360407", "0.6135536", "0.6128289", "0.6121...
0.7331514
0
Convert `f([1,2,3])` to `f(1,2,3)` call.
def func_star(a_b_c): return worker(*a_b_c)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def f(*args):\n alist = [a() for a in args]\n print(alist)", "def _sfn(x):\n if len(x) == 1:\n return x[0]\n return fn(*x)", "def call(f):\n def g(*args, **kwds):\n return (f, args, kwds)\n return g", "def tof(i, shape):\n if callable(i):\n re...
[ "0.6124384", "0.60952973", "0.6085935", "0.6050709", "0.6008939", "0.58921486", "0.58708686", "0.5853999", "0.58538496", "0.5820732", "0.5781621", "0.57792044", "0.57751167", "0.5746887", "0.5720413", "0.5692134", "0.56451917", "0.5604771", "0.55775815", "0.5568582", "0.55431...
0.0
-1
Snipout target regions from nc4 file Quick and dirty hax to reduce the size of data read in from netCDF files. Keeps a memory leak in the module from blowing up the script. Not the best way to handle this.
def read_region(config, *args, **kwargs): years, regions, data = read(*args, **kwargs) if configs.is_allregions(config): regions_msk = np.ones(regions.shape, dtype='bool') else: target_regions = configs.get_regions(config, regions) regions_msk = np.isin(regions, target_regions) return years, regions[regions_msk], data[..., regions_msk]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getmissedoutregions(peakfile,treatment_bamfile, min_size, min_coverage_gain_over_average,window_size):\n total_read_count=getmappedreadcount(treatment_bamfile)\n chrsizedict=getchrsizes(treatment_bamfile)\n total_chr_size=sum([chrsizedict[chrnm] for chrnm in chrsizedict])\n avg_reads=1.0*total_read...
[ "0.5983268", "0.57220346", "0.56906366", "0.56776756", "0.5443779", "0.53902256", "0.53483415", "0.5345517", "0.5310131", "0.5251542", "0.52337545", "0.5207498", "0.5138871", "0.5079943", "0.50771165", "0.50436515", "0.5033471", "0.502106", "0.50090265", "0.5006125", "0.49940...
0.0
-1
If deltamethod is True, treat as a deltamethod file.
def read(filepath, column='rebased', deltamethod=False): global deltamethod_vcv try: rootgrp = Dataset(filepath, 'r', format='NETCDF4') except: print "Error: Cannot read %s" % filepath exit() years = rootgrp.variables['year'][:] regions = rootgrp.variables['regions'][:] if deltamethod is None: # Infer from the file deltamethod = 'vcv' in rootgrp.variables if deltamethod: data = rootgrp.variables[column + '_bcde'][:, :, :] if deltamethod_vcv is None: deltamethod_vcv = rootgrp.variables['vcv'][:, :] else: assert(np.all(deltamethod_vcv == rootgrp.variables['vcv'][:, :])) else: data = rootgrp.variables[column][:, :] rootgrp.close() # Correct bad regions in costs if filepath[-10:] == '-costs.nc4' and not isinstance(regions[0], str) and not isinstance(regions[0], unicode) and np.isnan(regions[0]): rootgrp = Dataset(filepath.replace('-costs.nc4', '.nc4'), 'r', format='NETCDF4') regions = rootgrp.variables['regions'][:] rootgrp.close() return years, regions, data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def do_delete(self, arg):\n \treturn False", "def doDeltas(self, index, delta):\n raise NotImplementedError", "def has_delete(self) -> bool:\n return \"delete_item\" not in self.__abstractmethods__", "def is_deleted(file):\n return file.status == 'removed'", "def setup_tdelta(self, dir1...
[ "0.52665573", "0.52226734", "0.5083611", "0.5033847", "0.49743", "0.4964233", "0.49004477", "0.48254514", "0.4820641", "0.48202047", "0.47662693", "0.4760697", "0.47521505", "0.47316724", "0.47197148", "0.4699426", "0.46711266", "0.46684945", "0.4661074", "0.46458593", "0.463...
0.0
-1
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') else: self._captureManager.stopWritingVideo() # escape elif keycode == 27: self._windowManager.destroyWindow()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def keypress(self, key): # pragma: no cover\n if key == \"s\":\n self.screenshot()\n\n elif key == \"q\" or key == \"Esc\":\n self.close()\n\n elif key == \"c\":\n self._print_camera()", "def on_key_press(symbol, modifiers):\n\n if symbol == key.BACKSPACE...
[ "0.6659243", "0.6474064", "0.6172918", "0.6085636", "0.60522807", "0.60106236", "0.59625655", "0.59214485", "0.5895227", "0.5893601", "0.5828445", "0.57692516", "0.5768595", "0.5760644", "0.5697636", "0.5668367", "0.5653859", "0.56379724", "0.5637277", "0.56291217", "0.562732...
0.7867244
0
Convert obj to a boolean value.
def boolean(obj): try: text = obj.strip().lower() except AttributeError: return bool(obj) if text in ('yes', 'y', 'on', 'true', 't', '1'): return True elif text in ('no', 'n', 'off', 'false', 'f', '0'): return False else: raise ValueError("Unable to convert {!r} to a boolean value.".format(text))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def bool(self, obj):\n return True", "def bool(self, obj):\n return True", "def __bool__(self):\n return bool(self.obj)", "def get_bool_value(obj):\n value = get_signed_value(obj)\n if value is None:\n return None\n if value == 0:\n return False\n return True", ...
[ "0.8203927", "0.8203927", "0.7958037", "0.7597296", "0.72692347", "0.7137266", "0.7102944", "0.7024828", "0.7009565", "0.69297254", "0.6888933", "0.6804311", "0.67199594", "0.6641516", "0.6618284", "0.65779626", "0.65483236", "0.6538082", "0.6533702", "0.6525651", "0.6517225"...
0.77563757
3
Convert binary string to octal string.
def bin2oct(x): return oct(int(x, 2))[_oct_index:]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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\\\...
[ "0.76374495", "0.7044908", "0.6909392", "0.65396476", "0.64724284", "0.6420651", "0.6391345", "0.63298297", "0.6304698", "0.62848026", "0.62484807", "0.6202142", "0.6194703", "0.6158532", "0.6135139", "0.60936713", "0.6040064", "0.60131395", "0.6008048", "0.5986144", "0.59714...
0.693906
2
Convert binary string to decimal number.
def bin2dec(x): return int(x, 2)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_decimal(binary):\n if len(re.findall('[0-1]+', binary)[0] )< 9:\n return int('0b'+binary, 2)\n return -1", "def binstr2dec(bstr):\n return int(bstr, base=2)", "def binary_to_num(s):\n if s == \"\":\n return 0\n return binary_to_num(s[:-1]) * 2 + (s[-1] == '1')", "def strTo...
[ "0.78903747", "0.7885636", "0.765049", "0.70580614", "0.6969785", "0.6961387", "0.693392", "0.68926793", "0.6852822", "0.67974126", "0.67220104", "0.66843843", "0.6644219", "0.66395557", "0.6582165", "0.651349", "0.64023507", "0.63830984", "0.63452876", "0.6322163", "0.631969...
0.6758526
10
Convert binary string to hexadecimal string.
def bin2hex(x): return hex(int(x, 2))[2:]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def bin2hex(binstr: str) -> str:\n if not binstr.lower().startswith(\"0b\"):\n raise ValueError(\"Binary string must be prefixed with '0b'.\")\n return str(hex(int(binstr, 2)))", "def hex(string):\n return string.encode('hex')", "def bytes_to_hex(s):\n\n return s.encode(\"hex\")"...
[ "0.7759733", "0.77295285", "0.7636728", "0.7604716", "0.7535407", "0.7260567", "0.7139173", "0.7033751", "0.70027816", "0.6942292", "0.6938883", "0.69219834", "0.68988675", "0.6864446", "0.6853494", "0.6837628", "0.68031734", "0.6798349", "0.67891264", "0.67869467", "0.678374...
0.7004051
8
Convert octal string to binary string.
def oct2bin(x): return bin(int(x, 8))[2:]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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\\\...
[ "0.75368214", "0.70557326", "0.69577855", "0.69247776", "0.6849758", "0.6813903", "0.6772026", "0.67233974", "0.66740793", "0.6569174", "0.64823663", "0.6465421", "0.64253926", "0.63317066", "0.6325535", "0.6298426", "0.61963886", "0.61666733", "0.6131182", "0.61288166", "0.6...
0.7644674
0
Convert octal string to decimal number.
def oct2dec(x): return int(x, 8)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def dec2int(r: str) -> int:", "def octal_frac_to_decimal(octal_frac_string):\n result = 0.0\n for place, digit in enumerate(octal_frac_string, start=1):\n result += int(digit) * (8 ** -place)\n\n return result", "def strToDec(string):\n\tstring = string.lstrip(\"0\")\n\tif len(string) == 0:\n\t...
[ "0.7270691", "0.6982738", "0.6802102", "0.6558195", "0.63187855", "0.6228094", "0.61978084", "0.6157006", "0.6082201", "0.60479116", "0.6019029", "0.59776914", "0.59653455", "0.5915168", "0.588256", "0.5826446", "0.5811062", "0.5801341", "0.5750719", "0.5742125", "0.5740209",...
0.73984647
0
Convert octal string to hexadecimal string.
def oct2hex(x): return hex(int(x, 8))[2:]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def int2hex(n: int) -> str:", "def print_as_hex(s):\n print(\":\".join(\"{0:x}\".format(ord(c)) for c in s))", "def hex(string):\n return string.encode('hex')", "def hex2oct(x):\n # moreZero = random.choice(range(10))\n moreZero = 0\n return oct(int(x, 16)).zfill(moreZero + len(oct(int(x, 16))...
[ "0.7127962", "0.6858865", "0.67977035", "0.66891956", "0.66581327", "0.6595217", "0.65746325", "0.6475897", "0.6462714", "0.6440759", "0.6420401", "0.63975835", "0.6394663", "0.6390578", "0.6357414", "0.63572913", "0.6354585", "0.6322785", "0.6259033", "0.62520534", "0.624957...
0.79475677
0
Convert decimal number to binary string.
def dec2bin(x): return bin(x)[2:]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def decimal_binary(num):\n\treturn \"{:08b}\".format(num)", "def decimal_to_binary(num):\n binary_res = \"\"\n while num >= 1:\n binary_char = num % BINARY_BASE\n num = math.floor(num / BINARY_BASE)\n binary_res += str(binary_char)\n if len(binary_res) < REGISTER_SIZE:\n bina...
[ "0.8236683", "0.819006", "0.812", "0.79700625", "0.7841461", "0.7756673", "0.77427316", "0.76487184", "0.75304836", "0.7437725", "0.7421353", "0.73704696", "0.7348961", "0.7341534", "0.72605896", "0.7256575", "0.7220447", "0.7186589", "0.717596", "0.71444225", "0.70927733", ...
0.67141455
35
Convert decimal number to octal string.
def dec2oct(x): return oct(x)[_oct_index:]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_octal(number: int) -> str:\n return oct(number).replace(\"0o\", \"\")", "def Oct(num):\n n = CInt(num)\n if n == 0:\n return \"0\"\n else:\n return oct(n)[2:]", "def oct2dec(x):\n return int(x, 8)", "def transforme(n):\n if n<10 :\n return '0'+str(n)\n else :\...
[ "0.85344994", "0.7369621", "0.67910177", "0.6471545", "0.6426", "0.64133406", "0.6403742", "0.6379834", "0.63354963", "0.62981486", "0.6294578", "0.62746924", "0.6197787", "0.617983", "0.60516167", "0.5865457", "0.5854878", "0.5846542", "0.582088", "0.58134466", "0.5812273", ...
0.69433445
2
Convert decimal number to hexadecimal string.
def dec2hex(x): return hex(x)[2:]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def int_to_hex(num):\n return hex(num)", "def int2hex(n: int) -> str:", "def conv_hex(num):\n\n if num < 10:\n return str(num)\n if num == 10:\n return 'A'\n if num == 11:\n return 'B'\n if num == 12:\n return 'C'\n if num == 13:\n return 'D'\n if num == ...
[ "0.78035283", "0.77907705", "0.75513417", "0.7522622", "0.7502476", "0.74146914", "0.7356076", "0.6979989", "0.69490105", "0.6932604", "0.68115395", "0.6799762", "0.6793538", "0.67127126", "0.67070514", "0.66273284", "0.6567772", "0.64950943", "0.64847827", "0.6417631", "0.64...
0.708946
7
Convert hexadecimal string to binary string.
def hex2bin(x): return bin(int(x, 16))[2:]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __convertToBinaryStr(self, hex_str): \n final_bi_str = ''\n for c in hex_str:\n bi_str = bin(int(c, 16))[2:]\n if len(bi_str) != 4:\n bi_str = (4 - len(bi_str)%4)*'0' + bi_str\n final_bi_str += bi_str\n \n # sanity check\n i...
[ "0.7621665", "0.7618675", "0.73749584", "0.72984225", "0.72389203", "0.7198531", "0.7171915", "0.70927596", "0.7027672", "0.6871051", "0.6852968", "0.68465996", "0.68267417", "0.67572474", "0.67438805", "0.67404485", "0.6701374", "0.66283566", "0.6606921", "0.6577254", "0.655...
0.69028884
9
Convert hexadecimal string to octal string.
def hex2oct(x): return oct(int(x, 16))[_oct_index:]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def oct2hex(x):\n return hex(int(x, 8))[2:]", "def hex2oct(x):\n # moreZero = random.choice(range(10))\n moreZero = 0\n return oct(int(x, 16)).zfill(moreZero + len(oct(int(x, 16)))).strip('L')", "def to_octal(number: int) -> str:\n return oct(number).replace(\"0o\", \"\")", "def test_binary_st...
[ "0.7262856", "0.6970385", "0.6871056", "0.6547219", "0.6355148", "0.626188", "0.6197579", "0.608063", "0.60802263", "0.6070935", "0.6067904", "0.6041254", "0.6039679", "0.6004906", "0.5979743", "0.59688586", "0.59631056", "0.5912364", "0.5895775", "0.5880666", "0.5853619", ...
0.7017675
1
Convert hexadecimal string to decimal number.
def hex2dec(x): return int(x, 16)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def Convert_Hex_To_Decimal(hex_data):\n try:\n decimal_data = int(hex_data, 16)\n return decimal_data\n except (ValueError, TypeError):\n return ''", "def hex2dec(string_num):\n if hex_pattern.match(string_num):\n return int(string_num.upper(), 16)\n else:\n return ...
[ "0.7818734", "0.72936374", "0.72419447", "0.7171258", "0.71257603", "0.71137595", "0.70621866", "0.7044454", "0.70193475", "0.69514954", "0.6795297", "0.6723554", "0.66410637", "0.66204774", "0.66098815", "0.66023034", "0.6579708", "0.6495168", "0.6473546", "0.6464677", "0.64...
0.7270727
2