Exemplo n.º 1
0
def update_announcement(aid):
    try:
        if request.json:
            for key in announcement_keys:
                if key not in request.json:
                    return jsonify({
                        "error":
                        "Paramenter {0} missing in request".format(key)
                    })
            if int(request.json['platformid']) > 0:
                result = dbm.edit_platform_announcement(
                    request.json['a_img'], request.json['a_title'],
                    request.json['active'], request.json['aid'],
                    request.json['platformid'])
            else:
                result = dbm.edit_store_announcement(request.json['a_img'],
                                                     request.json['a_title'],
                                                     request.json['active'],
                                                     request.json['aid'])
            return jsonify({'aid': result})
        else:
            return bad_request()
    except Exception as e:
        print e.message
        return internal_server_error()
Exemplo n.º 2
0
def update_payment(userid, payment_methodid):
    try:
        if request.method == 'PUT':
            if request.json:
                payment_keys = post_payment_keys
                payment_keys.append('ppreferred')
                for key in payment_keys:
                    if key not in request.json:
                        return missing_parameters_error()
                errors = validate_payment(request.json)
                if errors:
                    return jsonify({'Errors': errors}), 400
                billing_addressid = dbm.fetch_user_preferences(
                    userid)['billing_address']['aid']
                if billing_addressid:
                    pid = dbm.update_payment_method(userid, payment_methodid,
                                                    request.json,
                                                    billing_addressid)
                    return jsonify({'payment_methodid': pid}), 201
                else:
                    return jsonify({
                        'Error':
                        'Preferred Billing Address Not Found For User {0}'.
                        format(userid)
                    }), 400
            return bad_request()
        elif request.method == 'DELETE':
            result = dbm.deactivate_user_payment_method(
                userid, payment_methodid)
            if result:
                return jsonify(result)
            return bad_request()
    except Exception as e:
        print e.message
        return internal_server_error()
 def __init__(self, windowSize):
     self.windowSize = windowSize
     self.dbManager = DBManager()
     self.dictionary = self.dbManager.selectDictionaryDB()
     self.isWindowValid = self.dbManager.isWindowValid(self.windowSize)
     self.analyzer = Analyzer(self.windowSize, self.dictionary)
     self.analyzer.fillMatrixSearch(self.dbManager.coocToDictWindow(self.windowSize))
Exemplo n.º 4
0
def signIn(sock):
    while True:
        # 接受用户名
        try:
            userName = sock.recv(20).decode(coding)
        # Windows 用户断开链接
        except ConnectionResetError:
            return sock
        # Linux 用户断开链接
        if not userName:
            return sock
        # 用户不存在返回False 提示 注册
        if not DBManager.existent(userName):
            sock.send('0'.encode(coding))
            if sock.recv(1).decode(coding) == 'Y':
                # 注册函数
                signUp(sock)
            continue
        else:
            sock.send('1'.encode(coding))
            break
    for x in range(3):
        # 等待登陆密码
        signInPasswd = sock.recv(32).decode(coding)
        # 匹配登陆密码
        match = DBManager.match(userName, signInPasswd)
        if match:
            sock.send('1'.encode(coding))
            break
        sock.send('0'.encode(coding))
        if x == 2:
            return sock
    # 保存客户端信息
    sockDict[userName] = sock
    return userName
Exemplo n.º 5
0
def get_patients():

    # Can't be triggered by normal app use
    if not all(param in request.args for param in ('test_selection', )):
        return jsonify({
            'errors': {
                'missing_fields': 'Please supply all required fields'
            }
        }), 400

    tester_id = DBManager.get_logged_in_tester_id(request.cookies['sessionID'])
    # tester_id should never be None; this can only happen if the
    # tester is deleted after the first DBManager function call
    # (i.e. in is_logged_in) but before the second
    if tester_id == None:
        tester_id = -1

    patient_type = request.args.get(
        'patient_type') if 'patient_type' in request.args else None
    test_selection = int(request.args.get('test_selection')) == 1

    patients = DBManager.get_patients(tester_id,
                                      patient_type=patient_type,
                                      test_selection=test_selection)

    return jsonify({"Patients": patients})
Exemplo n.º 6
0
	def POST(self):
		"""
		This function generates different html pages based on the buttons pressed by the user. From this screen, the player can choose to load a previous game or start a new one.

		Parameters:
		None

		Returns:
		None
		"""
		playerStateObject = PlayerState() #Update the player state
		action = web.input() #Create web.input() to save any information the user
		if action['new'] == 'storyScreen': #Checks to see if the user pressed the button to send them to the character selection screen
			raise web.seeother('/story') #If the above is true this line renders charScreen.html
		elif action['new'] == 'loadScreen': #Checks to see if the user pressed the button to load a previous game
			if None != DBManager.getPlayerCharacterActionFromDB(playerStateObject.player_id): #If the above is true this line checks to see if the player has chosen a character in their previous game
				if None != DBManager.getPlayerStoryActionFromDB(playerStateObject.player_id): #If the above is true this line checks to see if the player has chosen a story in their previous game
					raise web.seeother('/load') #If the above is true this line renders gameScreen.html
				else:
					raise web.seeother('/load') #If the conditional on line 65 is false then the story selection screen for the players chosen character is rendered
			else:
				raise web.seeother('/load') #If the conditional on line 64 is false then the character selection screen is rendered
		elif action['new'] == 'aboutScreen': #This conditional checks to see if the user pressed the button to go to the about screen
			raise web.seeother('/about') #If the above conditional is true this line renders aboutScreen.html
		elif action['new'] == 'helpScreen': #This conditional checks to see if the user pressed the button to go to the help screen
			raise web.seeother('/help') #If the above is true then helpScreen.html is rendered
