def setup(self): """ Initializes instance variables, creates manager instance and tests connection @return: Nothing """ # Retrieve configuration settings addr = self.classconfig['addr'] password = self.classconfig['password'] if not addr: raise Exception('No address specified') # Check if addr is a "host:port" string (host, colon, port) = addr.partition(":") try: if colon: # IPv4/IPv6 self._m = manager.manager(host=host, port=int(port), password=password) else: # UNIX Socket self._m = manager.manager(path=addr, password=password) # Test connection self.getpid() except Exception, e: raise Exception(str(e))
def __init__(self, *args, **kwargs): """ Initializes instance variables, creates manager instance and tests connection @return: Nothing """ # Retrieve configuration settings addr = self.app.get_config(self).addr password = self.app.get_config(self).password if not addr: raise ConfigurationError("No address specified") # Check if addr is a "host:port" string (host, colon, port) = addr.partition(":") try: if colon: # IPv4/IPv6 self._m = manager.manager(host=host, port=int(port), password=password) else: # UNIX Socket self._m = manager.manager(path=addr, password=password) # Test connection self.getpid() except Exception, e: raise ConfigurationError(str(e))
def main(): w = World(5, 5, [(0, 0, 5), (2, 2, 5), (4, 4, 5)], [(1, 4, 5), (3, 4, 5), (4, 1, 5)], -1, 15, 15) a = Agent(1, 1) # This should run experiment number 1. 8000 steps total, the first 4000 # steps we use PRANDOM policy, then we use PGREEDY for the next 4000 steps manager(w, a, q_learning, 0.3, 0.5, PRANDOM, 8000, [(4000, PGREEDY)])
def jump(): global name reg = Gui() if re.match("S", name): student(reg, mysql, name) gui.close() elif re.match("T", name): teacher(reg, mysql, name) gui.close() elif re.match("W", name): worker(reg, mysql, name) gui.close() elif re.match("M", name): manager(reg, mysql, name) gui.close() gui.close()
def __init__(this, name, dateTime, repeat, mus, volume, useGenetic, usePuzzle): populationSize = 5 #ATRIBS this.name = name this.dateTime = dateTime this.repeat = repeat this.mus = mus this.volume = volume this.useGenetic = useGenetic this.usePuzzle = usePuzzle this.activate = True this.wakeTime = 160 #POPULATION MAKER FOR GENETIC transfer = copy.copy(this) transfer.wakeTime = 200 this.population = manager.manager() this.population.add_alarm(transfer) for i in range(0, populationSize): transfer.volume = this.volume + random.randint(-15, 15) transfer.mus = this.population.avaibleSongs[random.randint( 0, len(this.population.avaibleSongs) - 1)] transfer.usePuzzle = bool(random.getrandbits(1)) this.population.add_alarm(transfer)
def __init__(self, model=None, *args, **kwargs): self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic") # the container is where we'll stack a bunch of frames # on top of each other, then the one we want visible # will be raised above the others container = tk.Frame(root) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} self.frames["startPage"] = startPage(container, self) self.frames["startPage"].grid(row=0, column=0, sticky="nsew") self.frames["login"] = login(container, self) self.frames["login"].grid(row=0, column=0, sticky="nsew") self.frames["userMenu"] = userMenu(container, self) self.frames["userMenu"].grid(row=0, column=0, sticky="nsew") self.frames["manager"] = manager(container, self) self.frames["manager"].grid(row=0, column=0, sticky="nsew") self.frames["graphData"] = graphData(container, self) self.frames["graphData"].grid(row=0, column=0, sticky="nsew") self.frames["updateRegulations"] = updateRegulations(container, self) self.frames["updateRegulations"].grid(row=0, column=0, sticky="nsew") self.show_frame("login")
def initialize(self): _import() """アプリを初期化する。""" self.setGlobalVars() self.proxyEnviron = proxyUtil.virtualProxyEnviron() self.setProxyEnviron() self.installThreadExcepthook() # update関係を準備 if self.config.getboolean("general", "update"): globalVars.update.update(True) self.hMainView = main.MainView() if self.config.getboolean(self.hMainView.identifier, "maximized", False): self.hMainView.hFrame.Maximize() self.hMainView.Show() # sessions.dat対応 if self.config.getint("general", "fileVersion", 100) == 100: if os.path.exists(constants.SESSION_FILE_NAME): try: os.remove(constants.SESSION_FILE_NAME) self.log.debug("File %s deleted." % constants.SESSION_FILE_NAME) except Exception as e: self.log.error("Failed to delete file %s: e" % constants.SESSION_FILE_NAME) self.config["general"]["fileVersion"] = 101 self.accountManager = twitcasting.accountManager.AccountManager() self.hasAccountIssue = False self.Manager = manager.manager(self.hMainView) self.postItem = twitcasting.postItem.PostItem() if len(self.accountManager.tokens) == 0: simpleDialog.dialog( _("アカウント登録"), _("アカウントが登録されていません。ライブに接続する前に、設定メニューのアカウントマネージャからアカウントの登録を行ってください。" )) self.hasAccountIssue = True return True for i in self.accountManager.tokens: if datetime.datetime.now().timestamp() > i["expires_at"]: simpleDialog.dialog( _("アカウントの再登録"), _("期限が切れたトークンが見つかりました。設定メニューのアカウントマネージャから、再度アカウントの追加を行ってください。" )) self.accountManager.deleteAccount( self.accountManager.tokens.index(i)) self.hasAccountIssue = True self.accountManager.removeUnavailableTokens() if len(sys.argv) == 2: self.hMainView.Clear() self.Manager.connect(sys.argv[1]) return True if self.hasAccountIssue == False and self.config.getboolean( "general", "autoconnect", True) == True: self.hMainView.events.connect() return True
def main(): """ Main method to control the program flow """ # set runtime name Vault.set_runtime_name(Util.datetime_to_string()) # create runtime directory mkdir(f"{SESSION_CACHE_PATH}/{Vault.get_runtime_name()}") # set up threading Thread.set_interrupt(False) event = threading.Event() # start threads manager_thread = manager(event) Escapy.async_sniff(custom_action) # menu info_data = [ f"{RED}Sniffer is running but not saving anything locally{RESET}", f"{GREEN}Sniffer is running saving packets locally{RESET}" ] option = [ "Type \"start\" to start saving: ", "Type \"stop\" to stop saving: " ] while True: print(info_data[0 if not Vault.get_saving() else 1], end="\n") print( f"Dashboard: {YELLOW}http://127.0.0.1:8000{RESET} | \'q\' to stop") user_input = input(option[0 if not Vault.get_saving() else 1]) if not Vault.get_saving() and user_input == "start": Util.start_saving() elif Vault.get_saving() and user_input == "stop": Util.stop_saving() elif user_input == "q": break else: print(f"{YELLOW}Invalid option{RESET}", end="\n\n") # SAVE TO FILE IF PROGRAM ENDED AND SAVING IS TRUE if Vault.get_saving(): Util.stop_saving() # interrupt threads Thread.set_interrupt(True) event.set() Escapy.stop() # wait for threads to complete manager_thread.join()
def engine(initUrls): total_pages = manager(initUrls) downloader() success_page = int(redis.get('success')) success_rate = success_page / total_pages print('success_page:', success_page) print('total_pages:', total_pages) print('success_rate: %0.2f%%' % (success_rate * 100))
def setUp(self): db.delete('Users', where='id > 0') self.input_mock = MagicMock() self.winput = patch('web.input') self.input_mock.uname = 'kevin' self.input_mock.utype = 1 self.input_mock.pword = 'password' self.config_mock = MagicMock() self.config = patch('web.config', new=self.config_mock) self.config_mock._session.roleid = 1 self.manager = manager()
def __init__(self, machine_services: object, server_config: object): # Services file position self.root_service_log = os.path.join("machine-services", machine_services) # Services file config self.root_service_cfg = os.path.join("services-cfg", server_config) # Config options of active services that must be initialized self.__server_config = self.__retrive_active_services() # Services Manager self.__manager = manager(self.__server_config) # All active services self.__services = None
def __init__(self, *args, **kwargs): """ Initializes instance variables, creates manager instance and tests connection @return: Nothing """ # Retrieve configuration settings addr = self.app.get_config(self).addr password = self.app.get_config(self).password if not addr: raise ConfigurationError("No address specified") # Check if addr is a "host:port" string (host, colon, port) = addr.partition(":") try: if colon: # IPv4/IPv6 self._m = manager.manager(host = host, port = int(port), password = password) else: # UNIX Socket self._m = manager.manager(path = addr, password = password) # Test connection self.getpid() except Exception, e: raise ConfigurationError(str(e))
def setup(self): """ Initializes instance variables, creates manager instance and tests connection @return: Nothing """ # Retrieve configuration settings addr = self.classconfig["addr"] password = self.classconfig["password"] if not addr: raise Exception("No address specified") # Check if addr is a "host:port" string (host, colon, port) = addr.partition(":") try: if colon: # IPv4/IPv6 self._m = manager.manager(host=host, port=int(port), password=password) else: # UNIX Socket self._m = manager.manager(path=addr, password=password) # Test connection self.getpid() except Exception, e: raise Exception(str(e))
def initialize(self): """アプリを初期化する。""" #実行環境の取得(exeファイルorインタプリタ) self.frozen=hasattr(sys,"frozen") self.InitLogger() self.LoadSettings() locale.setlocale(locale.LC_TIME,self.config["general"]["locale"]) self.SetTimeZone() self.InitTranslation() # 音声読み上げの準備 reader=self.config["autoReadingOptions"]["output"] if(reader=="PCTK"): self.log.info("use reader 'PCTalker'") self.speech=accessible_output2.outputs.pc_talker.PCTalker() elif(reader=="NVDA"): self.log.info("use reader 'NVDA'") self.speech=accessible_output2.outputs.nvda.NVDA() #SAPI4はバグってるっぽいので無効にしておく #elif(reader=="SAPI4"): #self.log.info("use reader 'SAPI4'") #self.speech=accessible_output2.outputs.sapi4.Sapi4() elif(reader=="SAPI5"): self.log.info("use reader 'SAPI5'") self.speech=accessible_output2.outputs.sapi5.SAPI5() elif(reader=="AUTO"): self.log.info("use reader 'AUTO'") self.speech=accessible_output2.outputs.auto.Auto() elif(reader=="JAWS"): self.log.info("use reader 'JAWS'") self.speech=accessible_output2.outputs.jaws.Jaws() elif(reader=="CLIPBOARD"): self.log.info("use reader 'CLIPBOARD'") self.speech=accessible_output2.outputs.clipboard.Clipboard() elif(reader=="NOSPEECH"): self.log.info("use reader 'NOSPEECH'") self.speech=accessible_output2.outputs.nospeech.NoSpeech() else: self.config.set("speech","reader","AUTO") self.log.warning("Setting missed! speech.reader reset to 'AUTO'") self.speech=accessible_output2.outputs.auto.Auto() # メインビューを表示 self.hMainView=main.MainView() self.hMainView.Show() self.Manager = manager.manager(self.hMainView) return True
def __init__(self): #read config, create connections self.db_config = {} ini_parser = configparser.ConfigParser() ini_parser.read("config.ini", 'utf-8') for section in ini_parser.sections(): self.db_config[section] = {} for option in ini_parser.options(section): self.db_config[section][option] = ini_parser.get(section,option) try: self.db_connection_from = dbConnection(self.db_config['source_db']) self.db_connection_to = dbConnection(self.db_config['target_db']) self.db_connection_target = dbConnection(self.db_config['target_db'], False) except dbException: sys.exit(1) self.informationParser = manager()
def __init__(self, parent=None, f=0): super(AddDialog, self).__init__(parent=parent, f=f) wrap = QtGui.QVBoxLayout() horiz = QtGui.QHBoxLayout() wrap.addLayout(horiz, 10) buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) ok = buttons.button(QtGui.QDialogButtonBox.StandardButton.Ok) cancel = buttons.button(QtGui.QDialogButtonBox.StandardButton.Cancel) ok.setDefault(True) cancel.setDefault(False) wrap.addWidget(buttons) self.setLayout(wrap) self.tree = CDMSFileTree() tree_layout = QtGui.QVBoxLayout() toolbar = AddEditRemoveToolbar(u"Available Files", add_action=self.add_file, remove_action=self.remove_file) tree_layout.addWidget(toolbar, 0) tree_layout.addWidget(self.tree, 10) m = manager() for f in m.files: self.tree.add_file(m.files[f]) m.addedFile.connect(self.addFileToTree) horiz.addLayout(tree_layout, 2) self.chooser = CDMSFileChooser() self.chooser.accepted.connect(self.added_files)
def get_tasks(): lenght = float(request.form['lenght']) bredth = float(request.form['bredth']) # check if the post request has the file part if 'file' not in request.files: flash('No file part') file = request.files['image'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': flash('No selected file') # return redirect(request.url) if file and allowed_file(file.filename): filename = str(uuid.uuid4()) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # return redirect(url_for('uploaded_file', # filename=filename)) image=UPLOAD_FOLDER+filename no_of_colors = int(request.form['no_of_colors']) result = manager.manager(lenght, bredth, image, no_of_colors).valueTaker() area=float(result[1]) tasks = [] for values in result[0]: percent=values[0] percentNum = str(percent[:-1]) color=values[1] hashVal=values[2] areaPercent=float(percentNum)*area/100 task1=[ { 'percent':percent, 'color':color, 'hash':hashVal, 'areaPercent':areaPercent, }, ] tasks.append(task1) return jsonify({'tasks': tasks})
def initialize(self): _import() """アプリを初期化する。""" self.setGlobalVars() self.proxyEnviron = proxyUtil.virtualProxyEnviron() self.setProxyEnviron() self.installThreadExcepthook() # update関係を準備 if self.config.getboolean("general", "update"): globalVars.update.update(True) self.hMainView = main.MainView() if self.config.getboolean(self.hMainView.identifier, "maximized", False): self.hMainView.hFrame.Maximize() self.hMainView.Show() self.accountManager = twitcasting.accountManager.AccountManager() self.hasAccountIssue = False self.Manager = manager.manager(self.hMainView) if len(self.accountManager.tokens) == 0: simpleDialog.dialog( _("アカウント登録"), _("アカウントが登録されていません。ライブに接続する前に、設定メニューのアカウントマネージャからアカウントの登録を行ってください。" )) self.hasAccountIssue = True return True for i in self.accountManager.tokens: if datetime.datetime.now().timestamp() > i["expires_at"]: simpleDialog.dialog( "", _("期限が切れたトークンが見つかりました。設定メニューのアカウントマネージャから、再度アカウントの追加を行ってください。" )) self.accountManager.deleteAccount( self.accountManager.tokens.index(i)) self.hasAccountIssue = True if len(sys.argv) == 2: self.hMainView.Clear() self.Manager.connect(sys.argv[1]) return True if self.hasAccountIssue == False and self.config.getboolean( "general", "autoconnect", True) == True: self.hMainView.events.connect() return True
def updatemanager(self): import manager con = db.createconnection() self.a = self.txtusername.text() self.b = self.txtphone.text() self.c = self.txtdob.text() self.d = self.txtaddress.text() self.e = self.txtcity.text() self.f = self.txtcollege.text() query = "update managerprofile set Name=%s,Phone=%s,DoB=%s,Address=%s,City=%s,College=%s where UserId=%s" cursor = con.cursor() cursor.execute( query, (self.a, self.b, self.c, self.d, self.e, self.f, self.userid)) con.commit() self.back = manager.manager() self.back.show() self.back.lbluser.setText(self.userid) self.close()
def __init__(self): #read config, create connections self.db_config = {} ini_parser = configparser.ConfigParser() ini_parser.read("config.ini", 'utf-8') for section in ini_parser.sections(): self.db_config[section] = {} for option in ini_parser.options(section): self.db_config[section][option] = ini_parser.get( section, option) try: self.db_connection_from = dbConnection(self.db_config['source_db']) self.db_connection_to = dbConnection(self.db_config['target_db']) self.db_connection_target = dbConnection( self.db_config['target_db'], False) except dbException: sys.exit(1) self.informationParser = manager()
def main(): """ Parser Options """ parser = OptionParser (option_class=eng_option) manager.add_parser_options (parser) (options, args) = parser.parse_args () if len(args)!=0: parser.print_help() sys.exit(1) phy = PyHydra.transceiver(options) mpif = PyHydra.mpif_impl(options) mpif.set_transceiver(phy) g = PyHydra.FuncThread(phy.run) g.start() mpif.start() mgr = manager(options) mgr.SetMPIF(mpif) h = PyHydra.FuncThread(bar, "bar", mgr, mgr.control) h.setDaemon(1) h.start() mgr.run()
import manager if __name__ == '__main__': new_manager = manager.manager() new_manager.run()
def __init__(self): """Initialize the interperter""" self._logger = logger.logger() self._manager = manager.manager(self._logger)
#!/usr/bin/env python # -*- coding: utf-8 -*- from telegram import Updater import telegram import logging from manager import manager from datetime import datetime from mods import logger_sys as log from time import sleep id_channel = -116368010 id_priva = 84340477 man = manager() logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.WARNING) logger = logging.getLogger(__name__) def packet(p,a): name = p.message.from_user.username id = p.message.chat_id text = p.message.text msg_id = p.message.message_id return {"name":name,"id":id,"text":text,"args":a, "msg_id": msg_id} def get_print_time(): return "%s:%s" % (datetime.now().hour, datetime.now().minute) def brew(bot,update,args): p = packet(update,args) man.queue_coffee(p) print("%s - Brew %s" % (get_print_time(), p["name"])) def brew_timer(bot):
import time import cPickle import parser import sys import manager import subindex import config PENDING = 0 RUNNING = 1 CHECKING = 2 doc_dic = {} docid = 0 mgr = manager.manager() #COUNTNUM = 12000 COUNTNUM = 500 COUNTNUM_L = 20 mgrcount = 0 def blockmanage(docid, parsed_data): global mgr, mgrcount print(mgrcount) mgrcount += 1 if mgr.state == PENDING: block = subindex.subindex(mgr.blocknum, config.DATAPATH) mgr.blocknum += 1 mgr.block.append(block)
count_limit.set('请输入运行次数') time_limit = tk.StringVar() time_limit.set('请输入运行时间(分钟)') win_name = tk.StringVar() win_name.set('请输入模拟器窗口名(默认MuMu)') recharge_num = tk.StringVar() recharge_num.set('请输入碎石数量') ratio = tk.StringVar() ratio.set('请输入系统缩放倍率(默认1.5)') w = 400 h = 300 auto = manager("明日方舟 - MuMu模拟器") status_message = tk.StringVar() status_message.set(auto.status_message) time_message = tk.StringVar() time_message.set(auto.time_message) entry_win_name = tk.Entry(window, textvariable=win_name,width = 35, font=("微软雅黑", 14)) entry_win_name.pack(anchor='center') entry_ratio = tk.Entry(window, textvariable=ratio, width = 35, font=("微软雅黑", 14)) entry_ratio.pack(anchor='center') entry_recharge_num = tk.Entry(window, textvariable=recharge_num, width = 35, font=("微软雅黑", 14)) entry_recharge_num.pack(anchor='center') entry_count_limit = tk.Entry(window, textvariable=count_limit, width = 35, font=("微软雅黑", 14)) entry_count_limit.pack(anchor='center')
import shelve from person import person from manager import manager bob=person('bob smith',42,30000,'sweng') sue=person('sue jones',45,40000,'music') tom=manager('tom doe',50,50000) db=shelve.open('class-shelve') db['bob']=bob db['sue']=sue db['tom']=tom db.close()
elif this_time - self.last_time > self.interval: self.send(this_time) return done """listener args are [port]""" class listener(manager.worker): def setup(self): self.port = self.args[0] self.soc = socket(AF_INET, SOCK_DGRAM) self.soc.bind(('', self.port)) self.soc.settimeout(0.1) self.soc.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) def work(self): try: data, address = self.soc.recvfrom(1024) except timeout: return False else: self.queue.append(("listener", data, address)) return False #this thread will never finish, it will only be killed by the others if __name__ == "__main__": prog = manager.manager() prog.add_thread(listener, 12345) prog.add_thread(broadcaster, 12345, "This is all you get", -1) prog.add_thread(broadcaster, 12345, "hello", 1) prog.start_threads() prog.run()
def check_services(self): mng = manager(self.conf) self.rpc_srv.set_procs_running(self.token, mng.get_list())
import flask import gerador import random import manager from flask import request from flask_socketio import SocketIO import json app = flask.Flask('servidor') m = manager.manager() socketio = SocketIO(app) @app.route("/solucao", methods=['POST']) def solucao(): sol = m.parseSolution(request.data) m.registerSolution(sol) #print(m.d[sol["uuid"]]) return flask.jsonify({"status": "ok"}) @app.route("/") def index(): idGrupo = request.args.get("idGrupo") #p = random.randint(1,3) p = 3 if p == 1: prob = gerador.geraProblema1() elif p == 2: prob = gerador.geraProblema2()
"123", "123", "123", "123", ] print("1==>login as manager") print("2==>login as staff") print("3==>quit") ch = int(input("enter the choice")) flag = 0 if (ch == 1): user = input("enter the user id") pasw = input("enter the password") if (user == "admin"): if (pasw == "admin123"): manager() else: flag = 1 else: flag = 1 if (flag == 1): print("wrong admin userid or password") elif (ch == 2): user = input("enter the user id") pasw = input("enter the password") len1 = len(l1) for i in range(0, len1): if (l1[i] == user): if (l2[i] == pasw): if (user == "nimit"): while (True):
def main(): # use MW_HOME to find etc/ & var/ directories path = getenv('MW_HOME') if path == None: stderr.write("MW_HOME not set in environment, program cannot start.") _exit(1) logging.config.fileConfig('/'.join([path, 'etc', 'logging.conf']), disable_existing_loggers=False) config = parse_config('/'.join([path, 'etc', 'vddb_async.conf'])) start_dbpc(config, 'task_manager') # make db connection pool, assign 1 connection to each db accessing thread # kingship checker + db loader + task fetcher + # task cleanup : a total of 4 threads, + 1 manager thread pool db_pool = make_db_pool(config, DB_RESERVE_CONN + int(config['cleaner_threads_num'])) # kingship granted event, all threads wait till this event is set hbase_pool = make_hbase_pool(config) kev = Event() kev.clear() # db load finished eventm all threads wait till this event is set lev = Event() lev.clear() # conditions each thread wait on, named after the waiter fetch_cond = Condition(Lock()) pick_cond = Condition(Lock()) manage_cond = Condition(Lock()) clean_cond = Condition(Lock()) # kingship checker check = Thread(target=check_kingship, args=(config, db_pool, kev, config['tm_module_name'], # NOTE: if task manager stops working for X minutes, the # tasks won't be scheduled and executed for X # minutes since tasks have to be finished in a # timely fashion, the task manager master timeout # should not be too long int(config['tm_master_timeout']), logging.getLogger('mwtm_tmcheck'))) check.start() # all other threads wait here kev.wait() # this event is never cleared #assert kev.isSet() # worker threads, created in dependence order fetch = fetcher(config, db_pool, fetch_cond, pick_cond) clean = cleaner_cluster(config, db_pool, hbase_pool, clean_cond, manage_cond) manage = manager(config, db_pool, manage_cond, pick_cond, clean) pick = picker(config, pick_cond, fetch, manage) # db config observers, loader will notify them when there's new data loaded observers = [fetch, pick, manage, clean] load = Thread(target=load_database, args=(config, db_pool, lev, observers)) # start the loader, and make other threads wait for the first load load.start() lev.wait() assert lev.isSet() # start all other threads fetch.start() clean.start() manage.start() pick.start()
import alarms import datetime import manager import pickle try: with open('manager_data.pkl', 'rb') as manager_file: mngr = pickle.load(manager_file) except FileNotFoundError: mngr = manager.manager() except Exception: print("WARNING: Alarm file impossible to load.") mngr = manager.manager() print("Program Test") while True: command = input() if len(command) == 0: print('') elif command == "help": print( "Commands:\nadd <name> <hour:minute> <repeat (Y/N)> <year/month/day> <songFile> \nlist {alarmNumber} \nedit <index> <atrib> <value>\nrem <index>" ) elif command.split()[0] == "add": try: clName = command.split()[1] clHour = command.split()[2].split(':')[0] clMinute = command.split()[2].split(':')[1] if command.split()[3] == 'Y': clRep = True
import tkinter from tkinter import messagebox from manager import manager import datetime from textblob import TextBlob import matplotlib matplotlib.use("TKAgg") import matplotlib.pyplot as plt #button(window,text = "Text", width = 12, bg = "black", fg = "white", command = def) #button.place(x,y) #tkinter.messagebox.showinfo("Title","Text") man = manager() def log(x): man.logentry(x) rating = str(round(TextBlob(x).polarity,1)) man.logRating(rating) man.logDates(str(datetime.date.today())) def analyze(): plt.plot(man.getX(),man.getY()) plt.xlabel("Entry Dates") plt.ylabel("Happiness Rating") plt.title("Emotional Analysis") plt.show() def journ():
def get_selected(self): if self.tabs.current_row() == 0: files = [] for fpath in self.file_browser.get_selected_files(): files.append(manager().get_file(fpath)) return files
def sendtomanager(cont): man = manager() man.logentry(cont)
def employee(root): def store(v): if e1.get() == "" or e2.get() == "": #Condition to check Empty Fields messagebox.showinfo("ERROR3", "Each Field is Mandatory") else: res = [] p.execute('''select username from employee1''') result = p.fetchall() for row in result: if row[0] == e1.get(): p.execute( "select password from employee1 where username='******';") result1 = p.fetchall() name = e1.get() if result1[0][0] == e2.get(): messagebox.showinfo("Success", "Logged In Successfully") p.execute( "select designation from employee1 where username='******';") result2 = p.fetchall() desig = result2[0][0] e1.delete(0, 'end') e2.delete(0, 'end') login.login(v, root, name, desig) break else: flag = False p.execute("select username from employee1") res = p.fetchall() for row in res: if row[0] == e1.get(): flag = True #print(flag) if flag == False: messagebox.showinfo("Error", "Wrong Username") else: flag = False p.execute( "select password from employee1 where username='******';") res1 = p.fetchall() for row in res1: if row[0] == e2.get(): flag = True #print(flag) if flag == False: messagebox.showinfo("Error", "Wrong password") v.deiconify() i = 3 v = Toplevel(root) v.title("employee") v.minsize(1250, 700) background_img = PhotoImage(file="./bg1.png") background_label = Label(v, image=background_img) background_label.pack(fill=BOTH, expand=True) #employee="employee" #print(employee) #BUTTON b1 = Button(v, bg="steelblue2", fg="black", text='HOME', font="Bold 10", pady=3.0, relief=FLAT, height=1, width=15, command=lambda: home(root, v)) b1.place(x=600, y=20) b2 = Button(v, bg="steelblue2", fg="black", text='MANAGER', font="Bold 10", pady=3.0, relief=FLAT, height=1, width=15, command=lambda: manager.manager(v)) b2.place(x=750, y=20) b3 = Button(v, bg="white", fg="black", text='EMPLOYEE', font="Bold 10", pady=3.0, relief=GROOVE, height=1, width=15) b3.place(x=900, y=20) b4 = Button(v, bg="steelblue2", fg="black", text='ACCOUNT DETAILS', font="Bold 10", pady=3.0, relief=FLAT, height=1, width=15, command=lambda: admin.admin(v)) b4.place(x=1050, y=20) l1 = Label(v, font="Bold 15", fg="BLACK", bg="lightcyan", text="Username: "******"Bold 15", fg="BLACK", bg="lightcyan", text="Password : "******"*") l1.place(x=500, y=250) l2.place(x=500, y=300) e1.place(x=700, y=250) e2.place(x=700, y=300) b5 = Button(v, bg="DEEP SKY BLUE", fg="Black", text='LOGIN', font="Bold 10", pady=3.0, relief=RAISED, height=1, width=15, command=lambda: store(v)) b5.place(x=600, y=350) b6 = Button(v, bg="lightcyan", fg="NAVY BLUE", text='New User? Sign Up Here.', font="Bold 15", pady=3.0, relief=FLAT, height=1, width=20, command=lambda: signup.signup(v, root, "employee1")) b6.place(x=580, y=390) #c=con.cursor() #result=c.execute('''select * from employee1''') '''con.commit() for row in result: print(row[0],end=', ') print(row[1],end=', ') print(row[2],end=', ') print(row[3],end=', ') print(row[4])''' root.withdraw() v.mainloop() return v
from manager import manager from engineer3 import engineer3 from task3 import task3 mSkill = 5.0 mCat = 1.0 mTimeliness = 1.0 mInsight = 1.0 m = manager(mSkill, mCat, mTimeliness, mInsight) engSkill = 5.0 engCat = 1.0 timeliness = 1.0 # spawn the engineers e0 = engineer3('e0', engSkill, engCat) e1 = engineer3('e1', engSkill, engCat) e2 = engineer3('e2', engSkill, engCat) # set up the first task diff = 5.0 cat = 1.0 prio = 1.0 days = 100 # make our test task t0 = task3(diff, cat, prio, days, 't0') t1 = task3(diff, cat, prio, days, 't1') t2 = task3(diff, cat, prio, days, 't2') t3 = task3(diff, cat, prio, days, 't3') t4 = task3(diff, cat, prio, days, 't4')
pady=3.0, relief=FLAT, height=1, width=15) b1.place(x=600, y=20) b2 = Button(root, bg="firebrick4", fg="white", text='MANAGER', font="Bold 10", pady=3.0, relief=FLAT, height=1, width=15, command=lambda: manager.manager(root)) b2.place(x=750, y=20) b3 = Button(root, bg="firebrick4", fg="white", text='EMPLOYEE', font="Bold 10", pady=3.0, relief=FLAT, height=1, width=15, command=lambda: employee.employee(root)) b3.place(x=900, y=20) b4 = Button(root,
def main(): # use MW_HOME to find etc/ & var/ directories path = getenv('MW_HOME') if path == None: stderr.write("MW_HOME not set in environment, program cannot start.") _exit(1) logging.config.fileConfig('/'.join([path, 'etc', 'logging.conf']), disable_existing_loggers=False) config = parse_config('/'.join([path, 'etc', 'vddb_async.conf'])) start_dbpc(config, 'task_manager') # make db connection pool, assign 1 connection to each db accessing thread # kingship checker + db loader + task fetcher + # task cleanup : a total of 4 threads, + 1 manager thread pool db_pool = make_db_pool( config, DB_RESERVE_CONN + int(config['cleaner_threads_num'])) # kingship granted event, all threads wait till this event is set hbase_pool = make_hbase_pool(config) kev = Event() kev.clear() # db load finished eventm all threads wait till this event is set lev = Event() lev.clear() # conditions each thread wait on, named after the waiter fetch_cond = Condition(Lock()) pick_cond = Condition(Lock()) manage_cond = Condition(Lock()) clean_cond = Condition(Lock()) # kingship checker check = Thread( target=check_kingship, args=( config, db_pool, kev, config['tm_module_name'], # NOTE: if task manager stops working for X minutes, the # tasks won't be scheduled and executed for X # minutes since tasks have to be finished in a # timely fashion, the task manager master timeout # should not be too long int(config['tm_master_timeout']), logging.getLogger('mwtm_tmcheck'))) check.start() # all other threads wait here kev.wait() # this event is never cleared #assert kev.isSet() # worker threads, created in dependence order fetch = fetcher(config, db_pool, fetch_cond, pick_cond) clean = cleaner_cluster(config, db_pool, hbase_pool, clean_cond, manage_cond) manage = manager(config, db_pool, manage_cond, pick_cond, clean) pick = picker(config, pick_cond, fetch, manage) # db config observers, loader will notify them when there's new data loaded observers = [fetch, pick, manage, clean] load = Thread(target=load_database, args=(config, db_pool, lev, observers)) # start the loader, and make other threads wait for the first load load.start() lev.wait() assert lev.isSet() # start all other threads fetch.start() clean.start() manage.start() pick.start()
def home(): form = ReusableForm(request.form) # print form.errors if request.method == 'POST': lenght=float(request.form['lenght']) bredth=float(request.form['bredth']) no_of_colors=int(request.form['no_of_colors']) ############################################## if 'file' not in request.files: flash('No file part') file = request.files['image'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = str(uuid.uuid4()) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) image=UPLOAD_FOLDER+filename image=UPLOAD_FOLDER+filename result = manager.manager(lenght, bredth, image, no_of_colors).valueTaker() area=float(result[1]) tasks = [] for values in result[0]: percent=values[0] percentNum = str(percent[:-1]) color=values[1] hashVal=values[2] areaPercent=float(percentNum)*area/100 task1=[ { 'percent':percent, 'color':color, 'hash':hashVal, 'areaPercent':areaPercent, }, ] tasks.append(task1) # print(tasks) database=mydatabase.databse().material() final=[tasks,database] return render_template('result.html', my_objects=final) if form.validate(): # Save the comment here. flash('Thanks for registration ') else: flash('Error: All the form fields are required. ') return render_template('hello.html', form=form)
def main(): sampleFamily = family.family() sampleFamily.addManager(manager.manager()) sampleFamily.addCitizen(citizen.citizen()) print"Created a family" sampleFamily.show()
import manager if __name__ != "__main__": __name__ = "__main__" if __name__ == "__main__": # master = manager.manager(domain = "ilazycat.com") # master.execute(tasks = ['http://ilazycat.com/']) master = manager.manager(thread_size = 10, domain = "121.") master.execute(tasks = ['http://villanch.top/'])