def get_notifications(self, request): if not self.check_demo_optin(request): return yield Notification(text="Your IP is %s" % request.META.get("REMOTE_ADDR")) yield Notification(title="Dice", text="Your lucky number is %d" % random.randint(1, 43), kind="success") yield Notification(title="Stock Alert", text="Items X, Y, Z are running low", kind="warning") yield Notification(title="Outstanding Orders", text="10 orders have not been touched in 7 days", kind="danger")
def run_once(self): try: for order in self.orders: order.cancel_order() if order.status in [1, 2]: title = "%s已成交,价格:%f, 数量:%f" % (self.symbol, order.price, order.amount) Notification.log_and_email(title, title) self.orders = [] userinfo = json.loads(okcoinSpot.userinfo()) if "result" in userinfo and userinfo["result"]: coin = self.symbol.split("_")[0] free_coin = float(userinfo["info"]["funds"]["free"][coin]) ticker = okcoinSpot.ticker(self.symbol) last_price = float(ticker['ticker']['last']) for cfg in self.cfg: price = last_price * (1 + cfg['p']) amount = free_coin * cfg['v'] order = json.loads( okcoinSpot.trade(self.symbol, "sell", price, amount)) if "order_id" in order: self.orders.append( SellOrder(self.symbol, order["order_id"], price, amount)) else: print(userinfo) except Exception as e: print(e) pass
def patch(self): requestedArgs = getArguments( ['notificationId', 'title', 'message', 'creationTime']) args = requestedArgs.parse_args() notification = Notification.getNotificationsByNotificationId( self.session, args['notificationId'])[0] notification = dict_as_obj(args, notification) return Notification.updateNotification(self.session, notification)
def notify(message, ts, title=None): if test_folder or back_test: print("%s\n%s: %s" % (title,time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(ts)), message)) else: t = title if not title: t = message Notification.log_and_email(message, t)
def auth(userID, img): if (userUD == 'Unknown'): Switch.open() Audio.negative() Notification.notif(img) else: Switch.close() Audio.positive(userID)
def get(self): requestedArgs = getArguments( ['cmd', 'notificationId', 'title', 'message', 'creationTime']) args = requestedArgs.parse_args() if args['cmd'] == 'getNotificationsByNotificationId': return Notification.getNotificationsByNotificationId( self.session, args['notificationId']) return Notification.getNotifications(self.session)
def downloadNewLinksFromPinboard(destinationPath, options): log.debug("Starting up.") last_update_file = options['pinboard']['lastUpdateFile'] already_downloaded_tag = options['pinboard']['alreadyDownloadedTag'] failed_download_tag = options['pinboard']['failedDownloadedTag'] enable_downloads = options['pinboard']['enableDownloads'] last_update_time = "" if os.path.exists(last_update_file): with open(last_update_file, 'r') as f: for line in f: last_update_time = line pinboard_conn = pinboard.open(token=options['pinboard']['apiToken']) pinboard_last_update_time = pinboard_conn.last_update() log.debug("Last updated at %s. Pinboard updated at %s", last_update_time, pinboard_last_update_time) if last_update_time == pinboard_last_update_time: log.info("No changes. Exiting.") return successfulDownloads = [ ] failedDownloads = [ ] log.debug("Looking for new bookmarks...") posts = pinboard_conn.posts(fromdt=last_update_time) for p in posts: url = p['href'] name = p['description'] tags = p['tags'] update_time = p['time'] urlMatch = False for pat in options['pinboard']['urlPatterns']: if re.search(pat, url): urlMatch = True if urlMatch and already_downloaded_tag not in tags and failed_download_tag not in tags: log.debug(u"Found %s (%s)", name, url) try: name = download(url, destinationPath, options) except Exception as e: tags.append(failed_download_tag) log.exception("Download failed. Adding failed tag.") failedDownloads.append(name) else: tags.append(already_downloaded_tag) log.debug("Download complete. Adding completed tag.") successfulDownloads.append(name) if enable_downloads: pinboard_conn.add(url, name, replace='yes', tags=tags) if enable_downloads: with open(last_update_file, 'w') as f: f.write(pinboard_last_update_time) if len(successfulDownloads) > 0 or len(failedDownloads) > 0: sucStr = string.join(['"'+name[0:20]+'"' for name in successfulDownloads], ", ") failStr = string.join(['"'+name[0:20]+'"' for name in failedDownloads], ", ") message = "%d succeeded, %d failed. OK: %s, Failed: %s" % (len(successfulDownloads), len(failedDownloads), sucStr, failStr) Notification.send("PinTheVideo done", message, options)
def listen(self) -> NoReturn: """Continuously loop while checking for due plans and unread email.""" while True: # Check Plans plans = self.db.read() for plan in plans: if plan.due_date <= arrow.utcnow(): self.db.write(filter(lambda p: plan != p, plans)) Notification.toast('Butler', f'{plan.name} is due.') # Check Messages for mail in Email.get(self.username, self.password): Notification.toast(mail.subject, mail.body)
def CheckAvalibility(self): start_date = self.le_start_date.text() end_date = self.le_end_date.text() start_time_1 = self.le_start_time1.text() start_time_2 = self.le_start_time2.text() end_time_1 = self.le_end_time1.text() end_time_2 = self.le_end_time2.text() if start_date != "" and end_date != "" and start_time_1 != "" and start_time_2 != "" and end_time_1 != "" and end_time_2 != "": messages = [] check_result = CheckTimeslots(start_time_1, end_time_1, start_time_2, end_time_2, self.select_job_combo.currentText()) if check_result != -1: messages.append(check_result) check_result = CheckAvailability(start_date, end_date, start_time_1, end_time_1, True, self.record_id) if check_result != -1: messages.append(check_result + " In StartTime1 + EndTime1") elif start_time_2 != "N/A" and end_time_2 != "N/A": check_result = CheckAvailability(start_date, end_date, start_time_2, end_time_2, True, self.record_id) if check_result != -1: messages.append(check_result + " In StartTime2 + EndTime2") if len(messages) != 0: message = "" for each in messages: message = message + each + ";" else: message = "No Issues with the current time slots" else: message = "Please fill in all times and dates" notification = Notification(self, message) notification.setModal(True) notification.show() notification.raise_()
def get_notifications(self, request): try: engines["jinja2"] except InvalidTemplateEngineError: text = """Simple Order Notifications can't send order notifications because it can't find a Jinja2 template engine. Name your Jinja2 template engine "jinja2" to resolve this.""" yield Notification(text=text)
def openfile(self): files = [('Text Document', '*.txt'), ('Word Document', '.doc')] filename = tkinter.filedialog.askopenfilename(parent=self.__root, filetypes=files, defaultextension=files) if filename is not None and filename != '': with open(filename, encoding='utf-8', mode='r') as file: data = file.read() if self.__handle_data.get_mute() == 'True': Notification('You can not speak here').start() return self.__txt.config(state=NORMAL) try: self.__txt.insert(END, data + '\n') except: self.__txt.insert( END, "Your device doesn't support this type of message" + '\n') self.__txt.yview(END) self.__txt.config(state=DISABLED) self.__client_socket.write( (self.__client_name + '01' + data).encode()) self.__my_cursor.execute( "SELECT chat FROM users WHERE name=%s ", (self.__client_name[1:], )) msg = self.__my_cursor.fetchone() if msg[0] is not None: my_chat = msg[0] message = my_chat + DATE + ' ' + str( time.strftime("%H:%M") ) + ' ' + self.__client_name[1:] + ': ' + data + '\n' message = emoji.demojize(message) self.__my_cursor.execute("UPDATE users SET chat = %s", (message, ))
def get_notifications(self, request): if is_telemetry_enabled() and is_in_grace_period() and not is_opt_out(): yield Notification( _("Statistics will be periodically sent to E-Commerce.com after 24 hours. Click here for more information."), title=_("Telemetry"), kind="info", url="E-Commerce_admin:telemetry" )
def test_notification_reverse_url(): try: set_urlconf("E-Commerce_tests.notify.notification_test_urls") n = Notification(shop=factories.get_default_shop()) kwargs = dict(viewname="test", kwargs={"arg": "yes"}) # kwargs within kwargs, oh my n.set_reverse_url(**kwargs) n.save() with pytest.raises(ValueError): n.set_reverse_url() assert n.url == reverse(**kwargs) finally: set_urlconf(None)
def cancel_order(self): while 1: try: result = json.loads( okcoinSpot.cancelOrder(self.symbol, self.orderid)) self.update_status() cc = 0 while self.status not in [-1, 2, 1] and cc < 10: self.update_status() time.sleep(0.2) cc += 1 if cc >= 10: Notification.log_and_email("无法取消订单", "无法取消订单") continue return except Exception as e: print(e) time.sleep(10)
def entry_font_color(self): try: color = ask_string('font color', 'write a color') if color == 'available colors': Available(self.__root) return if color == 'default': color = '#FB2412' self.__e1.configure(fg=color, insertbackground=color) self.add_color_db(color, 'input_font_color') except: Notification("This color doesn't exist").start()
def root_background_color(self): try: color = ask_string('background color', 'write a color') if color == 'available colors': Available(self.__root) return if color == 'default': color = '#025E73' self.__root.configure(background=color) self.add_color_db(color, 'root_background_color') except: Notification("This color doesn't exist").start()
async def requestReceived(websocket, session, request): global notificationsSubscribers #Websockets endpoints if request['operation'] == 'get': #get endpoint notifications = Notification.getNotifications(session) response = convertToJson({'operation' : 'get', 'table' : 'Notifications', 'data' : notifications}) await websocket.send(response) elif request['operation'] == 'subscribe': #subscription endpoint notifications = Notification.getNotifications(session) response = convertToJson({'operation' : 'get', 'table' : 'Notifications', 'data' : notifications}) notificationsSubscribers.add(websocket) await websocket.send(response) elif request['operation'] == 'add': #add endpoint if checkArguments(request, ['title', 'message']) == False: print('Not all parameters were provided for ADD in Notifications') await websocket.send(convertToJson({'error' : 'Invalid request'})) return notification = dict_as_obj(request['data'], Notification.Notification(), ['notificationId', 'creationTime']) notification = Notification.addNotification(session, notification) response = convertToJson({'operation' : 'add', 'table' : 'Notifications', 'data' : notification}) notificationsSubscribers = set(filter(removeClosedConnection, notificationsSubscribers)) for subscriber in notificationsSubscribers: await subscriber.send(response) elif request['operation'] == 'update': #update endpoint if checkArguments(request, ['notificationId']) == False: print('Not all parameters were provided for UPDATE in Notifications') await websocket.send(convertToJson({'error' : 'Invalid request'})) return data = request['data'] notification = Notification.getNotificationsByNotificationId(session, data['notificationId'])[0] notification = dict_as_obj(data, notification) notification = Notification.updateNotification(session, notification) response = convertToJson({'operation' : 'update', 'table' : 'Notifications', 'data' : notification}) notificationsSubscribers = set(filter(removeClosedConnection, notificationsSubscribers)) for subscriber in notificationsSubscribers: await subscriber.send(response) elif request['operation'] == 'delete': #delete endpoint if checkArguments(request, ['notificationId']) == False: print('Not all parameters were provided for DELETE in Notifications') await websocket.send(convertToJson({'error' : 'Invalid request'})) return notification = Notification.deleteNotification(session, request['data']['notificationId']) response = convertToJson({'operation' : 'delete', 'table' : 'Notifications', 'data' : notification}) notificationsSubscribers = set(filter(removeClosedConnection, notificationsSubscribers)) for subscriber in notificationsSubscribers: await subscriber.send(response)
def DeleteRecord(came_from, current_record_id, table_name): are_you_sure = ConfirmationWindow(came_from, "Are you sure you wish to delete this record? This action cannot be undone.") are_you_sure.setModal(True) are_you_sure.show() are_you_sure.raise_() decision = are_you_sure.exec_() #confirm deletion window if decision == 1: if current_record_id != -1 and current_record_id != "There Are No Records To Display": database.DeleteRecord(table_name, current_record_id) came_from.DisplayAll() else: #notify if record not selected notification = Notification(came_from, "Please select a record") notification.setModal(True) notification.show() notification.raise_()
def parse_request(self): request = input("Enter your request: \n") request = request.rstrip().split(' ') time_stamp = datetime.now() data = Office.basicCaseData( self.unique_id, Notification.timeStamp(time_stamp.hour, time_stamp.minute, time_stamp.second)) if len(request) == 2 and request[0] == 'AID' and is_float(request[1]): average_earnings = float(request[1]) expected_time = self.service_proxy.requestUnemployedAid( data, average_earnings) self.logger.info( 'Expected resolution time for case {} is {}'.format( request[0], expected_time)) elif len(request) == 3 and request[0] == 'PERMISSION' and is_float( request[2]): address = request[1] area = float(request[2]) expected_time = self.service_proxy.requestBuildingPermission( data, address, area) self.logger.info( 'Expected resolution time for case {} is {}'.format( request[0], expected_time)) elif len(request) == 3 and request[0] == 'LICENCE' and to_bool( request[2]) is not None and request[1].isdigit(): candidate_profile = int(request[1]) first_licence = to_bool(request[2]) expected_time = self.service_proxy.requestDrivingLicence( data, candidate_profile, first_licence) self.logger.info( 'Expected resolution time for case {} is {}'.format( request[0], expected_time)) elif len(request) == 1 and request[0] == 'REFRESH': self.notifier_proxy = self.notifier_proxy_factory.create_notifier_proxy( ) self.reception_proxy.register(self.unique_id, self.notifier_proxy) elif len(request) == 1 and request[0] == 'QUIT': return False else: self.logger.warning('Invalid arguments provided!') return True
def get_notifications(self, request): shop = request.shop old_open_orders = Order.objects.filter( shop=shop, status__role=OrderStatusRole.INITIAL, order_date__lt=now() - timedelta(days=4) ).count() if old_open_orders: yield Notification( title=_("Outstanding Orders"), text=_("%d outstanding orders") % old_open_orders, kind="danger" )
def get_notifications(self, request): try: engine = engines["jinja2"] except KeyError: engine = None if engine and isinstance(engine, Jinja2): # The engine is what we expect... if isinstance(engine.env, XthemeEnvironment): # ... and it's capable of loading themes... if not get_current_theme(request.shop): # ... but there's no theme active?! # Panic! yield Notification( text=_("No theme is active. Click here to activate one."), title=_("Theming"), url="E-Commerce_admin:xtheme.config" )
def get_notifications(self, request): """ Injects a message to the user and also a notification """ # multi-shop not supported if not E-CommerceSettings.get_setting("E-Commerce_ENABLE_MULTIPLE_SHOPS"): from E-Commerce.admin.shop_provider import get_shop shop = get_shop(request) if sample_manager.has_installed_samples(shop): messages.warning(request, _('There is sample data installed. ' 'Access "Settings > Sample Data" for more information.')) yield Notification( _("There is sample data installed. Click here to consolidate or delete them."), title=_("Sample Data"), kind="warning", url="E-Commerce_admin:sample_data" )
def get_notifications(self, request): shop = get_shop(request) notif_qs = NotificationModel.objects.unread_for_user(request.user).filter(shop=shop).order_by("-id")[:15] for notif in notif_qs: if notif.priority == Priority.HIGH: kind = "warning" elif notif.priority == Priority.CRITICAL: kind = "danger" else: kind = "info" yield Notification( text=notif.message, url=notif.url, kind=kind, dismissal_url=reverse("E-Commerce_admin:notify.mark-read", kwargs={"pk": notif.pk}), datetime=notif.created_on )
def RestoreDatabase(self): #restore pervious backup are_you_sure = ConfirmationWindow( self, "Are you sure you wish to restore an earlier version of the database? You should make a backup before restoring to be safe." ) are_you_sure.setModal(True) are_you_sure.show() are_you_sure.raise_() self.decision = are_you_sure.exec_() if self.decision == 1: if not (os.path.isdir(os.getcwd() + "\DatabaseBackups") ): #if there isn't the backups dir notification = Notification(self, "No backups have been made") notification.setModal(True) notification.show() notification.raise_() else: filenames = os.listdir( os.getcwd() + "\DatabaseBackups") #get list of all backups select_database = SelectDatabase( self, filenames) #send to restore window select_database.show() select_database.raise_() self.hide()
def ConfirmChoice(self): self.choice = self.database_combo.currentText() connection = sqlite3.connect("Pet_Service.db") connection.commit() connection.close() #close the database while swapping in old copy shutil.copyfile( os.path.join(os.getcwd() + "\DatabaseBackups", self.choice), os.getcwd() + "\Pet_Service.db" ) #replace .db file that is used with backup (no need to rename) notification = Notification( self, "Restore Complete") #tell user restore has been completed notification.show() notification.raise_() self.came_from.show() self.close()
def start(self, params=None): while (1): try: ws = create_connection("wss://real.okex.com:10441/websocket") t = PingThread(ws) t.start() break except: Notification.log('connect ws error,retry...') time.sleep(5) symbols = set() for h in self.handlers: symbols = symbols.union(h.get_cfg_symbols_set()) print("symbols", symbols) if capture_mode: self.handlers = [Handlers.CaptureHandler(notify)] for s in symbols: ws.send("""{'event':'addChannel','channel':'ok_sub_spot_%s_deals'}""" % s) ws.send("""{'event':'addChannel','channel':'ok_sub_spot_%s_depth'}""" % s) last_check_time = time.time() try: while (1): result = ws.recv() result_json = json.loads(result) t = time.time() if t - last_check_time > 30*60: Notification.log("alive") last_check_time = t for data in result_json: if "channel" in data: if data["channel"][-6:] == "_deals": symbol = data["channel"][12:-6] self.dispatch_deal_msg(data['data'], symbol, t) elif data["channel"][-6:] == "_depth": symbol = data["channel"][12:-6] self.dispatch_depth_msg(data['data'], symbol, t) pass except Exception as e: Notification.log(e)
options_dict = {} with open(sys.argv[1], 'r') as options_file: options_dict = yaml.load(options_file) log_file = options_dict['directories']['logDir'] + "/PinTheVideo.%s.log" % ( datetime.date.today()) logging.basicConfig( filename=log_file, level="DEBUG", format="%(asctime)-15s %(name)-8s %(module)-15s %(funcName)-15s %(message)s" ) log = logging.getLogger("PinTheVideo") destination = options_dict['directories']['destination'] if not os.path.exists(destination): os.mkdir(destination) log.info("Starting with destination = '%s'", destination) try: DownloadStage.downloadNewLinksFromPinboard(destination, options_dict) except Exception as ex: log.exception("DownloadStage failed") Notification.send("DownloadStage failed", str(ex), options_dict) try: MuxBrokenFiles.fixUnmuxedFiles(destination, options_dict) except Exception as ex: log.exception("Remux failed") Notification.send("Remux failed", str(ex), options_dict)
import logging, datetime, sys, os import DownloadStage, MuxBrokenFiles, Notification import yaml options_dict = {} with open(sys.argv[1], 'r') as options_file: options_dict = yaml.load(options_file) log_file = options_dict['directories']['logDir'] + "/PinTheVideo.%s.log" % (datetime.date.today()) logging.basicConfig(filename=log_file, level="DEBUG", format="%(asctime)-15s %(name)-8s %(module)-15s %(funcName)-15s %(message)s") log = logging.getLogger("PinTheVideo") destination = options_dict['directories']['destination'] if not os.path.exists(destination): os.mkdir(destination) log.info("Starting with destination = '%s'", destination) try: DownloadStage.downloadNewLinksFromPinboard(destination, options_dict) except Exception as ex: log.exception("DownloadStage failed") Notification.send("DownloadStage failed", str(ex), options_dict) try: MuxBrokenFiles.fixUnmuxedFiles(destination, options_dict) except Exception as ex: log.exception("Remux failed") Notification.send("Remux failed", str(ex), options_dict)
def fun(): a = web_value.get() b = freq_value.get() c = t_value.get() Notification.noti(a, b, c) app.destroy()
import Server import Notification if __name__ == "__main__": Server.main() Notification.notificatioMain()
def post(self): requestedArgs = getArguments(['title', 'message']) args = requestedArgs.parse_args() notification = dict_as_obj(args, Notification.Notification()) return Notification.addNotification(self.session, notification)
def delete(self): requestedArgs = getArguments(['notificationId']) args = requestedArgs.parse_args() return Notification.deleteNotification(self.session, args['notificationId'])