Exemplo n.º 7
0
def unlock_patient():

    # Can't be triggered by normal app use
    if not all(param in request.json for param in ('patient_id', 'password')):
        return jsonify({
            'errors': {
                'missing_fields': 'Please supply all required fields'
            }
        }), 400

    patient_id = int(request.json['patient_id'])
    password = request.json['password']

    password_hash = DBManager.get_patient_password_hash(patient_id)
    is_blind = DBManager.is_patient_blind(patient_id)

    if password_hash and check_password_hash(password_hash,
                                             password) and not is_blind:
        tester_id = DBManager.get_logged_in_tester_id(
            request.cookies['sessionID'])
        DBManager.unlock_patient(tester_id, patient_id)
        response = jsonify({'unlock_successful': True})
    else:
        response = jsonify({'unlock_successful': False})

    return response, 201
Exemplo n.º 8
0
def user_address(userid):
    try:
        if request.method == 'GET':
            address = dbm.fetch_user_address(userid)
            if address:
                return jsonify(address)
            return not_found()
        elif request.method == 'POST':
            if request.json:
                address_keys = post_address_keys
                address_keys.append('apreferred')
                address_keys.append('atype')
                for key in address_keys:
                    if key not in request.json:
                        return missing_parameters_error()
                errors = validate_address(request.json)
                if errors:
                    return jsonify({'Errors': errors}), 400

                if request.json[
                        'atype'] == 'billing' and 'pid' not in request.json:
                    return jsonify({'Errors': "Missing Payment Method."}), 400

                new_address_id = dbm.create_user_address(userid, request.json)
                return jsonify({'aid': new_address_id}), 201
            else:
                return missing_parameters_error()
    except Exception as e:
        print e.message
        return internal_server_error()
Exemplo n.º 9
0
def daily_job():
    DBManager.update_today()
    content = InfoHandler.pack_daily_content()
    receivers = DBManager.get_auditors()
    MailSender.send(receivers, 'Daily LeetCode Notice', content, True)
    DBManager.update_yestoday()
    print("daily job done")
    return
Exemplo n.º 10
0
 def lista_insert(self):
     banco = DBManager()
     listabanco = banco.consulta_tabela()
     for pos, linha in enumerate(listabanco):
         self.__lista_listbox[0].insert(END, listabanco[pos][0])
         self.__lista_listbox[1].insert(END, listabanco[pos][1])
         self.__lista_listbox[2].insert(END, listabanco[pos][2])
         self.__lista_listbox[3].insert(END, listabanco[pos][4])
Exemplo n.º 11
0
def minus_job(user):
    """
    Removes a job to a user
    :param user:
    """
    userdb = DBManager.get_user(user)
    new_jobs = userdb['jobs'] - 1
    DBManager.update_user(user, new_jobs, userdb['reputation'])
Exemplo n.º 12
0
def plus_job(user):
    """
    Adds a job to a user
    :param user:
    """
    userdb = DBManager.get_user(user)
    new_jobs = userdb['jobs'] + 1
    DBManager.update_user(user, new_jobs, userdb['reputation'])
Exemplo n.º 13
0
def newGenre(series):
	genres = series['genres'].strip('|').split('|')
	for genre in genres:
		DB.storeData('genre',{'tag':genre,'genreid':'NULL'})
		result = DB.selectWhere('genre','tag',genre,genreid)
		if result:
			DB.storeData('genre_relation',{'genreid':result[0][0]
				,'seriesid':series['seriesid']})
Exemplo n.º 14
0
    def set_veiculo(self):
        data = datetime.today()
        banco = DBManager()

        banco.inserir_veiculo(self.__edPlaca.get().upper(), data, self.__tipo)
        messagebox.showinfo('Aviso', 'Veículo inserido com sucesso!')
        self.__edPlaca.focus_force()
        self.__edPlaca.delete(0, END)
    def __init__(self):
        print ("Calling parent constructor")

        self.con = DBManager.connectDB()
        self.engine = DBManager.createEngine()
        self.cur = self.con.cursor()
        self.qd_exception_list = []
        self.fr_exception_list = []
Exemplo n.º 16
0
def minus_rep(user, decrease=1):
    """
    Removes rep from a user
    :param decrease:
    :param user:
    """
    userdb = DBManager.get_user(user)
    new_rep = userdb['reputation'] - decrease
    DBManager.update_user(user, userdb['jobs'], new_rep)
Exemplo n.º 17
0
 def __init__(self):
     self._DBHandle = DBManager()
     self._DBCur = self._DBHandle.getDBCur()
     self._DBCon = self._DBHandle.getDBCon()
     self._URLInstance = URLBuilder()
     self._code = ""
     self._Component = ""
     self._fileSet = set()
     pass
Exemplo n.º 18
0
def plus_rep(user, increase=1):
    """
    Adds rep to a user
    :param increase:
    :param user:
    """
    userdb = DBManager.get_user(user)
    new_rep = userdb['reputation'] + increase
    DBManager.update_user(user, userdb['jobs'], new_rep)
Exemplo n.º 19
0
 def pagar(self):
     banco = DBManager()
     # recupera a id do usuário do banco em forma de tupla
     id_usuario = banco.consulta_tabela_funcionarioid(self.__usuario)
     #registra no banco os dados do pagamento
     banco.pagar(Calcular.__placa, self.setPlaca(), id_usuario[0])
     #limpa a caixa de texto edplaca
     self.__edplaca.delete(0, END)
     #mensagem de aviso para pagamento realizado
     messagebox.showinfo("Aviso", "Pagamento registrado!")
