def main(): # 1.创建管理员对象 ad = Admin("admin", "123") # 2. 管理员登录 ad.landUI() # 3.创建atm对象 atm = Atm() # 4.显示操作界面 while True: atm.printOptionUI() # 5.用户输入对应的编号,调用对应的函数 bh = input("请输入编号") if bh == "1": atm.creatUser() elif bh == "2": atm.serach() elif bh == "3": atm.save() elif bh == "4": atm.take() elif bh == "5": atm.transfer() elif bh == "6": atm.change() elif bh == "7": atm.lock() elif bh == "8": atm.unlock() elif bh == "9": atm.clear() elif bh == "T": atm.exit()
def main(): loginPrompt = "Please select option: login | guest | register | admin: " val = input(loginPrompt) logins = readLogins("loginStore.txt") adminLogins = readLogins("adminLoginStore.txt") global isGuest isGuest = True if val == "login" or val == "register": # register accounts if val == "register": logins = register(logins) # login time login(logins, False) isGuest = False elif val == "admin": isSuccess = login(adminLogins, True) if (not isSuccess): exit() admin = Admin() admin.modify() print("Exiting admin session") exit() cart = ShoppingCart(isGuest) cart.startShopping()
def __init__(self): admin = Admin() handlers = [ (r"/", MainHandler) , (r"/browse-books", BrowseHandler) , (r"/you", ProfileHandler) , (r"/user/([\d]+)", ProfileHandler) , (r"/top-10", TopTenHandler) , (r"/book/([\d]+)", BookDetailHandler) , (r"/login", AuthLoginHandler) , (r'/book/([\d]+)/rate/([\d\.]+)', BookRatingHandler) ] handlers.extend(admin.get_handlers('admin')) # TODO: Change cookie_secret settings = dict( debug=True, cookie_secret="43oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=", login_url="/auth/login", template_path = os.path.join(os.path.dirname(__file__), "templates"), static_path = os.path.join(os.path.dirname(__file__), "public"), ) #global db #db = DBWrapper() #initialize DB global smaker smaker = Util.make_sessionmaker(Base) tornado.web.Application.__init__(self, handlers, **settings)
def list_public_projects(project_type): ''' ''' admin = Admin() list_of_projects = admin.list_projects(project_type, project_access='public') return jsonify(list_of_projects)
def init_lists(c_list, s_list, a_list): course1 = Course("CSC227", 2) course1.add_student("1003") course1.add_student("1004") c_list.append(course1) course2 = Course("CTI115", 2) course2.add_student("1001") c_list.append(course2) course3 = Course("DBA130", 1) course3.add_student("1002") c_list.append(course3) student1 = Student("1001", "111") s_list.append(student1) student2 = Student("1002", "222") s_list.append(student2) student3 = Student("1003", "333") s_list.append(student3) student4 = Student("1004", "444") s_list.append(student4) admin1 = Admin("8001", "888") a_list.append(admin1) admin2 = Admin("9001", "999") a_list.append(admin2)
def init_lists(c_list, s_list, a_list): """ This function adds elements to course_list, student_list and admin_list. It makes testing and grading easier. It has three parameters: c_list is the list of Course objects; s_list is the list of Student objects; a_list is the list of Admin objects. This function has no return value. """ course1 = Course("CSC121", 2) course1.add_student("1004") course1.add_student("1003") c_list.append(course1) course2 = Course("CSC122", 2) course2.add_student("1001") c_list.append(course2) course3 = Course("CSC221", 1) course3.add_student("1002") c_list.append(course3) student1 = Student("1001", "111") s_list.append(student1) student2 = Student("1002", "222") s_list.append(student2) student3 = Student("1003", "333") s_list.append(student3) student4 = Student("1004", "444") s_list.append(student4) admin1 = Admin("7001", "777") a_list.append(admin1) admin2 = Admin("8001", "888") a_list.append(admin2)
def main(argv): loop=True floors=[] if len(sys.argv)<3: printWarning("usage:\nMVP\t -n = Number of floors\n\t -m= Number of Elevators") return 0 m,n=int(sys.argv[1]), int(sys.argv[2]) printInfo("received values:"+str(n)+" "+str(m)); admin=Admin(n,m) for i in range(m): floors.append(Floor(i,admin)) while loop: ## While loop which will keep going until loop = False admin.printStatusElevators() print_menu() ## Displays menu choice = input("Enter your choice [1-3]: ") if choice==1: floor, destination = map(int,raw_input(" <floor> <destination floor>\n").split(" ")) if floor <= m and destination<=m and destination!=floor: up_down=1 if destination>floor else 2 closer_elevator=floors[floor].askResources(up_down) print "The elevator " + str(closer_elevator)+ " will attend this request" threading.Timer(1, set_floor,[admin.elevators[closer_elevator],floor,destination]).start() #routine to ask elevator elif choice==2: admin.printStatusElevators() elif choice==3: loop=False
def admin_menu(): while True: choice = input("What do you want to do?") if choice == '1': # Admin register if not ADMIN_REGISTERED: Admin.register() ADMIN_REGISTERED = True else: print("Admin has been registered before.") continue elif choice == '2': continue elif choice == '3': pass continue elif choice == '4': pass continue elif choice == '5': pass continue elif choice == '6': # Quit pass break
def adminLogin(): # get the log in state and redirect to the index page if true if session.get('adminLogin'): return redirect(url_for('admin_page')) messages = "" # get the parameters if the request method is GET if request.method == "GET": if request.args.get('loggedout'): messages = "You have been logged out!" elif request.args.get('loginerror'): messages = "Username & Password combination is incorrect, try again!" # get the POST data if request method is POST elif request.method == "POST": admin_username = request.form['username'] admin_password = request.form['password'] admin_password = hashlib.sha256(admin_password.encode()).hexdigest() # call the login_admin method for the Admin class right after creating the admin object admin = Admin() response = admin.login_admin(username=admin_username, password=admin_password) if response: # set session parameters and timeout to 5mins and redirect to the index page session.permanent = True app.permanent_session_lifetime = datetime.timedelta(minutes=5) session['adminLogin'] = True session['adminUsername'] = admin_username return redirect(url_for('admin_page', username=admin_username)) else: return redirect(url_for("adminLogin", loginerror=True)) return render_template('admin_login.html', data = messages), 200
def load_bank_data(self): customer_1 = Customer("Adam", "1234", ["14", "Wilcot Street", "Bath", "B5 5RT"]) account_no = 1234 account_1 = Account(5000.00, account_no) customer_1.open_account(account_1) self.customers_list.append(customer_1) customer_2 = Customer("David", "password", ["60", "Holborn Viaduct", "London", "EC1A 2FD"]) account_no+=1 account_2 = Account(3200.00,account_no) customer_2.open_account(account_2) self.customers_list.append(customer_2) customer_3 = Customer("Alice", "MoonLight", ["5", "Cardigan Street", "Birmingham", "B4 7BD"]) account_no+=1 account_3 = Account(18000.00,account_no) customer_3.open_account(account_3) self.customers_list.append(customer_3) customer_4 = Customer("Ali", "150A",["44", "Churchill Way West", "Basingstoke", "RG21 6YR"]) account_no+=1 account_4 = Account(40.00,account_no) customer_4.open_account(account_4) self.customers_list.append(customer_4) admin_1 = Admin("Julian", "1441", True, ["12", "London Road", "Birmingham", "B95 7TT"]) self.admins_list.append(admin_1) admin_2 = Admin("Eva", "2222", False, ["47", "Mars Street", "Newcastle", "NE12 6TZ"]) self.admins_list.append(admin_2)
def main(): global database global markov global updater global chat_states # This is safe as long as we only access the db within the dispatcher # callbacks. If not then we need locks. database = Database(sqlite3.connect(config.DBFILE, check_same_thread=False)) database.initialize() markov = Markov(database) chat_states = ChatStates(database) updater = Updater(config.TOKEN) updater.last_update_id = database.get_parameter('last_update', -1) + 1 admin = Admin(database, markov, updater, chat_states, config.ADMIN_LIST) dp = updater.dispatcher admin.register_handlers(dp) dp.add_handler(MessageHandler(Filters.sticker, on_sticker), 0) dp.add_handler(MessageHandler(Filters.all, on_message), 0) # Commit updates after being handled. This avoids messages being handled # twice or updates being missed dp.add_handler(MessageHandler(Filters.all, on_post_message), 1) dp.add_handler(AllUpdateHandler(on_post_update), 1) dp.add_error_handler(on_error) updater.start_polling() updater.idle() os._exit(0)
def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.show() self.admin = Admin(self.ui) self.ui.pushButton.clicked.connect(self.slot_method)
def __init__( self, url=None, schema=None, tenant=None, namespace=None ): self.admin = Admin(url,schema,tenant,namespace)
def create_products(): counter = 0 admin = Admin() product_ids = [] while counter < 5: product_ids.append(admin.create_product().get("product")["product_id"]) counter += 1 return product_ids
def main(): user = raw_input('username:'******'password:') admin = Admin() result = admin.CheckValidate(user, pwd) # 调用,验证合法性 if not result: print "用户名或密码错误" else: print "进入后台管理页面"
def admin(self): # 后台查看所有用户 ad = Admin() if ad.adminLogin(): return -1 print('已存在账号信息:') for i, j in self.allUsers.items(): print('卡号:%s 姓名:%s 身份证:%s 电话:%s 金额:%d' % (i, j.name, j.idCard, j.phone, j.card.cardMoney)) time.sleep(5)
def admin_feed_1(message=None): keyboard = telebot.types.ReplyKeyboardMarkup(one_time_keyboard=False, resize_keyboard=True) Admin.set_state('feed') for var in Admin.feedback_var: keyboard.add(var) admin_bot.send_message(Admin.get_id(), Template.feed_admin_q(), reply_markup=keyboard)
def run_admin_options(self, admin_obj): loop = 1 while loop == 1: #Transfer money choice = self.admin_menu(admin_obj) if choice == 1: sender_lname = input("\nPlease input sender surname: ") amount = float( input("\nPlease input the amount to be transferred: ")) receiver_lname = input("\nPlease input receiver surname: ") receiver_account_no = input( "\n Please input receiver account number: ") self.transferMoney(sender_lname, receiver_lname, receiver_account_no, amount) elif choice == 2: #This option is used to access a specific customers account customer_name = input("\nPlease input customer surname: \n") customer_account = self.search_customers_by_name(customer_name) if customer_account != None: customer_account.run_account_options() elif choice == 3: #Delete customer if Admin.has_full_admin_right( admin_obj ) == True: #Checks the current logged in administrator for their full administration rights customer_name = input( "\nInput customer name you want to delete: ") customer_account = self.search_customers_by_name( customer_name ) #Looks to see if the entered account exists in the if customer_account != None: self.accounts_list.remove(customer_account) print("%s was deleted successfully!" % customer_name) else: print( "\nYou do not have permission to delete customers \n") elif choice == 4: #Print all customer details self.print_all_accounts_details( ) #Calls fucntion to print all customer account details elif choice == 5: #Update current logged in administrators details if Admin.has_full_admin_right( admin_obj ) == True: #Checks whether the current admin has full admin rights admin_last_name = input("\nPlease input admin surname: \n") admin_account = self.search_admins_by_last_name( admin_last_name) if admin_account != None: admin_account.run_account_options( ) #WHY IS THIS NOT WORKING HAVE TO INVESTIGATE ARRRHHJHHJHJKGHFGJH else: print("\nYou do not have full administrator rights") elif choice == 6: loop = 0 print("\n Exit account operations")
def register_admin(admin_name, password, path): """ this function register user and save to file. :param admin_name: user name of user. :param password: password of user. :param path: address of file. """ password_hash = hash_pas.hash(password) member = Admin(admin_name, password_hash) member.add_file(path)
def newadminDB(): if 'admin' in session: username = request.form['username'] password = request.form['password'] admin = Admin(username, password) admin.addAdmin() return redirect(url_for('dashboard')) else: flash('You need to Login first!', 'warning') return redirect(url_for('admin'))
def create_coupons(): counter = 0 admin = Admin() coupon_codes = [] while counter < 10: coupon_codes.append(admin.create_coupon_code().get("coupon")["code"]) counter += 1 return coupon_codes
class Application(QMainWindow): def __init__(self, parent=None): super(Application, self).__init__(parent) self.reservation_button = QPushButton("Reservation") self.reservation_button.setStyleSheet( u"QPushButton {\n" " color: white;\n" " background-color: rgb(0, 59, 76);\n" " min-width: 80px;\n" "}") self.catalog_button = QPushButton("Car catalog") self.catalog_button.setStyleSheet( u"QPushButton {\n" " color: white;\n" " background-color: rgb(0, 59, 76);\n" " min-width: 80px;\n" "}") self.history_button = QPushButton("Car history") self.history_button.setStyleSheet( u"QPushButton {\n" " color: white;\n" " background-color: rgb(0, 59, 76);\n" " min-width: 80px;\n" "}") layout = QGridLayout() self.setLayout(layout) groupbox = QGroupBox("Menu") layout.addWidget(groupbox) vbox = QVBoxLayout() groupbox.setLayout(vbox) vbox.addWidget(self.reservation_button) vbox.addWidget(self.catalog_button) vbox.addWidget(self.history_button) self.setCentralWidget(groupbox) self.reservation_button.clicked.connect(self.showReservation) self.catalog_button.clicked.connect(self.showCatalog) self.history_button.clicked.connect(self.showHistory) self.reservation = Reservation() self.admin = Admin() def showReservation(self): self.reservation.show() def showCatalog(self): print("catalog") def showHistory(self): self.admin.show()
def admin_send_feed(keyboard, isBad=Admin.get_isBad): try: feed = Feedback.read_feedback(isBad) Admin.set_current_feed(feed) text = feed['description'] except FeedbackListIsEmptyError: Admin.set_current_feed(False) text = 'Список отзывов пуст' keyboard = keyboard_off admin_feed_close() admin_bot.send_message(Admin.get_id(), text, reply_markup=keyboard)
class AppWindow(QDialog): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.show() self.admin = Admin(self.ui) self.ui.pushButton.clicked.connect(self.slot_method) @pyqtSlot() def slot_method(self): self.admin.showData()
def getAllTriggersAlarming(): triggerCached = cache_get('triggerTelao', cache_options['triggerGet']['name']) if triggerCached: return json.loads(triggerCached) elif cache_get('updatingCache', cache_options['updates']['name']) == 'True': while cache_get('updatingCache', cache_options['updates']['name']) == 'True': time.sleep(0.3) else: return json.loads( cache_get('triggerTelao', cache_options['updates']['name'])) else: if cache_exists('updatingCache', cache_options['updates']['name']): cache_update('updatingCache', 'True', cache_options['updates']['expiration_time'], cache_options['updates']['name']) else: cache_set('updatingCache', 'True', cache_options['updates']['expiration_time'], cache_options['updates']['name']) admin = Admin() zbx_admin_token = admin.auth() triggers = fowardZ.sendToZabbix(method='trigger.get', params={ 'selectHosts': ["name"], 'selectGroups': ['groups'], 'selectLastEvent': ['lastEvent', 'acknowledged'], 'expandComment': 1, 'expandDescription': 1, 'only_true': 1, 'output': 'extend' }, auth=zbx_admin_token) cache_set('triggerTelao', json.dumps(triggers), cache_options['triggerGet']['expiration_time'], cache_options['triggerGet']['name']) cache_update('updatingCache', 'False', cache_options['updates']['expiration_time'], cache_options['updates']['name']) return triggers
def main(): admin = Admin() #管理员对象 admin.printAdminView() #管理员开机 if admin.adminOperation(): return -1 atm = ATM() while True: #等待用户操作 admin.sysFunctionView() option = input("请输入你的操作:") if option == '0': atm.createUser() if option == '1': pass elif option == '2': pass elif option == '3': pass elif option == '4': pass elif option == '5': pass elif option == '6': pass elif option == '7': pass elif option == '8': pass elif option == '9': if admin.adminOperation(): return -1
def test(self): storage = {} a = Admin(storage) l = Login(storage) a.addUser('fred', 's3cr3t') u = l.login('fred', 's3cr3t') self.assertTrue(u is not None) u2 = l.login('fred', 's3cr3t') self.assertTrue(u is u2) u3 = l.login('fred', 'password') self.assertTrue(u3 is None)
def SwitchToRoleMenu(): if (staff_role == "d"): doctor = Doctor(staff_name, staff_id) doctor.doctorMenu() elif (staff_role == "n"): nurse = Nurse(staff_name, staff_id) nurse.InitializeNurseMenu() elif (staff_role == "a"): admin = Admin(staff_name, staff_id) admin.AdminMenu() else: print("\nSomething went wrong please re-login") Login()
def main(): # 存取所以用户的信息 # 界面对象 admin = Admin() admin.print_admin_view() # 用户管理员开机 # 如果view.admin_login()返回值是-1,程序结束。如果是0就不会执行下去 if admin.admin_option() == -1: return -1 # 提款机对象 ''' f = open(file_path, "rb") all_users = pickle.load(f) atm = Atm(all_users) ''' file_path = os.path.join(os.getcwd(), "a.txt") all_users = {} atm = Atm(all_users) # admin.print_sys_function_view() while True: admin.print_sys_function_view() # 等待用户操作 option = input("请输入你的操作:") if option == "1": atm.create_user() elif option == "2": atm.search_user_info() elif option == "3": atm.get_money() elif option == "4": print("存款") elif option == "5": print("转账") elif option == "6": print("改密") elif option == "7": atm.lock_user() elif option == "8": atm.unlock_user() elif option == "9": print("补卡") elif option == "0": print("销户") elif option == "q": if not admin.admin_option(): # 讲当前系统中用户信息保存到文件中 # abs_path = os.getcwdb() # 获取当前目录觉得路径 # file_path = os.path.join(os.getcwdb(), "allusers.txt") f = open(file_path, "wb") pickle.dump(atm.all_user, f) f.closed print(file_path) return -1 time.sleep(0.5)
def admin_feed_3(message=None): try: option = Admin.feedback_options[message.text] except KeyError: option = Admin.feedback_options_after_reply[message.text] if option == 1: Admin.set_state('reply') admin_bot.send_message(Admin.get_id(), 'Пришли ответ мне', reply_markup=keyboard_off) elif option == 2: admin_send_feed(Admin.feed_keyboard()) elif option == 3: admin_feed_close()
def signinProcess(self): if (len(self.entrySigninEmail.get()) != 0) and (len( self.entrySigninPassword.get()) != 0): email = self.entrySigninEmail.get() self.cursor.execute( "SELECT userFirstName, userLastName, userPassword, userBalance, admin, userID " "FROM Users " "WHERE userEmail = '" + email + "';") passwordCheck = self.cursor.fetchall() password = "" if len(passwordCheck) == 0: self.showErrorWindow("Email not found") else: for row in passwordCheck: firstName = row[0] lastName = row[1] password = row[2] balance = row[3] adminPrivilege = row[4] accountID = row[5] if password == self.entrySigninPassword.get(): if adminPrivilege == 1: # Create admin instance and open to admin home screen self.adminInstance = Admin(firstName, lastName, password, accountID) self.adminHomeWindow() else: # Create user instance and open home screen self.userInstance = User(firstName, lastName, password, balance, accountID, self.transactionLog) self.fromSigninToHome() else: self.showErrorWindow("Password is incorrect") print("Password is wrong") else: if len(self.entrySigninEmail.get()) == 0: self.showErrorWindow("No Email Entered") print("No Email") elif len(self.entrySigninPassword.get()) == 0: self.showErrorWindow("No Password Entered") print("No Password") else: self.showErrorWindow("Internal Error") print("Internal Error")
def main(): #存储所有用户的信息 allUsers = {} #管理员对象 admin = Admin() #管理员开机 admin.printAdminView() if admin.adminOption(): return -1 #提款机对象 filePath = os.path.join(os.getcwd(), 'allusers.txt') f = open(filePath, 'rb') allUsers = pickle.load(f) atm = ATM(allUsers) while True: admin.printSysFunctionView() #等待用户的操作 option = raw_input('请输入您的操作:') if option == '1': #print '开户' atm.createUser() elif option == '2': #print '查询' atm.searchUserInfo() elif option == '3': #print '取款' atm.getMoney() elif option == '4': print '存款' elif option == '5': print '转账' elif option == '6': print '改密' elif option == '7': #print '锁定' atm.lockUser() elif option == '8': #print '解锁' atm.unlockUser() elif option == '9': print '补卡' elif option == '0': print '销户' elif option == 't': if not admin.adminOption(): #将当前系统中的用户信息保存到文件中 #path = r'D:\test\bank.txt' #filePath = os.path.join(os.getcwd(), 'allusers.txt') f = open(filePath, 'wb') pickle.dump(atm.allUsers, f) f.close() return -1 time.sleep(2)
def get_admin(from_user): admin = Admin.get(id=from_user.id) if admin: admin.first_name = from_user.first_name admin.last_name = from_user.last_name admin.username = from_user.username return admin
def add_xmpp_admin(bot, command, args_array, bridge): parser = ArgumentParser(prog=command) parser.add_argument('jid', type=str) parser.add_argument('--say-level', choices=say_levels.levels, default=say_levels.levels[1]) try: args = parser.parse_args(args_array) except Exception as e: return '\n'+e.args[1] admin = Admin() admin.jid = args.jid admin.say_level = args.say_level bot.admins.append(admin) for b in bot.bridges: for p in b.participants: if p.real_jid != None and xmpp.protocol.JID(args.jid).bareMatch(p.real_jid): p.bot_admin = True return 'XMPP admin added.'
def __init__(self, host_list = ['0.0.0.0:5000']): """初始化服务端/客户端服务 """ self.logger = Logger(logname='log/log.txt', loglevel = 3, callfile = __file__).get_logger() try: self.server = Admin(host_list) self.client = Client(host_list) except: print "Gearman server host port is error!" self.logger.error("Dispatch a task name %s, %r" %(task_name, json_data)) sys.exit()
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER ALLOWED_DATA_EXTENSIONS = set(['csv', 'zip']) DOWNLOAD_FOLDER = 'static/download' app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER from models import Burial, BurialImage, BurialJSONEncoder, \ get_burials, get_burial, add_burial, remove_all_burials, \ get_burial_images, get_burial_image, \ add_burial_image, set_latlng from admin import Admin, BurialModelView, BurialImageModelView admin = Admin(app, name='cemetery-map', template_mode='bootstrap3') admin.add_view(BurialModelView(Burial, db.session)) admin.add_view(BurialImageModelView(BurialImage, db.session)) def randstr(): return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(30)) def allowed_image_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_IMAGE_EXTENSIONS def allowed_data_file(filename):
from admin import Admin ad = Admin("S", "K", "*****@*****.**") ad.list_preiveleges()
quit(2) bots_jids.append(bot_el.getAttribute('jid')) bots = [] for bot_el in config.getElementsByTagName('bot'): debug = False if bot_el.hasAttribute('debug'): if bot_el.getAttribute('debug') == 'true': debug = True admins = [] for admin_el in bot_el.getElementsByTagName('admin'): if admin_el.hasAttribute('jid'): admin = Admin() admin.jid = admin_el.getAttribute('jid') if admin_el.hasAttribute('say_level'): admin.say_level = say_levels.get(admin_el.getAttribute('say_level')) else: admin.say_level = say_levels.warning admins.append(admin) bot = Bot(bot_el.getAttribute('jid'), bot_el.getAttribute('password'), bot_el.getAttribute('nickname'), admins=admins, debug=debug) bots.append(bot) for bridge_el in bot_el.getElementsByTagName('bridge'): xmpp_room = bridge_el.getElementsByTagName('xmpp-room')[0] irc = bridge_el.getElementsByTagName('irc')[0] irc_connection_interval = 1 if irc.hasAttribute('connection_interval'):
from unsubscribes import Unsubscribes app = flask.Flask(__name__) # Config Mongo mongo = db.establish_mongo_connection(app) app.mongo = mongo # Config secret key app.secret_key = settings.secret_key # Routes app.add_url_rule('/adminnew', view_func=Admin.as_view('admin'), methods=["GET", "POST"]) app.add_url_rule('/adminnew/users', view_func=Users.as_view('users'), methods=["GET", "POST"]) app.add_url_rule('/adminnew/transactions', view_func=UserTransactions.as_view('transactions'), methods=["GET"]) app.add_url_rule('/adminnew/cronjobs', view_func=Cronjobs.as_view('cronjobs'), methods=["GET"]) app.add_url_rule('/adminnew/emails', view_func=Emails.as_view('emails'), methods=["GET"]) app.add_url_rule('/adminnew/unsubscribes', view_func=Unsubscribes.as_view('unsubscribes'),
def refresh_admin_cache(mapper, connection, target): # The next time someone tries to access an Admin, # the cache will be repopulated. Admin.reset_cache()
from user import User from admin import Privileges, Admin user1 = User("bobby", "brown") user1.print_name() admin1 = Admin("alex", "admin") admin1.print_name() admin1.privileges.show_priv()
def reindex_stuff(dummy): a = Admin() a.rebuild_index()
class GUI(clutter.Stage): """ """ SHOW_GAME_BOARD = 'SHOW_GAME_BOARD' SHOW_CLUE = 'SHOW_CLUE' SHOW_QUESTION = 'SHOW_QUESTION' SHOW_FINAL_ROUND = 'SHOW_FINAL_ROUND' SHOW_FINAL_ROUND_CATEGORY = 'SHOW_FINAL_ROUND_CATEGORY' SHOW_FINAL_ROUND_CLUE = 'SHOW_FINAL_ROUND_CLUE' SHOW_FINAL_ROUND_QUESTION = 'SHOW_FINAL_ROUND_QUESTION' def __init__(self): super(GUI, self).__init__() logging.info('Initializing game gui.') self.admin = Admin() self.gui_state = self.SHOW_GAME_BOARD # Set the stage background to grey. self.set_color(config.stage_background_color) # Connect callback listeners logging.info('Setting up game stage signals.') self.connect('destroy', clutter.main_quit) self.connect('key-press-event', self.on_press) self.connect('button-release-event', self.on_click) self.connect('allocation-changed', self.on_allocation_changed) self.board_box = clutter.Box(clutter.BoxLayout()) board_box_layout = self.board_box.get_layout_manager() # Instantiate the game board which is the collection of squares to show # on screen. self.game_board = GameBoard() board_box_layout.pack(self.game_board, True, True, True, clutter.BOX_ALIGNMENT_CENTER, clutter.BOX_ALIGNMENT_CENTER) # Determine whether or not to display player scores. self.player_score_box = None if config.display_player_scores: self.player_score_box = PlayerScoreBox(game.get_players()) self.player_score_box.set_width(0.1 * self.get_width()) if config.player_scores_position == 'east': layout = self.player_score_box.get_layout_manager() layout.set_vertical(True) board_box_layout.pack(self.player_score_box, True, True, True, clutter.BOX_ALIGNMENT_CENTER, clutter.BOX_ALIGNMENT_CENTER) if config.player_scores_position == 'south': layout = self.player_score_box.get_layout_manager() layout.set_vertical(False) board_box_layout.pack(self.player_score_box, True, True, True, clutter.BOX_ALIGNMENT_CENTER, clutter.BOX_ALIGNMENT_CENTER) else: self.board_box.add(self.player_score_box) # Add the box with the board in it to the screen. self.add(self.board_box) # Overlay box for displaying clue information and answers self.clue_overlay = ClueOverlay() self.clue_overlay.set_size(self.get_width(), self.get_height()) self.add(self.clue_overlay) self.clue_overlay.set_opacity(0) # Overlay box for display category information. self.category_overlay = CategoryOverlay() self.category_overlay.set_size(self.get_width(), self.get_height()) # Overlay box for displaying which player buzzed in. self.player_buzz_overlay = PlayerBuzzOverlay() self.player_buzz_overlay.set_size(self.get_width(), self.get_height()) self.player_buzz_overlay.set_opacity(0) self.add(self.player_buzz_overlay) # Overlay box for displaying player score. self.player_score_overlay = PlayerScoreOverlay() self.player_score_overlay.set_size(self.get_width(), self.get_height()) self.player_score_overlay.set_opacity(0) self.add(self.player_score_overlay) # Overlay box for daily double. self.daily_double_overlay = DailyDoubleOverlay() self.daily_double_overlay.set_size(self.get_width(), self.get_height()) self.daily_double_overlay.set_opacity(0) self.add(self.daily_double_overlay) # Overlay box for final round. self.final_round_overlay = FinalRoundOverlay() self.final_round_overlay.set_size(self.get_width(), self.get_height()) self.final_round_overlay.set_opacity(0) self.add(self.final_round_overlay) # Overlay box for displaying all player scores. self.all_player_scores_overlay = AllPlayerScoresOverlay() self.all_player_scores_overlay.set_size(self.get_width(), self.get_height()) self.all_player_scores_overlay.set_opacity(0) self.add(self.all_player_scores_overlay) self.flashing_scores = False # Set a default stage size. self.set_fullscreen(False) self.set_size(800, 600) self.set_user_resizable(True) self.show() def on_click(self, actor, event): """ """ if type(event.source) == ClueSquare: clue_square = event.source logging.debug('Notify game clue selected') game.select_clue(clue_square.clue) def on_press(self, actor, event): """ """ if event.keyval == clutter.keysyms.Escape: clutter.main_quit() elif event.keyval == clutter.keysyms.a: # player A rings in. game_buttons.player_set(0, True) game.buzz(0) self.update() elif event.keyval == clutter.keysyms.b: # player B rings in. game_buttons.player_set(1, True) game.buzz(1) self.update() elif event.keyval == clutter.keysyms.c: # player C rings in. game_buttons.player_set(2, True) game.buzz(2) self.update() elif event.keyval == clutter.keysyms.space: if not self.final_round_overlay.is_playing(): # We do not allow for incoming space button presses when final # round overlay music is playing. # multi-purpose bar press game.bar() self.update() elif event.keyval == clutter.keysyms.x: # cancel game.cancel() self.update() elif event.keyval == clutter.keysyms.y: # correct answer game.correct_answer() self.update() elif event.keyval == clutter.keysyms.n: # incorrect answer game.incorrect_answer() self.update() elif event.keyval == clutter.keysyms.z: logging.debug('resetting player lights') game_buttons.reset_player_lights() elif event.keyval == clutter.keysyms.l: if self.category_overlay in self.get_children(): self.category_overlay.animate(clutter.LINEAR, 500, 'x', self.category_overlay.get_x() - self.get_width()) else: self.category_overlay.set_size(self.get_width(), self.get_height()) self.category_overlay.set_x(self.get_width()) self.add(self.category_overlay) self.category_overlay.animate(clutter.LINEAR, 500, 'x', self.category_overlay.get_x() - self.get_width()) elif event.keyval == clutter.keysyms.p: # DEBUG - for testing end of round condition without clicking everything. # don't leave this active in production code! for category in game.categories: for clue in category.clues: clue.state = 'selected' game.categories[0].clues[0].state = 'unanswered' elif event.keyval == clutter.keysyms.f: # Fullscreen play area. self.set_fullscreen(not self.get_fullscreen()) elif event.keyval == clutter.keysyms.s: self.flash_scores() def on_allocation_changed(self, stage, box, flags): """ """ logging.debug("self size %d x %d and stage size %d x %d" % (self.get_width(), self.get_height(), stage.get_width(), stage.get_height())) self.clue_overlay.set_size(self.get_width(), self.get_height()) self.daily_double_overlay.set_size(self.get_width(), self.get_height()) self.board_box.set_size(self.get_width(), self.get_height()) if config.display_player_scores: self.player_score_box.set_size(0.1 * self.get_width(), self.get_height()) self.game_board.set_size(0.9 * self.get_width(), self.get_height()) else: self.game_board.set_size(self.get_width, self.get_height()) self.board_box.set_size(self.get_width(), self.get_height()) self.category_overlay.set_size(self.get_width(), self.get_height()) self.player_buzz_overlay.set_size(self.get_width(), self.get_height()) self.player_score_overlay.set_size(self.get_width(), self.get_height()) self.daily_double_overlay.set_size(self.get_width(), self.get_height()) self.final_round_overlay.set_size(self.get_width(), self.get_height()) self.all_player_scores_overlay.set_size(self.get_width(), self.get_height()) def on_tick(self): """ Call back associated with each tick. """ game.on_tick() self.admin.on_tick() # Send update to player scores. self.player_score_box.update() # Read incoming game button presses if they exist. player1, player2, player3 = game_buttons.read() if player1: game.buzz(0) elif player2: game.buzz(1) elif player3: game.buzz(2) game_buttons.reset_buttons() self.update() return True def update(self): """ Update the GUI based on the current state of the game. """ if game.check_update_game_board(): self.board_box.remove(self.game_board) self.game_board = GameBoard() self.board_box.add(self.game_board) if config.display_player_scores: self.game_board.set_size(0.9 * self.get_width(), self.get_height()) else: self.game_board.set_size(self.get_width, self.get_height()) self.game_board.lower_bottom() if game.check_timeout_beep(): logging.debug("****************** BZZZZZT! ******************") tex = cluttergst.VideoTexture() tex.set_filename(config.sound_timeout) tex.set_playing(True) if game.check_flash_player_name(): player_name = game.players[game.buzzed_player].name self.player_buzz_overlay.set_opacity(255) self.player_buzz_overlay.set_text(player_name) self.player_buzz_overlay.animate(clutter.EASE_IN_CUBIC, 2000, 'opacity', 0) if game.check_flash_player_score(): player = game.players[game.buzzed_player] self.player_score_overlay.set_opacity(255) self.player_score_overlay.set_content(player.name, player.last_score_change) self.player_score_overlay.animate(clutter.EASE_IN_CUBIC, 1000, 'opacity', 0) if game.check_flash_daily_double(): self.daily_double_overlay.set_opacity(255) tex = cluttergst.VideoTexture() tex.set_filename(config.sound_daily_double) tex.set_playing(True) if game.check_clear_daily_double(): self.daily_double_overlay.animate(clutter.EASE_IN_CUBIC, 1000, 'opacity', 0) new_gui_state = self.gui_state if game.state == game.IDLE: new_gui_state = self.SHOW_GAME_BOARD elif game.state == game.FINAL_ROUND: new_gui_state = self.SHOW_FINAL_ROUND elif game.state == game.FINAL_ROUND_WAGER: new_gui_state = self.SHOW_FINAL_ROUND_CATEGORY elif game.state == game.FINAL_ROUND_CLUE: new_gui_state = self.SHOW_FINAL_ROUND_CLUE elif game.state == game.FINAL_ROUND_QUESTION: new_gui_state = self.SHOW_FINAL_ROUND_QUESTION elif game.state in (game.DISPLAY_CLUE, game.AWAIT_BUZZ, game.AWAIT_ANSWER, game.DAILY_DOUBLE_AWAIT_WAGER, game.DAILY_DOUBLE_SHOW_CLUE): new_gui_state = self.SHOW_CLUE elif game.state == game.DISPLAY_QUESTION: new_gui_state = self.SHOW_QUESTION else: logging.error('Invalid game state') if self.gui_state != new_gui_state: logging.debug("State %s to %s" % (self.gui_state, new_gui_state)) if new_gui_state == self.SHOW_CLUE: # Reset the buttons. game_buttons.reset_buttons() # We're not displaying clue. Setup the users that are locked out. if game.selected_clue.get_type() == 'audio': self.clue_overlay.set_audio(game.selected_clue.answer['audio']) elif game.selected_clue.get_type() == 'image': self.clue_overlay.set_image(game.selected_clue.answer['image']) elif game.selected_clue.get_type() == 'text': self.clue_overlay.set_text(game.selected_clue.answer) elif game.selected_clue.get_type() == 'video': self.clue_overlay.set_video(game.selected_clue.answer['video']) self.clue_overlay.set_opacity(255) self.clue_overlay.set_scale(0.1, 0.1) self.clue_overlay.animate(clutter.LINEAR, 500, 'scale-x', 1, 'scale-y', 1) elif new_gui_state == self.SHOW_QUESTION: self.clue_overlay.set_text(game.selected_clue.question) self.clue_overlay.set_opacity(255) self.clue_overlay.animate(clutter.LINEAR, 500, 'scale-x', 1, 'scale-y', 1) elif new_gui_state == self.SHOW_GAME_BOARD: logging.debug("Hiding clue overlay") self.clue_overlay.set_opacity(0) elif new_gui_state == self.SHOW_FINAL_ROUND: self.final_round_overlay.set_opacity(255) elif new_gui_state == self.SHOW_FINAL_ROUND_CATEGORY: self.final_round_overlay.set_opacity(255) self.final_round_overlay.set_text("Category:\n%s" % game.final_round.category) elif new_gui_state == self.SHOW_FINAL_ROUND_CLUE: self.final_round_overlay.set_opacity(255) self.final_round_overlay.set_text(game.final_round.answer) self.final_round_overlay.play_music() elif new_gui_state == self.SHOW_FINAL_ROUND_QUESTION: self.final_round_overlay.set_opacity(255) self.final_round_overlay.set_text(game.final_round.question) self.gui_state = new_gui_state def flash_scores(self): if self.flashing_scores == False: sc = "" for player in game.players: sc += '%s\n$%d\n' % (player.name, player.score) self.all_player_scores_overlay.set_text(sc) self.all_player_scores_overlay.animate(clutter.EASE_IN_CUBIC, 500, 'opacity', 255) self.flashing_scores = True else: self.all_player_scores_overlay.animate(clutter.EASE_IN_CUBIC, 500, 'opacity', 0) self.flashing_scores = False
def admin(self): self.logger.info('First endpoint for admin') from admin import Admin a = Admin( logger = self.logger, global_options = self.global_options) a.start()
class Gearman_Manage(object): def __init__(self, host_list = ['0.0.0.0:5000']): """初始化服务端/客户端服务 """ self.logger = Logger(logname='log/log.txt', loglevel = 3, callfile = __file__).get_logger() try: self.server = Admin(host_list) self.client = Client(host_list) except: print "Gearman server host port is error!" self.logger.error("Dispatch a task name %s, %r" %(task_name, json_data)) sys.exit() def show_status(self): """查看server状态信息""" current_status = self.server.get_status() num = 0 for status in current_status: print status def get_worker(self, task_name = None): """查看worker端状态信息""" workers = [] for w in self.server.get_workers(): if w['tasks']: workers.append( w ) print "totla workers: %d" % (len(workers)) if not task_name: for i in workers: print "the IP:[%s]---Worker_name:[%s]---Task_name:[%s]"%(i['ip'],i['client_id'],i['tasks']) else: for i in workers: if task_name and i['tasks'][0] == task_name: print "the IP:[%s]---Worker_name:[%s]---Task_name:[%s]"%(i['ip'],i['client_id'],i['tasks']) return workers def send_task(self, task_name, json_data, priority=PRIORITY_NONE): """发送控制指令""" self.client.send_job(name=task_name, data=json.dumps(json_data), wait_until_complete=False, background=True, priority=priority) print ("Dispatch a task name %s, %r" %(task_name, json_data)) self.logger.info("Dispatch a task name %s, %r" %(task_name, json_data)) def clear_workers(self, task_name = None,priority = PRIORITY_HIGH): """关闭worker""" current_status = self.server.get_status() num = 0 if not task_name: print "I don't know which worker will be clear!" return if task_name == 'all': for status in current_status: num = 0 num = int(status['workers']) for i in range(num): self.send_task(status['task'], {'SHUTDOWN': True},priority) print "stop worker total:%d" % num else: for status in current_status: if status['task'] == task_name: num = int(status['workers']) print status for i in range(num): self.send_task(task_name,{'SHUTDOWN': True},priority) print "stop worker total:%d" % num if num == 0: print "Task list no have name is '%s' task!" % task_name return None def clear_server_list(self, task_name = None): """清理server job 队列""" current_status = self.server.get_status() if not task_name: print "I don't know clear which data list!" return if task_name == 'all': pass else: num = [i['queued'] for i in current_status if task_name == i['task']] print "the list len:%d" % num[0] self.server.empty_task(str(task_name)) def start_server(self, prot = 5000): """启动服务器""" self.server.start_server(prot) self.logger.info("start server.") def stop_server(self): """停止服务器""" try: self.server.send_shutdown() self.logger.info("stop server.") except: print "server is not run!" def ping_server(self): """查看服务器连通状况""" try: print self.server.get_response_time() except: print "server is not run!"
player1 = Player(name) player1.register() player1.login() player1.init_money() player1.give_money(USD, 1000) player1.give_money(USD, 2000) player1.give_money(GOLD, 20) player1.take_money(GOLD, 50) player1.logout() print(player1.sessions) print(player1.player_as_dict()) moder1 = Moderator(name) moder1.register() moder1.login() moder1.give_a_ban() moder1.take_a_ban() moder1.logout() print(moder1.moderator_as_dict()) admin1 = Admin(name) admin1.register() admin1.login() admin1.make_a_moderator() import MySQLdb con = MySQLdb.connect('localhost', 'root', 'root', 'classes'); with con: cur = con.cursor() cur.execute("SELECT * FROM players") for row in cur.fetchall(): print(row)
#!/usr/bin/env python from urlparse import urlparse import rivr from rivr.http import ResponsePermanentRedirect from rivr.wsgi import WSGIHandler import redis from admin import Admin r = redis.StrictRedis(host='redis1.e3.drk.sc', db=1) router=rivr.Router((r'^admin/?$', Admin.as_view(connection=r))) @router.register(r'^') def handler(request): hostname = request.environ['HTTP_HOST'] if ":" in hostname: hostname, port = hostname.split(":", 1) URL = r.get(hostname) if URL: return ResponsePermanentRedirect(URL + request.path) raise rivr.Http404('Hostname not found in DB') app = rivr.MiddlewareController.wrap(router, rivr.TemplateMiddleware(template_dirs = ['./']) ) wsgi = WSGIHandler(app)
def __init__(self): super(GUI, self).__init__() logging.info('Initializing game gui.') self.admin = Admin() self.gui_state = self.SHOW_GAME_BOARD # Set the stage background to grey. self.set_color(config.stage_background_color) # Connect callback listeners logging.info('Setting up game stage signals.') self.connect('destroy', clutter.main_quit) self.connect('key-press-event', self.on_press) self.connect('button-release-event', self.on_click) self.connect('allocation-changed', self.on_allocation_changed) self.board_box = clutter.Box(clutter.BoxLayout()) board_box_layout = self.board_box.get_layout_manager() # Instantiate the game board which is the collection of squares to show # on screen. self.game_board = GameBoard() board_box_layout.pack(self.game_board, True, True, True, clutter.BOX_ALIGNMENT_CENTER, clutter.BOX_ALIGNMENT_CENTER) # Determine whether or not to display player scores. self.player_score_box = None if config.display_player_scores: self.player_score_box = PlayerScoreBox(game.get_players()) self.player_score_box.set_width(0.1 * self.get_width()) if config.player_scores_position == 'east': layout = self.player_score_box.get_layout_manager() layout.set_vertical(True) board_box_layout.pack(self.player_score_box, True, True, True, clutter.BOX_ALIGNMENT_CENTER, clutter.BOX_ALIGNMENT_CENTER) if config.player_scores_position == 'south': layout = self.player_score_box.get_layout_manager() layout.set_vertical(False) board_box_layout.pack(self.player_score_box, True, True, True, clutter.BOX_ALIGNMENT_CENTER, clutter.BOX_ALIGNMENT_CENTER) else: self.board_box.add(self.player_score_box) # Add the box with the board in it to the screen. self.add(self.board_box) # Overlay box for displaying clue information and answers self.clue_overlay = ClueOverlay() self.clue_overlay.set_size(self.get_width(), self.get_height()) self.add(self.clue_overlay) self.clue_overlay.set_opacity(0) # Overlay box for display category information. self.category_overlay = CategoryOverlay() self.category_overlay.set_size(self.get_width(), self.get_height()) # Overlay box for displaying which player buzzed in. self.player_buzz_overlay = PlayerBuzzOverlay() self.player_buzz_overlay.set_size(self.get_width(), self.get_height()) self.player_buzz_overlay.set_opacity(0) self.add(self.player_buzz_overlay) # Overlay box for displaying player score. self.player_score_overlay = PlayerScoreOverlay() self.player_score_overlay.set_size(self.get_width(), self.get_height()) self.player_score_overlay.set_opacity(0) self.add(self.player_score_overlay) # Overlay box for daily double. self.daily_double_overlay = DailyDoubleOverlay() self.daily_double_overlay.set_size(self.get_width(), self.get_height()) self.daily_double_overlay.set_opacity(0) self.add(self.daily_double_overlay) # Overlay box for final round. self.final_round_overlay = FinalRoundOverlay() self.final_round_overlay.set_size(self.get_width(), self.get_height()) self.final_round_overlay.set_opacity(0) self.add(self.final_round_overlay) # Overlay box for displaying all player scores. self.all_player_scores_overlay = AllPlayerScoresOverlay() self.all_player_scores_overlay.set_size(self.get_width(), self.get_height()) self.all_player_scores_overlay.set_opacity(0) self.add(self.all_player_scores_overlay) self.flashing_scores = False # Set a default stage size. self.set_fullscreen(False) self.set_size(800, 600) self.set_user_resizable(True) self.show()