Exemplo n.º 20
0
    def applyJob(self, jobid, jobname):
        result = messagebox.askquestion(
            "Applying for job: " + jobname,
            "Your resume will be shared to the poster. Apply?")

        if result == 'yes':
            db = DBManager()
            try:
                userInfo = db.run(
                    "SELECT * FROM APPLICANT WHERE USERNAME = %s;",
                    (self.user.username, ))
                db.run(
                    "INSERT INTO APPLICATIONS VALUES(%s, %s, %s, %s, %s, %s);",
                    (
                        int(jobid),
                        userInfo[0][2],
                        userInfo[0][0],
                        userInfo[0][1],
                        userInfo[0][3],
                        userInfo[0][4],
                    ))
                db.close()
                messagebox.showinfo("APPLIED",
                                    "Your application has been sent.")

            except Exception as e:
                print(e)
                db.close()
                messagebox.showerror("ERROR", e)
Exemplo n.º 21
0
    def __get_hora_entrada(self, placa):
        try:
            banco = DBManager()
            entrada = banco.consulta_placa(placa)
            Calcular.__entrada = datetime.strptime(entrada[0], '%Y-%m-%d %H:%M:%S.%f')
            return Calcular.__entrada

        except TypeError:
            messagebox.showinfo("Aviso", "Placa não consta no sistema")
            self.__edplaca.delete(0, END)
            self.__edplaca.focus_force()
Exemplo n.º 22
0
def create_test():

    # Can't be triggered by normal app use
    if not all(param in request.json
               for param in ('app', 'patient_id', 'test_date')):
        return jsonify({
            'errors': {
                'missing_fields': 'Please supply all required fields'
            }
        }), 400

    test = {
        'app':
        request.json['app'],
        'patient_id':
        int(request.json['patient_id']),
        'tester_id':
        DBManager.get_logged_in_tester_id(request.cookies['sessionID']),
        'test_date':
        request.json['test_date']
    }

    if test['patient_id'] == 0:
        test['patient_id'] = DBManager.create_patient({
            'patient_type':
            'anonymous',
            'visible_patient_id':
            datetime.datetime.fromtimestamp(
                time.time()).strftime('%Y-%m-%d %H:%M:%S'),
            'group':
            '',
            'name':
            '',
            'dob':
            '',
            'notes':
            '',
            'gender':
            '',
            'password_hash':
            ''
        })

    test['details'] = {}
    for key, value in request.json.iteritems():
        if key not in test:
            test['details'][key] = value

    try:
        globals()[test['app'] + '_post_process'](test)
    except KeyError, NameError:
        # Post-processing functions aren't defined for all the games
        pass
Exemplo n.º 23
0
def collect():
    print('\nCollecting @ ', datetime.now())  # current time
    start = t.time()

    articles_list = Scrape.get_articles()  # scraping data
    DBM.populate_db(articles_list)  # saving to database
    DBM.prune_db(days)  # pruning articles

    print(str(t.time() - start), 'seconds')  # timing the execution
    print('Next collection @ ~',
          datetime.now() + timedelta(minutes=min_interval),
          '\n')  # approx. next collection time
Exemplo n.º 24
0
    def __init__(self):
        self.janela = Tk()

        self.banco = DBManager()

        self.config()
        self.listaNome()
        self.lista()
        Button(self.janela, text="Voltar", command=self.voltar).grid(row=0,
                                                                     column=2)

        self.janela.mainloop()
Exemplo n.º 25
0
def user_preferences(userid):
    try:
        if request.method == 'GET':
            preferences = dbm.fetch_user_preferences(userid)
            if preferences:
                return jsonify(preferences)
            return not_found()
        elif request.method == 'PUT':
            if ('shipping_addressid' or 'billing_addressid'
                    or 'cid') not in request.json:
                return missing_parameters_error()
            errors = validate_user_preferences(request.json, userid)
            if errors:
                return jsonify({'errors': errors}), 400
            if 'shipping_addressid' in request.json:
                dbm.update_user_preferred_shipping(
                    request.json['shipping_addressid'], userid)
            if 'billing_addressid' in request.json:
                dbm.update_user_preferred_billing(
                    request.json['billing_addressid'], userid)
            if 'cid' in request.json:
                dbm.update_user_preferred_payment(request.json['cid'], userid)
            preferences = dbm.fetch_user_preferences(userid)
            if preferences:
                return jsonify(preferences)
            return bad_request()
    except Exception as e:
        print e.message
        return internal_server_error()
Exemplo n.º 26
0
def signUp(sock):
    while True:
        newUser = sock.recv(20).decode(coding)
        # 查询用户是否存在
        # 存在
        if DBManager.existent(newUser):
            sock.send('0'.encode(coding))
            continue
        # 不存在 发送1 接收密码
        sock.send('1'.encode(coding))
        passwd = sock.recv(32).decode(coding)
        DBManager.insert('userInfo', newUser, passwd)
        print('新用户:%s' % newUser)  # 日志
        break
Exemplo n.º 27
0
def delete_from_user_wish_list(userid, productid):
    try:
        if request.method == 'DELETE':
            in_wish_list = dbm.wish_list_contains(
                productid=productid, userid=userid)['product_in_wishlist']
            if in_wish_list:
                dbm.remove_from_wish_list(productid=productid, userid=userid)
                wish_list = dbm.fetch_user_wish_list(userid=userid)
                return jsonify(wish_list)
            else:
                not_found()
        elif request.method == 'POST':
            in_wish_list = dbm.wish_list_contains(
                productid=productid, userid=userid)['product_in_wishlist']
            if not in_wish_list:
                dbm.add_product_to_user_wishlist(productid=productid,
                                                 userid=userid)
                wish_list = dbm.fetch_user_wish_list(userid=userid)
                return jsonify(wish_list)
            else:
                return jsonify({
                    'error':
                    'Product {0} is already in user {1} wish list.'.format(
                        productid, userid)
                }), 400
    except Exception as e:
        print e
        return internal_server_error()
Exemplo n.º 28
0
class Patio(object):
    def __init__(self):
        self.janela = Tk()

        self.banco = DBManager()

        self.config()
        self.listaNome()
        self.lista()
        Button(self.janela, text="Voltar", command=self.voltar).grid(row=0,
                                                                     column=2)

        self.janela.mainloop()

    def voltar(self):
        self.janela.destroy()

    def listaNome(self):
        pass

    def config(self):
        self.janela.title("Listagem de Veiculos no patio")
        self.janela.geometry("620x200+450+200")
        lb = Label(self.janela, text="Veiculos com pagamento em aberto")
        lb.grid(row=0, column=0, columnspan=2)

    def lista(self):
        self.listaplaca = Listbox()
        self.listaentrada = Listbox()
        self.listapago = Listbox()
        self.listatipo = Listbox()

        self.listas = [["Placa", self.listaplaca],
                       ["Entrada", self.listaentrada],
                       ["Pago", self.listapago], ["Tipo", self.listatipo]]
        for p, linha in enumerate(self.listas):
            Label(self.janela, text=self.listas[p][0]).grid(row=2, column=p)
            linha[1] = Listbox(self.janela, width=25)
            linha[1].grid(row=3, column=p)
            self.lista_insert(p)

    def lista_insert(self, pos):
        query = [
            self.banco.consulta_tabela_veiculo_placa(),
            self.banco.consulta_tabela_veiculo_entrada(),
            self.banco.consulta_tabela_veiculo_pago(),
            self.banco.consulta_tabela_veiculo_tipo()
        ]
        for i in query[pos]:
            self.listas[pos][1].insert(END, i)
Exemplo n.º 29
0
	def GET(self):
		"""
		This function renders homeScreen.html and checks to see if player data exists in the database. If not, this is a new player and new data is inserted into the database.
		If there is player data then the existing player state is updated.

		Parameters:
		None

		Returns:
		None
		"""
		#if not DBManager.checkforExistingPlayer(web.ctx.ip): #Checking to see if current player has played before
		DBManager.getPlayerIP(web.ctx.ip) #If the above is true save the players ip address in the database
		playerStateObject = PlayerState() #Updating the player state
		return self.render.homeScreen() #Render homeScreen.html
Exemplo n.º 30
0
	def POST(self):
		"""
		This function checks to see if the home button was pressed and if it was homeScreen.html is rendered. If not, lastScreen.html stays rendered.

		Parameters:
		None

		Returns:
		None
		"""
		playerStateObject = PlayerState() #Updating the player state
		if web.input()['home']=='home': #Checks to see if the player pressed the home button
			raise web.seeother('/end') #If the above is true homeScreen.html is rendered
		else:
			DBManager.insertPlayerStepAction(playerStateObject.player_id) #If the player did not hit the home button this line records the action the player took and saves it in the database
			raise web.seeother('/end') #This line renders endScreen.html
Exemplo n.º 31
0
def on_trigger(submit_id, submit_author, comment):
    """
    On Trigger of bot
    :param submit_id:
    :param submit_author:
    :param comment:
    """
    cid = comment.id
    try:
        cauthor = comment.author.name
    except AttributeError:
        return

    cbody = comment.body.lower()
    message = cbody.split(OfferBot.TRIGGER)[1].split("\n")[0]

    if "accept" in message:
        # UserManager.plus_job(cauthor)
        reply = get_response_accept(cauthor, submit_author)
    elif "plusrep" in message:
        # UserManager.plus_rep(cauthor)
        reply = get_response_plus_rep(cauthor, submit_author)
    elif "minusrep" in message:
        reason = message.split("minusrep")[1]
        reply = get_response_minus_rep(cauthor, submit_author, reason)
    elif "done" in message:
        reply = get_response_done(cauthor, submit_author)
    else:
        reply = get_response_user(cauthor)

    if UserManager.get_rep_level(DBManager.get_user(cauthor)['reputation']) == "Scammer":
        OfferBot.bot_reply(comment, get_response_scammer(cauthor))

    OfferBot.bot_reply(comment, reply)
Exemplo n.º 32
0
	def GET(self):
		"""
		This function dynamically renders storyScreen.html when the user types in the appropriate url or navigates to the page by interacting with the website.

		Parameters:
		None

		Returns:
		None
		"""
		playerStateObject = PlayerState() #Updating the player state
		story_ids = DBManager.getStoriesFromDB(playerStateObject.player_id) #Getting story data from the database and saving it to a variable
		story_titles=DBManager.getStoryTitles(playerStateObject.player_id) #Getting story titles from the database and saving it to a variable
		walk_level=DBManager.getStoryData()[0]
		kid_friendly=DBManager.getStoryData()[1]
		return self.render.storyScreen(story_ids, story_titles, walk_level, kid_friendly) #Using the above two variables to dynamically generate storyScreen.html
Exemplo n.º 33
0
def dom0Info(xenHost):

	tool = Tools()
	db = DBManager()
	dom0 = Dom0(xenHost)
	
	# Check if dom0 contain dom0_info on db
	dom0ID = db.returnDom0Id(dom0)
	
	if dom0ID != None:
		memory = psutil.phymem_usage()
		cpuTotal = psutil.cpu_percent(interval=1, percpu=True)
		disk = psutil.disk_usage("/")
		
		dom0.id = dom0ID[0]
		dom0.memTotal = tool.convertBytes(memory.total)
		dom0.memUsed = tool.convertBytes(memory.used)
		dom0.memFree = tool.convertBytes(memory.free)
		dom0.memPercent = memory.percent
		dom0.diskTotal = tool.convertBytes(disk.total)
		dom0.diskUsed = tool.convertBytes(disk.used)
		dom0.diskFree = tool.convertBytes(disk.free)
		dom0.diskPercent = disk.percent
		dom0.cpu = tool.returnCpuInfo(cpuTotal)
		if db.checkDom0Info(str(dom0ID[0])) == None:
			db.insertDom0Info(dom0)
		else:
			db.updateDom0Info(dom0)
	else:
		print "Invalid dom0"
Exemplo n.º 34
0
 def __init__(self):
     self._DBHandle = DBManager()
     self._DBCur = self._DBHandle.getDBCur()
     self._DBCon = self._DBHandle.getDBCon()
     self._URLInstance = URLBuilder()
     self._code = ""
     self._Component = ""
     self._fileSet = set()
     pass
Exemplo n.º 35
0
	def POST(self):
		"""
		This function checks to see if the player has chosen a story and if they have the story choice is saved.

		Parameters:
		None

		Returns:
		None
		"""
		playerStateObject = PlayerState()
		action = web.input()
		if action['story']=="back":
			raise web.seeother('/')
		else:
			title=action['story']
			story_id=DBManager.getStoryIDFromTitle(title)
			DBManager.insertPlayerStoryAction(playerStateObject.player_id,story_id)
			raise web.seeother('/game')
Exemplo n.º 36
0
	def GET(self):
		"""
		This function dynamically generates the steps of the game until there are no more steps. The elements of this webpage change based on the players progress and their
		Character/Story choices.

		Parameters:
		None

		Returns:
		None
		"""
		playerStateObject = PlayerState()
		if DBManager.needLastScreen(playerStateObject.player_id)==True:
			print "need last"
			raise web.seeother('/last')
		else:
			print "not last"
		title, text, hint1, hint2, hint3, answertext = DBManager.getGameScreenDataFromDB(playerStateObject.player_id) #Assigning several variables by pulling data from the database in order to dynamically generate different bodies of text for the user
		return self.render.gameScreen(title, text, hint1, hint2, hint3, answertext) #Rendering the gameScreen.html
Exemplo n.º 37
0
    def __init__(self):
        # Mode actuel dans les différentes pièces
        self.currentMode = {"A": "AUTO", "B": "AUTO", "C": "AUTO", "D": "AUTO"}

        # Température par défaut des différentes pièces
        self.defaultTemp = {"A": 18, "B": 18, "C": 18, "D": 18}

        self.setup_gpio(param.GPIO)

        self.db = DBManager()
Exemplo n.º 38
0
	def POST(self):
		"""
		This function checks to see if the player has chosen a story and if they have the story choice is saved.

		Parameters:
		None

		Returns:
		None
		"""
		playerStateObject = PlayerState() #Updating the player state
		action = web.input() #Creating web.input() object to save any from data input by the user
		if action['story']== "back": #Checks to see if the player pressed the back button
			raise web.seeother('/home') #If the above is true then the charScreen.html is rendered
		else:
			title= action['story']
			story_id=DBManager.getStoryIDFromTitle(title)
			print story_id
			DBManager.insertPlayerStoryAction(playerStateObject.player_id,story_id) #If the above is true the story selection is inserted into the database
			raise web.seeother('/game') #Rendering gameScreen.html
Exemplo n.º 39
0
 def registerVMs(self, xenapi, session, host):
     hostRef = xenapi.session.get_this_host(session["Value"], session["Value"])["Value"]
     domURef = xenapi.host.get_resident_VMs(session["Value"], hostRef)["Value"]
     vmsList = []
     for vmRef in domURef:
         # dom0 will not be shown
         if vmRef != "00000000-0000-0000-0000-000000000000":
             vmInfoRef = xenapi.VM.get_record(session["Value"], vmRef)
             vmInfo = vmInfoRef["Value"]
             if vmInfo["HVM_boot_policy"] == "":
                 vmType = "Para-Virt"
             else:
                 vmType = "Full-Virt"
             vmMaxMemory = (int(vmInfo["memory_dynamic_max"]) / 1024) / 1024
             vmMetricRef = vmInfo["metrics"]
             vmMetric = xenapi.VM_metrics.get_record(session["Value"], vmMetricRef)
             domU = DomU(vmInfo["name_label"], vmType, vmMaxMemory, vmInfo["power_state"], host)
             vmsList.append(domU)
     db = DBManager()
     db.updateDomU(host, vmsList)
Exemplo n.º 40
0
def start():
	series = DB.dirContent()
	reqSer = []
	reqEp = {}
	for ser in series:
		res = selectWhere('series','seriesname',sub('[_\.]',' ',ser),'seriesid')
		if not :
			reqSer.append(ser)
		else:
			reqEp[ser] = []
			for ep in series[ser]:
				ep['id'] = res[0]
				if not executeSelectQuery('select * from episode where \
					seasonnumber=\'{season}\' and episodenumber=\
					\'{episode}\' and seriesid=\'{id}\''.format(**ep))
					reqEp[ser].append(ep)
	if reqSer != [] or reqEp != []:
		import StoreManager as SM
		for ser in reqSer:
			DB.newSeries(ser,series[ser])
		DB.newEpisode(reqEp)
Exemplo n.º 41
0
	def GET(self):
		"""
		This function render lastScreen.html when the player either navigates to it by interacting with the website or typing in the appropriate url.

		Parameters:
		None

		Returns:
		None
		"""
		playerStateObject = PlayerState() #Updating the player state
		title,text = DBManager.getLastScreenDataFromDB(playerStateObject.player_id) #Assigning several variables by pulling data from the database
		return self.render.lastScreen(text,title) #Rendering lastScreen.html using the variables on line 239
Exemplo n.º 42
0
def get_response_plus_rep(user, op):
    """
    OfferBot Tests
    :param user:
    """
    user_info = DBManager.get_user(user)
    rep = user_info['reputation']
    rep_string = UserManager.get_rep_level(rep)

    response = Template(config.get("offer", "plus_rep_reply"))
    response = response.substitute(username=user, username2=op, rep=rep_string, repno=rep)

    return response
Exemplo n.º 43
0
	def POST(self):
		"""
		This function responds to user input and generates the proper game screens. This function ultimately controls game flow.

		Parameters:
		None

		Returns:
		None
		"""
		playerStateObject = PlayerState() #Updating player state

		if web.input()['home']=='home': #Checking to see if the player pressed the home button
			raise web.seeother('/home') #If the above is true then homeScreen.html is rendered
		else:
			player_input= web.input()['home'] #Creating web.input() to hold user input information
			player_input= player_input.lower()
			#if DBManager.needLastScreen(playerStateObject.player_id, player_input): #Checks to see if the player has reached the end of the game and the final screen need to be displayed
			#	raise web.seeother('/last') #If the above is true then lastScreen.html is rendered
			DBManager.compareInputToAnswers(playerStateObject.player_id, player_input) #Inserting the action that the player took and inserting that information into the database
			print "compare input run"
			raise web.seeother('/game') #Rendering gameScreen.html
Exemplo n.º 44
0
    def __init__(self, pythonServer, clientSock, addr, sym_key):
        threading.Thread.__init__(self)
        self.security = Security()
        # reference to parent server
        self.pythonServer = pythonServer
        # new open socket  for client
        self.clientSock = clientSock
        # address connection : IP and Port
        self.addr = addr
        self.sym_key = None
        # Dictionary of ptotocols functions : Key - level  Value - referance to function
 #       self.operFnPtrDict = { 1 : self.oper1Fun, 2 : self.oper1Fun }
        self.AES=AESCrypt()
        self.DBManager = DBManager()
Exemplo n.º 45
0
def newSeries(name, pathDict, epFlag=0):
	"""
	newSeries(String)
	
	downloads the series info and stores it to the DB.
	"""
	seriesWhole = API.getSeries(name=name)
	series = seriesWhole['series']
	episodes = seriesWhole['episodes']
	if not epFlag:
		newGenre(series)
		newActors(series)
		newBanners('banner', series)
		DB.storeData('series', series)
	for episode in episodes:
		for ep in pathDict:
			if (ep['season'] == episode['seasonnumber'] and
				ep['season'] == episode['episodenumber']):
				episode['path'] = ep['path']
		else:
			episode['path'] = 'NULL'
		if episode['path'] != 'NULL' or not epFlag:
			_storeEpisode(episode)
Exemplo n.º 46
0
def bot_post_logic(sid, sauthor, comment):
    """
    Logic for each post
    :param sid:
    :param sauthor:
    :param comment:
    :return:
    """
    cid = comment.id
    try:
        cauthor = comment.author.name
    except AttributeError:
        return

    if cauthor.lower() == REDDIT_CLIENT.user.name.lower():
        return

    if DBManager.is_oldpost(cid):
        return
    DBManager.add_oldpost(cid)

    cbody = comment.body.lower()
    if TRIGGER.lower() in cbody:
        OfferManager.on_trigger(sid, sauthor, comment)
Exemplo n.º 47
0
	def __init__(self):
		"""
		The player state class is initialized for each player which keeps a record of the player within the DB.
		This allows for easy access to the player's information through DBManager.

		Parameters:
		Character: The player's chosen character.
		Story: The player's chosen story.

		Returns:
		Something.
		"""

		self.player_data = DBManager.getPlayerFromDB(web.ctx.ip) #Pulling all player data from the database via a unique player ip address

		self.player_id = self.player_data[0] #Pull the first element from the player_data array to obtain a player's unique id
Exemplo n.º 48
0
class DataCollecter():
    def __init__(self):
        self._DBHandle = DBManager()
        self._DBCur = self._DBHandle.getDBCur()
        self._DBCon = self._DBHandle.getDBCon()
        self._URLInstance = URLBuilder()
        self._code = ""
        self._Component = ""
        self._fileSet = set()
        pass

    def UpdateStocks(self, mark, IDHead, IDTail):
        try:
            self._DBCur.execute('''CREATE TABLE collections ''' + '''
                             (code text, recordtype text, date text, holders real, holderschangeper real, averagehold real, averageholdchangeper real, 
                             scr text, price real, averageamount real, top10hold real, top10outstandinghold real)''')
        except:
            pass

        countTmp = 0
        for x in range(IDHead,IDTail):
            urlToGet = self._URLInstance.GetURL(self.BuildCode(mark, x, 1))
            try:
                content = urllib2.urlopen(urlToGet).read()
                time.sleep(3)
                countTmp += 1
                if countTmp == 50:
                    time.sleep(6)
                    countTmp = 0
            except:
                continue
            
            self._ContentInstance = EastmoneyContent()
            self._ContentInstance.feed(content)

            self._ContentInstance.handle_listmatrix(self.BuildCode(mark, x, 0), "F10")

            #-----------------begin sqlite----------------------------
            if self._ContentInstance.listmatrix != []:
                
                for iteminlistmatrix in self._ContentInstance.listmatrix:
                    codeTmp = iteminlistmatrix[0]
                    dateTmp = iteminlistmatrix[2]
                    executeSQL = 'select * from collections where date = \"' + dateTmp + '\" and code = \"' + codeTmp + '\"'
                
                    self._DBCur.execute(executeSQL)
                    
                    SQLTmp = self._DBCur.fetchall()
                    if  SQLTmp == []:
                        executeSQL = 'INSERT INTO collections VALUES (?,?,?,?,?,?,?,?,?,?,?,?)'    
                        self._DBCur.execute(executeSQL, iteminlistmatrix)
                        self._DBCon.commit()

                print " done\n"
                self._DBCon.commit()
            else:
                print "  has none\n"


    def BuildCode(self, mark, x, mix):
        if mark == "sh":
            self._code = "6" + str(x)[-5:]
            self._Component = mark + self._code
        if mark == "sz":
            self._code = str(x)[-6:]
            self._Component = mark + self._code

        if mix == 1:
            return self._Component
        if mix == 0:
            return self._code

    def UpdateStockname(self, filename):
        x = 0
        for line in open(filename):
            if x == 0 : 
                x += 1
                continue
            x += 1
            linesplited = line.split('\t')
            executeSQL = '  update collections set name = \"' + linesplited[2] + '\" where code = ' + linesplited[1] + '  '
            self._DBCur.execute(executeSQL)
            self._DBCon.commit()
            pass

    def NewTab(self, filename):
        x = 0
        
        for line in open(filename):
            firstline = []
            pricenow = []
            if x == 0 : 
                x += 1
                firstline = line.split('\t')
                try:
                    self._DBCur.execute('''CREATE TABLE price ''' + '''(code text, newprice real, toplevel real, toplimitdays real)''')
                except:
                    pass

                continue

            x += 1
            linesplited = line.split('\t')
            executeSQL = 'INSERT INTO price VALUES (?,?,?,?)'              
            pricenow.append(linesplited[1][1:7])  
            pricenow.append(linesplited[7])
            pricenow.append(linesplited[10])
            pricenow.append(linesplited[8])
            self._DBCur.execute(executeSQL, pricenow)
            self._DBCon.commit()
            pass

    def UpdateStocksHtmls(self, mark, IDList):
        countTmp = 0
        #if not os.path.isdir(mark):
        #   os.makedirs(mark)
        path = "K:\\codes\\ApplicationStock\\ApplicationStocks\\sh"
        os.chdir(path)

        if len(self._fileSet) == 0:
            for root, dirs, files in os.walk( path ):
                for fn in files:
                    self._fileSet.add(fn)

        for x in IDList:
            '''
            for root, dirs, files in os.walk( path ):
                for fn in files:
                    if fn not in self._fileSet:
                        self._fileSet.add(fn)
            '''
            
            urlToGet = self._URLInstance.GetURL(self.BuildCode(mark, x, 1))
            if urlToGet[-6:] in self._fileSet:
                continue
            
            if os.path.exists(urlToGet[-6:]) == True:
                continue
            try:
                content = urllib2.urlopen(urlToGet).read()
                time.sleep(1)
                countTmp += 1
                if countTmp == 50:
                    time.sleep(6)
                    countTmp = 0
            except:
                continue

            fileobj = open(urlToGet[-6:], "wb")
            fileobj.write(content)
            fileobj.close()

    def UpdateStocksHtmlsFinance(self, mark, IDHead, IDTail):
        countTmp = 0
        if not os.path.isdir(mark + "finance"):
           os.makedirs(mark + "finance")

        os.chdir( "./" + mark + "finance" + "/")
        for x in range(IDHead,IDTail):
            urlToGet = self._URLInstance.GetURL(self.BuildCode(mark, x, 1))
            try:
                content = urllib2.urlopen(urlToGet).read()
                time.sleep(0)
                countTmp += 1
                if countTmp == 50:
                    time.sleep(6)
                    countTmp = 0
            except:
                continue

            fileobj = open(urlToGet[-8:], "wb")
            fileobj.write(content)
            fileobj.close()
Exemplo n.º 49
0
 def returnDom0Id(self, host):
     dom0 = Dom0(host)
     db = DBManager()
     db.returnDom0Id(dom0)
Exemplo n.º 50
0
 def updateDom0(self, host, state):
     dom0 = Dom0(host)
     db = DBManager()
     db.updateDom0(dom0, state)
Exemplo n.º 51
0
#
# checkHost
# Receives:
#   host -> ip dom0
#
def checkHost(host):
	try:
		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		sock.connect((host, int(xenPort)))
		sock.close()
		return 1
	except socket.error, err:
		return 0

#
# XOM - Main
#
dbManager = DBManager()
for dom0 in dbManager.returnDom0s():
	dom0Manager = Dom0Manager()
	if (checkHost(dom0[5])):
		xenApi = xmlrpclib.Server("http://" + dom0[5] + ":" + xenPort)
		session = Session(xenUser, xenPassword, xenApi).authentication()
		print "[xom] dom0 " + dom0[5] + " up."
		dom0Manager.updateDom0(dom0[5],"up")
		if(session['Status'] == "Success"):
			dom0Manager.registerVMs(xenApi, session, dom0[5])
	else:
		print "[xom] dom0 " + dom0[5] + " down."
		dom0Manager.updateDom0(dom0[5],"down")		
Exemplo n.º 52
0
class MyHouse:
    # Constructeur
    def __init__(self):
        # Mode actuel dans les différentes pièces
        self.currentMode = {"A": "AUTO", "B": "AUTO", "C": "AUTO", "D": "AUTO"}

        # Température par défaut des différentes pièces
        self.defaultTemp = {"A": 18, "B": 18, "C": 18, "D": 18}

        self.setup_gpio(param.GPIO)

        self.db = DBManager()
        # self.i2c = I2CManager()

    # GPIO configuration
    def setup_gpio(self, array):
        GPIO.setmode(GPIO.BCM)

        # v[0] contains the key
        # v[1] contains the value
        for v in array.items():
            if isinstance(v[1], dict):
                self.setup_gpio(v[1])
            else:
                if v[1][0].upper() == "IN":
                    GPIO.setup(v[1][1], GPIO.IN)
                else:
                    GPIO.setup(v[1][1], GPIO.OUT)

    # Test si la connexion est activee
    # Retourne True si internet est activee
    # Retourne False si non
    def isInternetOn(self):
        try:
            host = socket.gethostbyname("www.google.com")
            s = socket.create_connection((host, 80), 2)
            return True
        except:
            pass
        return False

    # Allume ou eteint le chauffage
    # room : nom du chauffage
    # status : True ou False
    def heat(self, room, status):
        GPIO.output(param.GPIO["Heating"][room][1], status)

    # Allume ou eteint la lampe
    # status : True ou False
    def setLamp(self, status):
        GPIO.output(param.GPIO["Lamp"][1], status)

    # Retourne la temperature d'une pièce
    def getTemp(self, name):
        list_room = {"A": 1, "B": 2, "C": 3, "D": 4}
        temp = 18  # Normalement devrait utiliser l'adc mais fonctionne pas ;(
        return temp

    # Sauvegarde la température par défault de la pièce
    def setDefaultTemp(self, room, temp):
        self.defaultTemp[room] = temp

        connection = self.db.getConnection()
        cursor = connection.cursor()
        cursor.execute("UPDATE temp_default SET temp_default = %s  WHERE room= %s", (temp, room))
        cursor.close()

    # Récupère la température par défaut d'une pièce
    def getDefaultTemp(self, room):
        connection = self.db.getConnection()
        cursor = connection.cursor()
        cursor.execute("SELECT temp_default FROM temp_default WHERE room = %s", (str(room)))
        result = cursor.fetchone()
        requestTemp = result[0]
        cursor.close()

        return requestTemp

    # Permet de récupérer la température pour la chambre à la date donnée
    def getRequestTemp(self, room, date):
        connection = self.db.getConnection()
        cursor = connection.cursor()
        cursor.execute(
            "SELECT temp FROM consigne WHERE room = %s AND start_order < %s AND end_order > %s",
            (str(room), str(date), str(date)),
        )
        result = cursor.fetchone()
        if result:
            temp = result[0]
            cursor.close()
            return temp

        connection = self.db.getConnection()
        cursor = connection.cursor()
        cursor.execute("SELECT temp_default FROM temp_default WHERE room = %s", (str(room)))
        result = cursor.fetchone()
        requestTemp = result[0]

        print("Request temp :", requestTemp, "in room", room)
        cursor.close()

        return requestTemp

    # Sauvegarde une consigne
    def setConsigne(self, room, temp, start_timestamp, end_timestamp):
        self.db.executeUpdate(
            "INSERT INTO `consigne` (`temp`, `start_order`, `end_order`, `room`) VALUES (%s,%s,%s,%s)",
            (str(temp), str(start_timestamp), str(end_timestamp), room),
        )

    def setMode(self, room, status):
        self.currentMode[room] = status

    # Retourne True ou False si fenetre Ferme ou Ouvert
    def getWindow(self, name):
        return GPIO.input(param.GPIO["Windows"][name][1])

    # Retourne True ou False si porte Ferme ou Ouvert
    def getDoor(self, name):
        return GPIO.input(param.GPIO["Doors"][name][1])

    # Régule la maison
    def regulate(self):
        date = int(time.time())  # Contient la date du jour
        requestTempA = self.getRequestTemp("A", date)
        requestTempB = self.getRequestTemp("B", date)
        requestTempC = self.getRequestTemp("C", date)
        requestTempD = self.getRequestTemp("D", date)

        if self.getTemp("D") > requestTempD or self.getWindow("D"):
            self.heat("D", False)
        else:
            self.heat("D", True)

        if self.getTemp("B") > requestTempB or self.getWindow("BG") or self.getWindow("BD"):
            self.heat("B", False)
        else:
            self.heat("B", True)

        if self.getTemp("C") > requestTempC or self.getWindow("C"):
            self.heat("C", False)
        else:
            self.heat("C", True)