Пример #1
0
 def _addClicked(self, *args):
     result = _pmCore.promptDialog(title='New Category', message="Enter Name: ", button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel')
     if result == 'OK':
         newCategory = _pmCore.promptDialog(query=True, text=True)
         _Database.addCategory(newCategory)
         _pmCore.textScrollList(self._textScrollList, edit=True, append=newCategory)
         self._updateCallback(newCategory)
Пример #2
0
 def _buildupWindow(self):
     if isinstance(self._window, _pmCore.uitypes.Window) and self._window.exists(self._window.name()):
         _pmCore.deleteUI(self._window, window=True)
     self._window = _pmCore.window(title=self._winTitle)
     _pmCore.columnLayout(adjustableColumn=True)
     _pmCore.scrollLayout(width=300, height=250, childResizable=True)
     _pmCore.gridLayout(numberOfColumns=2, cellHeight = self._iconSize, cellWidth=self._iconSize)
     for versionNum in _Database.getVersionList(self._fileID):
         versionInfo = _Database.getVersionInfo(self._fileID, versionNum)
         print versionInfo
         thumbnailPath = versionInfo[3]
         if not _os.path.exists(versionInfo[3]):
             thumbnailPath = "cube.png"
         button = _pmCore.iconTextButton(self._versionBtnName(versionNum), style='iconAndTextVertical', image1=thumbnailPath, 
                                         label=self._versionBtnName(versionNum), command=_pmCore.Callback(self._versionSelected, versionNum))
         self._uiWidget[self._versionBtnName(versionNum)] = button
     _pmCore.setParent('..')
     _pmCore.setParent('..')
     _pmCore.separator(style='none', height=10)
     _pmCore.text(label="Comments: ", align='left')
     self._uiWidget['commentLayout'] = _pmCore.scrollLayout(width=300, height=120, childResizable=True)
     _pmCore.setParent('..')
     _pmCore.separator(style='none', height=10)
     self._uiWidget['comment'] = _pmCore.scrollField(width=300, height=80)
     _pmCore.button(label='Add Comment', command=_pmCore.Callback(self._commentAdded))
Пример #3
0
 def setUp(self):
     self.tempdb = tempfile.NamedTemporaryFile()
     self.database = 'sqlite:///{}'.format(self.tempdb.name)
     Database.initialize_database(['test.dat.bgz'], self.database)
     self.SessionMaker = Database.get_sessionmaker(self.database)
     with open('test2.dat') as test_data:
         self.raw_record = test_data.read()
Пример #4
0
def filterSignatures(
        inclusionDatabaseLocation, exclusionDatabaseLocation,
        totalInclusion, totalExclusion, candidatesLocation,
        filteredOutputLocation, sortedOutputLocation, filterLength,
        filterPercent, seedSize):

    filterSignatures = FilterSignatures(
        candidatesLocation, filteredOutputLocation, sortedOutputLocation,
        totalInclusion, totalExclusion, filterLength)

    # QUERY DB - EXCLUSION
    exclusionQueryLocation = Database.queryDatabase(
        exclusionDatabaseLocation, candidatesLocation,
        filteredOutputLocation, filterPercent, seedSize)

    # FILTER
    filterSignatures.reportSignatures(exclusionQueryLocation)

    # QUERY DB - INCLUSION
    inclusionQueryLocation = Database.queryDatabase(
        inclusionDatabaseLocation, filteredOutputLocation,
        sortedOutputLocation, filterPercent, seedSize)

    # SORT
    filterSignatures.sortSignatures(inclusionQueryLocation)
Пример #5
0
def results():
    global warning, logged_in, user, name, projects, currProj

    if request.method=="GET" and 'user' in session:
        user = session['user']
        name['first'] = misc.getName(user)[0]
        name['last'] = misc.getName(user)[1]

        byMe = Database.getRatingsName(user)
        forMe = Database.forMe(user)

        return render_template("results.html", logged_in='user' in session, user=user, name=name, byMe=byMe, forMe=forMe, q=q, projects=projects, currProj=currProj)
    elif 'user' not in session:
        flash("Please log in first!")
        return redirect(url_for('login')) 
    else:
        button = request.form['button']
        if button == 'Go':
            currProj = request.form['projects']
            return redirect(url_for('results'))
        elif button == 'Back':
            currProj = ''
            return redirect(url_for('home'))
        elif button == 'Logout':
            return redirect(url_for('logout'))
Пример #6
0
    def testMergeDataDictDataBothOverride(self):
        dest = {'a': {'a1': 'DEST'}}
        src = {'a': {'a1': 'SRC'}}

        Database.mergeData(dest, src, override=True)

        self.assertEqual(dest, {'a': {'a1': 'SRC'}})
Пример #7
0
 def _insertRuleset(self, none, result, ruleset):
     """Callback used by store() to insert a new or modified ruleset into the SQL database"""
     import Database
     d = Database.pool.runOperation("INSERT INTO rulesets (uri, xml) values(%s, %s)" % (
         Database.quote(ruleset.uri, 'text'), Database.quote(ruleset.get_source(), 'text')))
     d.addCallback(result.callback)
     d.addErrback(result.errback)
Пример #8
0
	def register_post(self):
		username_is_taken = False
		passwords_dont_match = False
		username_is_invalid = False

		username = self.request.get('username')
		logging.info("Username: "******"^[a-zA-Z0-9_-]{3,20}$", username) is None:
			username_is_invalid = True
			logging.info("Invalid username: "******"Invalid registration attempted.")
			self.render_home(passwords_dont_match=passwords_dont_match, username_is_taken=username_is_taken, username_is_invalid=username_is_invalid)
			return
		Database.add_user(page_name, username, password, email)
		self.redirect('#!accountcreated')
Пример #9
0
	def post(self):
		username_is_taken = False
		passwords_dont_match = False
		username_is_invalid = False
		email_is_invalid = False

		username = self.request.get('username')
		password = self.request.get('password')
		password_repeat = self.request.get('password-repeat')
		email = self.request.get('email')
		first_name = self.request.get('first-name')
		last_name = self.request.get('last-name')

		username_is_taken = username in Database.get_all_users()
		passwords_dont_match = password != password_repeat
		username_is_invalid = re.match("^[a-zA-Z0-9_-]{3,20}$", username) is None
		if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
			email_is_invalid = True
		if username_is_taken or passwords_dont_match or username_is_invalid or email_is_invalid:
			s = "Failure"
			if username_is_taken:
				s += " username_is_taken"
			if passwords_dont_match:
				s += " passwords_dont_match"
			if username_is_invalid:
				s += ' username_is_invalid'
			if email_is_invalid:
				s += ' email_is_invalid'
			self.response.out.write(s)
		else:
			Database.add_user(first_name, last_name, username, password, email)
			self.login(Database.get_user(username))
			self.response.out.write("Success")
Пример #10
0
def saveSceneForVersion():
    filePath = _pmCore.sceneName()
    fileID = _Database.getIDByFilePath(filePath)[0]
    _pmCore.saveFile()
    versionNum, _, thumbnailPath = _Database.addVersion(filePath, _os.environ.get('AM_USERNAME'))
    _makeThumbnail(128, 128, thumbnailPath)
    return fileID, versionNum, thumbnailPath
Пример #11
0
    def store(self, recordType, msg):
        if recordType.lower() == "general":
            ID = self.General[0]
        elif recordType.lower() == "medical":
            ID = self.Medical[0]
        elif recordType.lower() == "training":
            ID = self.Training[0]
        else:
            print("Please enter the correct record type")
            return
        ct = self.pre.encrypt(self.params, ID, msg)

        # Serialise the ct for storage in MySql using appropriate charm API for each element type
        # Differentiate between the Integer element and the PairingGroup elements (Otherwise cannot seialise)
        # After serialisation, type is byte
        db = Database()
        ctI = serialize(ct['C']['C'])               # type of ctI is Integer. Use serialise API
        del ct['C']['C']
        ctPg = objectToBytes(ct, self.group)       # type of ctPG is PairingGroup. Use objectToBytes API

        ###################
        #MD: Todo: Add date to signature
        ######################
        # Get the mastser public key from the SignKeys table
        # mPK_bytes = db.getSignPubKey("master")              # bytes of the master public key
        # mPK = bytesToObject(mPK_bytes, self.signGroup)  # de-serialize the key before usage

        date = time.strftime("%Y-%m-%d %H:%M:%S")
        signature = objectToBytes(self.waters.sign(self.masterPK, self.signK, ''.join(msg + date)), self.signGroup)

        db.insertRecord(ID, ctI, ctPg, signature, date, self.ID)
        db.done()
Пример #12
0
def logProtectedCall(result, path, args, user, allowed=True):
    """This should be called when a protected call was attempted,
       successful or not. It logs the attempt and its results in the
       audit_trail database. This audit trail can be used for several things-
       listing recently updated metadata (perhaps for a 'whats new?' page)
       or detecting and recovering from malicious use of keys.
       """
    # Store the first argument separately so we can relatively efficiently search for it
    if args:
        main_param = str(args[0])
    else:
        main_param = None

    # Get the user's UID. If it hasn't even been looked up successfully,
    # this is just a failed operation on a nonexistent user and it's not worth logging.
    uid = user.getCachedUid()
    if uid is None:
        return

    Database.pool.runOperation(
        "INSERT INTO audit_trail (timestamp, uid, action_domain, action_name,"
        " main_param, params, allowed, results)"
        " VALUES(%d, %d, 'protected_call', %s, %s, '%s', %d, '%s')" % (
        time.time(),
        uid,
        Database.quote(".".join(path), 'text'),
        Database.quote(main_param, 'text'),
        Database.quoteBlob(cPickle.dumps(args)),
        allowed,
        Database.quoteBlob(cPickle.dumps(result))))
    return result
Пример #13
0
	def __init__(self
				,natoms,r_ij
				,eleNums,eleNames
				,eleMasses,nPool
				,stride,subString
				,boxAdd,surface
				,surfGA):

		self.natoms = natoms
		self.r_ij = r_ij
		self.eleNums = eleNums
		self.eleNames = eleNames
		self.eleMasses = eleMasses
		self.nPool = nPool
		self.stride = stride
		self.subString = subString
		self.boxAdd = boxAdd

		'''
		Surface Object.
		'''

		self.surface = surface
		self.surfGA = surfGA

		db.lock()

		self.calcNum = db.findLastDir() + 1 
		os.system("mkdir " + str(self.calcNum))

		db.unlock()

		self.genRan()
Пример #14
0
 def mark_selection_as_invoiceable(self):
   def do_mark():
     for row in self.transactions_tbl.selected_rows:
       t = self.transactions_tbl.rows[row]
       Q.markTransactionAsInvoiceable(t, True)
   D.withSession(do_mark)
   self.transactions_tbl._ns_inner_view.reloadData()
Пример #15
0
    def testMergeDataDataOnlyInDest(self):
        dest = {'a': 'A'}
        src = {}

        Database.mergeData(dest, src)

        self.assertEqual(dest, {'a': 'A'})
Пример #16
0
    def testMergeDataBothEmpty(self):
        dest = {}
        src = {}

        Database.mergeData(dest, src)

        self.assertEqual(dest, {})
Пример #17
0
    def testMergeDataDataInBothNoOverride(self):
        dest = {'a': 'DEST'}
        src = {'a': 'SRC'}

        Database.mergeData(dest, src, override=False)

        self.assertEqual(dest, {'a': 'DEST'})
Пример #18
0
    def testMergeDataDictOnlyInSrc(self):
        dest = {}
        src = {'a': {'a1': 'A1'}}

        Database.mergeData(dest, src)

        self.assertEqual(dest, {'a': {'a1': 'A1'}})
Пример #19
0
    def GET(self):
        user_data = web.input()
        projectId = user_data['project_id']

        show_statuses = []
        if user_data.has_key('show_active'):
            show_statuses.append('show_active')
        if user_data.has_key('show_inactive'):
            show_statuses.append('show_inactive')
        if user_data.has_key('show_complete'):
            show_statuses.append('show_complete')
        if user_data.has_key('show_canceled'):
            show_statuses.append('show_canceled')
        

        session = Database.Session()
        
        project = Database.getProject(projectId)

        projectTasks = Database.loadProjectPageData(projectId, show_statuses)
        
        
        PWP = Database.ProjectWikiPage
        pwp = session.query(PWP.project_wiki_page).filter_by(project_id=projectId).scalar()

        return render.view_project(project, projectTasks, pwp, show_statuses)
Пример #20
0
    def loadDocumentsAndVocabulary(self, availabilityLag):

        print "\nLoading documents from MySQL"

        db = Database()

        sql = u"select id, test_train, stemmed_tokens from property where usable = 1 and availability_lag <= {0};"
        sql = sql.format(availabilityLag)

        table = db.runSqlQueryTable(sql)

        self.propertyIds = [row[0] for row in table]
        self.testTrain = [row[1] for row in table]
        self.documents = [row[2].split(" ") for row in table]

        print len(self.documents), " documents loaded"

        print "\nLoading vocabulary"

        vocab = set()

        for document in self.documents:
            for token in document:
                vocab.add(token)
 
        self.vocabulary = sorted(vocab)

        print len(self.vocabulary), " terms loaded"
Пример #21
0
	def decide(self):

		'''
		Should cluster be added to pool.dat?
		'''

		if os.path.exists("pool.dat"):
			with open("pool.dat","r") as pool:
				poolList = pool.readlines()
				poolSize = len(poolList) / (self.natoms + 2)
				if poolSize < self.nPool:
					self.addToPool()
				else:
					AcceptReject = checkPool()
					Accept = AcceptReject.checkEnergy(float(self.finalEnergy))

					if Accept:
						Index = AcceptReject.lowestIndex
						Index = (Index*self.stride)+1

						db.updatePool("Finish"
									,Index,self.eleNums
									,self.eleNames,self.eleMasses
									,self.finalEnergy,self.finalCoords
									,self.stride,self.vaspIN.box)
		else:
			self.addToPool()
Пример #22
0
 def post(self):
     if self.get_argument("auth")=="PCBOSS":
         requestType = self.get_argument("type")
         if requestType == "add_user":
             email = self.get_argument("email")
             password = self.get_argument("password")
             first_name = self.get_argument("first_name")
             last_name = self.get_argument("last_name")
             if Database.addUser(email, password, first_name, last_name):
                 self.write("Success")
             else:
                 self.write("Failure")
         elif requestType == "list_jobs":
             self.write(str(Database.listJobs()))
         elif requestType == "request_file":
             filenum = self.get_argument("file_number")
             self.write(str(Database.getJob(filenum)))
         elif requestType == "update_job_status":
             filenum = int(self.get_argument("file_number"))
             status = self.get_argument("status")
             Database.updateStatus(filenum, status)
         elif requestType == "recent_file":
             self.write(str(Database.mostRecentFile()))
         elif requestType == "recent_file_timestamp":
             self.write(str(Database.mostRecentTimestamp()))
         elif requestType == "get_users":
             self.write(str(Database.listUsers()))
         elif requestType == "edit_user":
             email = self.get_argument("email")
             fname = self.get_argument("first_name")
             lname = self.get_argument("last_name")
             pword = self.get_argument("password")
             Database.updateAccount(email, fname, lname, pword)
     else:
         self.write("Error: Unrecognized Request")
Пример #23
0
	def post(self):
		username = self.request.get('username')
		content = self.request.get('content')
		entry_id = self.request.get('entry-id')
		entry_index = int(entry_id)
		Database.replace_entry_content(Database.get_user(username), content, entry_index)
		self.redirect('/entryeditor')
Пример #24
0
 def mark_selection_as_payment(self):
   def do_mark():
     t = self.transactions_tbl.rows[self.transactions_tbl.selected_row]
     person = PersonPicker().pick()
     if person:
       Q.markTransactionAsPayment(t, person)
   D.withSession(do_mark)
Пример #25
0
	def get(self):
		users = []
		for username in Database.get_all_users():
			user = Database.get_user(username)
			users.append({"username": user.username, "pageName": user.page_name})
		obj = json.dumps(users)
		self.response.write(str(obj))
Пример #26
0
    def _parse_guild(self, xml_file_object, site, get_characters=False):
        """Parse a guild page."""
        xml = minidom.parse(xml_file_object)
        guild_nodes = xml.getElementsByTagName("guildHeader")
        guild_node = guild_nodes[0]

        name = guild_node.attributes["name"].value
        realm = guild_node.attributes["realm"].value
        site = site
        guild = Guild(name, realm, site)
        log.info("Creating guild " + unicode(guild).encode("utf-8"))
        Database.insert(guild)

        # cflewis | 2009-03-28 | Now need to put in guild's characters
        if get_characters:
            log.debug("Parsing guild character")
            characters = self._parse_guild_characters(name, realm, site)
            #guild.characters = characters
        else:
            log.debug("Not parsing guild characters")

        # cflewis | 2009-03-28 | SQLAlchemy wasn't actually committing,
        # so I'm merging twice, and it seems to bite now.
        Database.insert(guild)

        return guild
Пример #27
0
	def post(self):
		user = self.get_user()
		if user and user.has_a_bio:
			image_url_is_valid = True
			description_is_valid = True

			description = self.request.get('description')
			image_url = self.request.get('image_url')

			# check if image is valid
			maintype= mimetypes.guess_type(urlparse.urlparse(image_url).path)[0]
			if maintype not in ('image/png', 'image/jpeg', 'image/gif'):
				image_url_is_valid = False

			# check if description is valid
			description_is_valid = description != ''

			if image_url_is_valid and description_is_valid:
				bio = Database.Bio(description=description, image_url=image_url)
				user.bio = bio
				user.put()
				Database.update_user_memcache()
				self.render('my_bio.html', page='bio', user=user, image_url_is_valid=image_url_is_valid,
					description_is_valid=description_is_valid, submission_successful=True)
			else:
				self.render('my_bio.html', page='bio', user=user, image_url_is_valid=image_url_is_valid,
					description_is_valid=description_is_valid, submission_successful=False,
					new_image_url=image_url)			

		else:
			self.render('permission_denied.html', user=user)
Пример #28
0
def getFilme(idIMDB, categoria):
    url = 'http://api-v2launch.trakt.tv/movies/%s?extended=full,images' % idIMDB
    urlpt = 'http://api-v2launch.trakt.tv/movies/%s/translations/pt' % idIMDB

    resultado = abrir_url(url, header=__HEADERS_TRAKT__)
    resultado = json.loads(resultado)

    resultadopt = abrir_url(urlpt, header=__HEADERS_TRAKT__)
    resultadopt = json.loads(resultadopt)

    if resultado["trailer"] is None:
        trailer = '-'
    else:
        trailer = resultado["trailer"]

    try:
        plot = resultadopt[0]["overview"]
    except:
        plot = resultado["overview"]

    if resultado["year"] is None:
        ano = "-"
    else:
        ano = str(resultado["year"])

    if resultado["images"]["poster"]["full"] is None:
        url2 = 'http://www.omdbapi.com/?i=%s&plot=full&r=json' % idIMDB
        resultado2 = abrir_url(url2, header=__HEADERS__)
        resultado2 = json.loads(resultado2)

        poster = resultado2["Poster"]
    else:
        poster = resultado["images"]["poster"]["full"]

    if resultado["images"]["fanart"]["full"] is None:
        url2 = 'http://www.omdbapi.com/?i=%s&plot=full&r=json' % idIMDB
        resultado2 = abrir_url(url2, header=__HEADERS__)
        resultado2 = json.loads(resultado2)

        fanart = resultado2["Poster"]
    else:
        fanart = resultado["images"]["fanart"]["full"]

    traktid = resultado["ids"]["trakt"]
    slug = resultado["ids"]["slug"]


    Database.insertFilmeDB(nome=resultado["title"], plot=plot, traktid=traktid, imdb=idIMDB, poster=poster, fanart=fanart, trailer=trailer, ano=ano, categoria=categoria, slug=slug)

    data = {}
    data["nome"] = resultado["title"]
    data["plot"] = plot
    data["imdb"] = idIMDB
    data["poster"] = poster
    data["fanart"] = fanart
    data["trailer"] = trailer
    data["ano"] = ano
    data["categoria"] = categoria
    return json.dumps(data)
Пример #29
0
	def post(self):
		username = self.request.get('username')
		password = self.request.get('password')
		if (Database.valid_password(username, password)):
			self.login(Database.get_user(username))
			self.response.out.write("Success")
		else:
			self.response.out.write("Failure")
Пример #30
0
	def addToPool(self):

		'''
		Add Final Geometry and 
		energy to pool.dat.
		'''

		clus = []

		output = DFTout(self.calcNum,self.natoms)
		self.finalEnergy = output.getEnergy()
		self.finalCoords = output.getCoords()

		db.lock()

		with open("pool.dat","a") as pool:

			pool.write(str(self.natoms)+"\n")
			pool.write("Energy = "+str(self.finalEnergy))
			pool.write(" Dir = "+str(self.calcNum)+"\n")

			'''
			Move coordinates from 
			centre of the simulation cell.
			'''

			box = self.vaspIN.box
			self.finalCoords = [float(i) - box/2 for i in self.finalCoords]

			'''
			Change format of 
			the coordinates.
			'''

			for i in range(0,self.natoms*3,3):

				x = self.finalCoords[i]
				y = self.finalCoords[i+1]
				z = self.finalCoords[i+2]

				clus.append([x,y,z])

			'''
			Add the element types
			and write to pool file.
			'''

			count = 0

			for i in range(len(self.eleNames)):
				for j in range(self.eleNums[i]):
					ele = self.eleNames[i]
					x,y,z = clus[count]
					atom = ele+" "+str(x)+" "+str(y)+" "+str(z)+"\n"
					pool.write(atom)
					count += 1

		db.unlock()
Пример #31
0
 def test_get_prof_quality_by_instructorFullName(self):
     assert Database.get_prof_quality_by_instructorFullName(
         self.cursor, "David Liu") == {
             'average_enthusiasm': 4.47,
             'average_course_atmosphere': 4.41
         }
Пример #32
0
    def handle_send(self):
        """
        Handles all of the sending options and sends correctly formatted messages
        """

        while True:
            # Wait for the user to press ENTER
            input()
            with self.console_lock:
                user_input = input("> ")
                command = Command(user_input)
                # Logs user out
                if command.is_logout():
                    self.logout()
                # Adds a user to the contacts list (sends handshake)
                # :add username
                # Example: :add alice
                elif command.is_add_contact():
                    username = command.parts[1]

                    # Check whether the user exists
                    self.populate_public_keys(username)
                    if not username in self.contacts:
                        print(
                            "Specified user does not exist. Please try again.")
                        continue

                    # Check whether we have to send handshake
                    if not "aes_key" in self.contacts[username]:
                        self.send_direct_handshake(username)
                    else:
                        print("User is already in your contacts.")
                # Creates a new group chat
                # :newGroup name members
                # Example: :newGroup testGroup alice,bob,john
                elif command.is_new_group():
                    group_name = command.parts[1]
                    group_members = command.parts[2].split(",")
                    if Database.check_group(
                            group_name) or self.is_group_in_groups(group_name):
                        print(
                            "Group name already exists. Please enter a different name and try again."
                        )
                    else:
                        self.send_group_handshake(group_name, group_members)
                # Sends a group message to the specified group.
                # :group name message
                # Example: :group testGroup "Hello testGroup"
                elif command.is_group_message():
                    group_name = command.parts[1]
                    message = command.parts[2]
                    if not self.is_group_in_groups(group_name):
                        print("The group was not found.")
                    else:
                        Send.send_group_message(
                            message, self.username, group_name, self.s,
                            self.groups[group_name]["members"], self.groups)
                # Sends a direct message to the specified user.
                # :direct name message
                # Example: :direct alice "Hello, Alice"
                elif command.is_direct_message():
                    recipient = command.parts[1]
                    message = command.parts[2]
                    if self.is_username_in_contacts(recipient):
                        Send.send_direct(self.username, recipient,
                                         self.contacts, message, self.s)
                    else:
                        print(
                            "User not found in your contacts. Please first add the user using :add command. Type :help for more details."
                        )

                # Displays members associated with the specified group.
                # :info group name
                # Example: :info group testGroup
                elif command.is_group_info():
                    group_name = command.parts[2]
                    if not group_name in self.groups:
                        print("Group " + group_name + " not found.")
                    else:
                        print("Group " + group_name + " members: ")
                        for member in self.groups[group_name]["members"]:
                            print(member)
                # Lists user's contacts.
                # :contacts
                elif command.is_list_contacts():
                    print("Your contacts:")
                    for contact in self.contacts:
                        print(contact)
                # Lists user's groups.
                # :groups
                elif command.is_list_groups():
                    print("Your groups:")
                    for group in self.groups:
                        print(group)
                elif command.is_help():
                    help_instructions = """
Available commands

Description: log out of account 
Usage: :logout 
Example: :logout

Description: add user to the contacts list
Usage: :add username
Example: :add alice

Description: create a new group chat
Usage: :newGroup groupName members
Example: :newGroup testGroup alice,bob,john

Description: send a group message to a group chat
Usage: :group groupName message
Example: :group testGroup "Hello testGroup"

Description: send a direct message to a user
Usage: :direct username message
Example: :direct alice "Hello, Alice"

Description: list contacts in contacts list
Usage: :contacts
Example: :contacts

Description: list groups
Usage: :groups
Example: :groups  

Description: list members of a group chat
Usage: :info group groupName
Example: :info group testGroup                    """
                    print(help_instructions)
                else:
                    print(
                        "Command not recognized. Type :help for more details.")
Пример #33
0
    def __init__(self, config, querylist, mainwin, debug=True):
        QSplitter.__init__(self, None)
        self.debug = debug
        self.conf = config
        self.main_window = mainwin
        self.sql = querylist

        self.liststore = [
        ]  # gtk.ListStore[]         stores the contents of the grids
        self.listcols = [
        ]  # gtk.TreeViewColumn[][]  stores the columns in the grids

        self.MYSQL_INNODB = 2
        self.PGSQL = 3
        self.SQLITE = 4

        # create new db connection to avoid conflicts with other threads
        self.db = Database.Database(self.conf, sql=self.sql)
        self.cursor = self.db.cursor

        settings = {}
        settings.update(self.conf.get_db_parameters())
        settings.update(self.conf.get_import_parameters())
        settings.update(self.conf.get_default_paths())

        # text used on screen stored here so that it can be configured
        self.filterText = {
            'handhead': _('Hand Breakdown for all levels listed above')
        }

        filters_display = {
            "Heroes": True,
            "Sites": True,
            "Games": True,
            "Currencies": True,
            "Limits": True,
            "LimitSep": True,
            "LimitType": True,
            "Type": True,
            "Seats": True,
            "SeatSep": True,
            "Dates": True,
            "Groups": True,
            "GroupsAll": True,
            "Button1": True,
            "Button2": True
        }

        self.filters = Filters.Filters(self.db, display=filters_display)
        self.filters.registerButton1Name(_("Filters"))
        self.filters.registerButton1Callback(self.showDetailFilter)
        self.filters.registerButton2Name(_("Refresh Stats"))
        self.filters.registerButton2Callback(self.refreshStats)

        scroll = QScrollArea()
        scroll.setWidget(self.filters)

        # ToDo: store in config
        # ToDo: create popup to adjust column config
        # columns to display, keys match column name returned by sql, values in tuple are:
        #     is column displayed(summary then position), column heading, xalignment, formatting, celltype
        self.columns = self.conf.get_gui_cash_stat_params()

        # Detail filters:  This holds the data used in the popup window, extra values are
        # added at the end of these lists during processing
        #                  sql test,              screen description,        min, max
        self.handtests = [  # already in filter class : ['h.seats', 'Number of Players', 2, 10]
            ['gt.maxSeats', 'Size of Table', 2, 10],
            ['h.playersVpi', 'Players who VPI', 0, 10],
            ['h.playersAtStreet1', 'Players at Flop', 0, 10],
            ['h.playersAtStreet2', 'Players at Turn', 0, 10],
            ['h.playersAtStreet3', 'Players at River', 0, 10],
            ['h.playersAtStreet4', 'Players at Street7', 0, 10],
            ['h.playersAtShowdown', 'Players at Showdown', 0, 10],
            ['h.street0Raises', 'Bets to See Flop', 0, 5],
            ['h.street1Raises', 'Bets to See Turn', 0, 5],
            ['h.street2Raises', 'Bets to See River', 0, 5],
            ['h.street3Raises', 'Bets to See Street7', 0, 5],
            ['h.street4Raises', 'Bets to See Showdown', 0, 5]
        ]

        self.cardstests = [
            [Card.DATABASE_FILTERS['pair'],
             _('Pocket pairs')],
            [Card.DATABASE_FILTERS['suited'],
             _('Suited')],
            [
                Card.DATABASE_FILTERS['suited_connectors'],
                _('Suited connectors')
            ],
            [Card.DATABASE_FILTERS['offsuit'],
             _('Offsuit')],
            [
                Card.DATABASE_FILTERS['offsuit_connectors'],
                _('Offsuit connectors')
            ],
        ]
        self.stats_frame = None
        self.stats_vbox = None
        self.detailFilters = []  # the data used to enhance the sql select
        self.cardsFilters = []

        self.stats_frame = QFrame()
        self.stats_frame.setLayout(QVBoxLayout())

        self.stats_vbox = QSplitter(Qt.Vertical)
        self.stats_frame.layout().addWidget(self.stats_vbox)

        self.addWidget(scroll)
        self.addWidget(self.stats_frame)
        self.setStretchFactor(0, 0)
        self.setStretchFactor(1, 1)

        # Make sure Hand column is not displayed.
        hand_column = (x for x in self.columns if x[0] == 'hand').next()
        hand_column[colshowsumm] = hand_column[colshowposn] = False

        # If rfi and steal both on for summaries, turn rfi off.
        rfi_column = (x for x in self.columns if x[0] == 'rfi').next()
        steals_column = (x for x in self.columns if x[0] == 'steals').next()
        if rfi_column[colshowsumm] and steals_column[colshowsumm]:
            rfi_column[colshowsumm] = False

        # If rfi and steal both on for position breakdowns, turn steals off.
        if rfi_column[colshowposn] and steals_column[colshowposn]:
            steals_column[colshowposn] = False
Пример #34
0
3 = EXIT""")

    @staticmethod
    def tak_choose():
        choose = input('SELECT MENU SECTION [1/2/EXIT]: ')
        return choose

    @staticmethod
    def take_choose2():
        choose2 = input('SELECT OPTION: [1-7]: ')
        return choose2


if __name__ == "__main__":

    Database.run()

    while True:

        menu = Interface()
        menu.display_menu()
        c1 = menu.tak_choose()
        ob = Vehicle()
        dr = Driver()

        if c1 == '1':
            c2 = menu.take_choose2()
            if c2 == '1':
                os.system('cls')
                print('Vehicle List')
                ob.show_v_list()
Пример #35
0
 def setThreads(self, value):
     self.settings['threads'] = value
     if self.settings["threads"] > len(self.writerdbs):
         for i in xrange(self.settings['threads'] - len(self.writerdbs)):
             self.writerdbs.append(
                 Database.Database(self.config, sql=self.sql))
Пример #36
0
import locale
import time
import Downloader
import Database
import Page
import urllib
import traceback

if __name__ == '__main__':
    locale.setlocale(0, 'en_US.UTF-8')
    n = 0
    try:
        while True:
            if n % 5 == 0:
                print('Read the League_ids ...')
                league_id = Database.read_league_id('League_ids.xlsx')
                print('\tdone !!!')
            for league in league_id:
                if league.split('|')[0] in ['Europe', 'England', 'Spain', 'Germany', 'Italy', 'France']:
                    continue
                if league.split('|')[0] in ['World', 'North America', 'Portugal', 'Scotland', 'Brazil', 'Denmark',
                                            'Finland', 'Ireland', 'Netherlands', 'Poland', 'Russia', 'Turkey',
                                            'Argentina']:
                    continue
                print('Begin processing matches in ' + league + ' ...')
                connecting_time = 0
                while True:
                    try:
                        connecting_time += 1
                        page = Downloader.odds_page(league_id[league])
                    except urllib.error.HTTPError as err:
Пример #37
0
def Repeater():

    logObj = Logger.LoggerClass()
    buttBot = CheckButton.ButtonBot()

    while (True):
        try:
            print "Instance"
            logObj.AddLog()
            buttBot.Check()
            MPDQueueFixer.Fix()
            time.sleep(1)
        except KeyboardInterrupt:
            print "was exited by user!"
            return
        except:
            print "error happened in loop"


if __name__ == "__main__":
    conn = Database.GetConnection()
    c = conn.cursor()

    # Create table
    #c.execute('''CREATE TABLE songPlays (fileName TEXT PRIMARY KEY, times INTEGER)''')

    conn.commit()
    conn.close()

    Repeater()
Пример #38
0
		tuneList.append(tuneAttempts[(i)])
	for i in range(10):
		n = '#' + str(i+1)
		print '**********', n , '**********'
		tuneList[i].display()
		score(tuneList[i], True)
	print '************************'

def createMIDIs():
	print 'not implemented yet'

menu = '1) Create tunes\n' + '2) Results\n' + '3) Score your own melody\n' + '4) Give feedback\n' + '5) Create MIDIs\n' + '6) Exit\n'
resultsMenu = '1) Display best 10\n' + '2) Display Sample of Results\n' + '3) Display Worst 10\n'

blockPrint()
Database.initializeFiles()
Database.storeHarmonies()
enablePrint()

num = ''
type = ''
length = ''
done = False
t1 = time.time()
total = t1-t0
print 'Database initialized in', total, 'seconds'
print 'Three note permutations scanned:\t', Database.threeNoteDatabase['total']
print 'Two note permutations scanned:\t\t', Database.twoNoteDatabase['total']
print 'Four note permutations scanned:\t\t', Database.fourNoteDatabase['total']
print 'Harmonic combinations scanned:\t\t', Database.harmonicDatabase['total']
while not done:
Пример #39
0
app.config.from_object(__name__)
#Session(app)

import jinja2
import os
JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(
    os.path.dirname(__file__)),
                                       extensions=['jinja2.ext.autoescape'])

#s = socket(AF_INET, SOCK_STREAM)
#s.connect(('0.0.0.0', 8194)) # Our socket for Calling Search Worker

conn = Server('http://localhost:1006')  # RPC Server

global db
db = Database("mongodb://localhost:27017/")

# Set the secret key to some random bytes. Keep this really secret!
import os
import random
app.secret_key = os.urandom(
    32)  #bytes(str(hex(random.getrandbits(128))), 'ascii')


@app.errorhandler(404)
def page_not_found(e):
    return render_template("/404.html")


@app.route("/logout", methods=["GET", "POST"])
def logout():
Пример #40
0
class EchoBot(Client):
    KEY = "AIzaSyB_R-OTY2BwfqtjqWQ3eBPRfoTb8WywqFU"
    URL = "https://maps.googleapis.com/maps/api/directions/json"
    # key:  str(thread_id)
    # value: list[queue]
    conversations = {}
    database = Database.Database(threading.Lock())

    def onMessage(self, author_id, message_object, thread_id, thread_type,
                  **kwargs):
        self.markAsDelivered(thread_id, message_object.uid)
        self.markAsRead(thread_id)
        print("author_id: {}, thread_id: {}, thread_type: {}, UID: {}".format(
            author_id, thread_id, thread_type, self.uid))
        log.info("{} from {} in {}".format(message_object, thread_id,
                                           thread_type.name))
        print(message_object.text)
        # If you're not the author, echo
        if author_id != self.uid:
            self.check_open_conversation(thread_id, thread_type,
                                         message_object)
        # self.send(message_object, thread_id=thread_id, thread_type=thread_type)

    def check_open_conversation(self, thread_id, thread_type, message_object):
        if thread_id not in self.conversations:
            q = queue.Queue()
            self.conversations[thread_id] = q
            t = threading.Thread(target=self.start_conversation,
                                 args=(thread_id, thread_type),
                                 daemon=True)
            t.start()

        else:
            self.conversations[thread_id].put(message_object.text)

    def start_conversation(self, thread_id, thread_type):
        self.send(Message(text="Hello Welcome to The Molly Report"),
                  thread_id=thread_id,
                  thread_type=thread_type)
        self.send_main_menu(thread_id, thread_type)

        try:
            user_input = int(self.conversations[thread_id].get())
        except:
            self.send_goodbye(thread_id, thread_type)
            self.conversations.pop(thread_id)
            return

        logged_in = False
        while not logged_in:
            if user_input == 1:
                msg = "attempting to login..."
                self.send(Message(text=msg),
                          thread_id=thread_id,
                          thread_type=thread_type)

                self.send(Message(text="Enter your username: "******"Enter your password: "******"you are now logged in"),
                              thread_id=thread_id,
                              thread_type=thread_type)
                else:
                    self.send(Message(text="unable to login"),
                              thread_id=thread_id,
                              thread_type=thread_type)

            elif user_input == 2:
                self.send(Message(text="Enter in first name: "),
                          thread_id=thread_id,
                          thread_type=thread_type)
                first = self.conversations[thread_id].get()

                self.send(Message(text="Enter in last name: "),
                          thread_id=thread_id,
                          thread_type=thread_type)
                last = self.conversations[thread_id].get()

                self.send(Message(text="Enter in username: "******"Enter in password: "******"account has been created"),
                          thread_id=thread_id,
                          thread_type=thread_type)

            else:
                self.send_goodbye(thread_id, thread_type)
                self.conversations.pop(thread_id)
                return

            if not logged_in:
                self.send_main_menu(thread_id, thread_type)

                try:
                    user_input = int(self.conversations[thread_id].get())
                except:
                    self.send_goodbye(thread_id, thread_type)
                    self.conversations.pop(thread_id)
                    return

        self.route_main_page(thread_id, thread_type, username)

    def check_username(self, username, thread_id, thread_type):
        self.database.cur.execute("SELECT username FROM Accounts")
        all_usernames = self.database.cur.fetchall()
        clean_all_user = []
        for user in all_usernames:
            clean_all_user.append(user[0])
        while username in clean_all_user:
            self.send(Message(
                text=
                "Username: \"{}\" is already taken. Please choose a new username."
                .format(username)),
                      thread_id=thread_id,
                      thread_type=thread_type)
            self.send(Message(text="Enter in new username: "******"--- Home ---\nPlease enter in the number of the choice below.\n1. Login\n2. Signup\nAnything else to quit\n\nNumber:"
        self.send(Message(text=msg),
                  thread_id=thread_id,
                  thread_type=thread_type)

    def send_route_menu(self, thread_id, thread_type):
        msg = "--- Routes ---\n1. View Routes\n2. Create Route\n3. Delete Route\n4. Update Route\nAnything else to quit and logout\n\nNumber of Choice:"
        self.send(Message(text=msg),
                  thread_id=thread_id,
                  thread_type=thread_type)

    def send_goodbye(self, thread_id, thread_type):
        self.send(
            Message(text="Thank you for using the Molly Report! Goodbye"),
            thread_id=thread_id,
            thread_type=thread_type)

    def route_main_page(self, thread_id, thread_type, username):
        self.send_route_menu(thread_id, thread_type)

        try:
            user_input = int(self.conversations[thread_id].get())
        except:
            self.send_goodbye(thread_id, thread_type)
            self.conversations.pop(thread_id)
            return

        done = False
        while not done:
            if user_input == 1:
                self.view_routes(thread_id, thread_type, username)

            elif user_input == 2:
                self.create_route(thread_id, thread_type, username)

            elif user_input == 3:
                self.delete_route(thread_id, thread_type, username)
            elif user_input == 4:
                self.update_route(thread_id, thread_type, username)
            elif user_input == 5:
                self.update_account(thread_id, thread_type, username)
            else:
                done = True
                self.send_goodbye(thread_id, thread_type)
                self.conversations.pop(thread_id)
                return

            self.send_route_menu(thread_id, thread_type)

            try:
                user_input = int(self.conversations[thread_id].get())
            except:
                done = True
                self.send_goodbye(thread_id, thread_type)
                self.conversations.pop(thread_id)
                return

    def view_routes(self, thread_id, thread_type, username):
        # this shows the whoel database, need to prettify and make it more useful to the user
        self.send(Message(text="--- Viewing all your routes ---"),
                  thread_id=thread_id,
                  thread_type=thread_type)
        data = self.database.get_all_routes(username)
        if data == []:
            self.send(Message(text="You have no routes."),
                      thread_id=thread_id,
                      thread_type=thread_type)

        else:
            for route in data:
                print(route)
                msg = "Route Name: {}\nStart: {}\nEnd: {}\nDeparture Time: {}".format(
                    route[1], route[3], route[4], route[2])
                self.send(Message(text=msg.replace('+', '  ')),
                          thread_id=thread_id,
                          thread_type=thread_type)

    def create_route(self, thread_id, thread_type, username):
        self.send(Message(text="--- Create Route --- "),
                  thread_id=thread_id,
                  thread_type=thread_type)
        self.send(Message(text="Enter your route name: "),
                  thread_id=thread_id,
                  thread_type=thread_type)
        name = self.conversations[thread_id].get()

        self.send(Message(text="Enter in your starting location:"),
                  thread_id=thread_id,
                  thread_type=thread_type)
        self.send(
            Message(text="Enter in Address line (ex. 123 Main Street): "),
            thread_id=thread_id,
            thread_type=thread_type)
        address_line = self.conversations[thread_id].get()

        self.send(Message(text="Enter in City (ex. Los Angelos): "),
                  thread_id=thread_id,
                  thread_type=thread_type)
        city = self.conversations[thread_id].get()

        self.send(Message(text="Enter in State abbreviation (ex. CA): "),
                  thread_id=thread_id,
                  thread_type=thread_type)
        state = self.conversations[thread_id].get()

        self.send(Message(text="Enter in zip code (ex. 90210): "),
                  thread_id=thread_id,
                  thread_type=thread_type)
        zip = self.conversations[thread_id].get()

        start = address_line + '+' + city + '+' + state + '+' + zip

        self.send(Message(text="Enter in your ending location:"),
                  thread_id=thread_id,
                  thread_type=thread_type)
        self.send(
            Message(text="Enter in Address line (ex. 123 Main Street): "),
            thread_id=thread_id,
            thread_type=thread_type)
        address_line = self.conversations[thread_id].get()

        self.send(Message(text="Enter in City (ex. Los Angelos): "),
                  thread_id=thread_id,
                  thread_type=thread_type)
        city = self.conversations[thread_id].get()

        self.send(Message(text="Enter in State abbreviation (ex. CA): "),
                  thread_id=thread_id,
                  thread_type=thread_type)
        state = self.conversations[thread_id].get()

        self.send(Message(text="Enter in zip code (ex. 90210): "),
                  thread_id=thread_id,
                  thread_type=thread_type)
        zip = self.conversations[thread_id].get()

        end = address_line + '+' + city + '+' + state + '+' + zip

        self.send(Message(
            text=
            "Enter departure time in military time in PST (ex. 4:30 PM => 1630 or 6:00 AM => 600): "
        ),
                  thread_id=thread_id,
                  thread_type=thread_type)
        time = self.conversations[thread_id].get()

        self.database.create_route(start, end, time, name, username)
        self.send(Message(text="Your route has been created."),
                  thread_id=thread_id,
                  thread_type=thread_type)

    def delete_route(self, thread_id, thread_type, username):
        self.view_routes(thread_id, thread_type, username)
        self.send(Message(
            text="Enter the number for the route you want to delete: "),
                  thread_id=thread_id,
                  thread_type=thread_type)
        route_number = int(self.conversations[thread_id].get())

        name = self.database.delete_route(username, route_number)
        msg = "\'{}\' has successfully been deleted".format(name)
        self.send(Message(text=msg),
                  thread_id=thread_id,
                  thread_type=thread_type)

    def update_route(self, thread_id, thread_type, username):
        self.view_routes(thread_id, thread_type, username)
        self.send(Message(
            text="Enter the number for the route you want to update: "),
                  thread_id=thread_id,
                  thread_type=thread_type)
        route_number = int(self.conversations[thread_id].get())

        msg = "What would you like to update about your route?\n1. Route Name\n2. Departuret time\n3. Start Location\n4. End Location\n\nChoice: "
        self.send(Message(text=msg),
                  thread_id=thread_id,
                  thread_type=thread_type)
        route_update = int(self.conversations[thread_id].get())

        msg = "Enter in the new data: "
        self.send(Message(text=msg),
                  thread_id=thread_id,
                  thread_type=thread_type)
        route_info = self.conversations[thread_id].get()

        self.database.update_route(username, route_number, route_update,
                                   route_info)

        msg = "Your route has been updated."
        self.send(Message(text=msg),
                  thread_id=thread_id,
                  thread_type=thread_type)

    def update_account(self, thread_id, thread_type, username):
        msg = "What would you like to update about your account?\n1. First Name\n2. Last Name\n3. Username\n4. Password\nAnything else to quit.\n\nChoice: "
        self.send(Message(text=msg),
                  thread_id=thread_id,
                  thread_type=thread_type)
        user_input = int(self.conversations[thread_id].get())

        if user_input == 1:
            pass
        elif user_input == 2:
            pass
        elif user_input == 3:
            pass
        elif user_input == 4:
            pass

    def send_route_info(self, time):
        routes, user_info_list = self.database.get_routes_with_time(time)
        for route in routes:
            query = {
                "key": self.KEY,
                "destination": route[4],
                "origin": route[3],
                "avoid": "tolls",
                "departure_time": "now",
                "traffic_model": "best_guess"
            }
            r = requests.get(self.URL, params=query)
            info = r.json()

            # pp = pprint.PrettyPrinter(indent = 4)
            # pp.pprint(info)
            print("URL: " + r.url)

            if info["status"] == "OK":
                print("Distance: " +
                      info["routes"][0]["legs"][0]["distance"]["text"])
                print("Duration in Traffic: " + info["routes"][0]["legs"][0]
                      ["duration_in_traffic"]["text"])
            else:
                print("status != OK")

            print()

            route_msg = ''
            leg_num = 1
            for step in info["routes"][0]["legs"][0]["steps"]:
                inst = step["html_instructions"]
                present = True
                while present:
                    start = inst.find('<')
                    if start >= 0:
                        end = inst.find('>')
                        inst = inst[:start].strip() + ' ' + inst[end +
                                                                 1:].strip()
                        # print(inst)
                    else:
                        present = False
                        route_msg += str(leg_num) + ") " + inst + '\n'
                        leg_num += 1

            # msg = "Distance: " + info["routes"][0]["legs"][0]["distance"]["text"] + '\n' + "Duration in Traffic: " + \
            #       info["routes"][0]["legs"][0]["duration_in_traffic"]["text"] + '\n' + route

            name = ''
            thread_id = ''
            thread_type = ''
            for i in user_info_list:
                if route[5] == i[1]:
                    name = i[0]
                    thread_id = i[2]
                    thread_type = i[3]
                    break
            print(thread_id)
            print(thread_type)

            route_msg = "Hi " + name + '\n' + "\nYour \'" + route[1] + "\' route report for today is:\n\n" + \
                         "Distance: " + info["routes"][0]["legs"][0]["distance"]["text"] + '\n' + \
                         "Duration in Traffic: " + info["routes"][0]["legs"][0]["duration_in_traffic"]["text"] + \
                        "\n\nYour route instructinos is: \n" + route_msg + "\n\nOpen in Google Maps? Coming Soon"
            self.send(Message(text=route_msg),
                      thread_id=thread_id,
                      thread_type=ThreadType.USER)
Пример #41
0
# Nevow imports
from nevow import rend, loaders, tags
from twisted.application import service, internet, strports, app
from twisted.web import server, static
from twisted.python import failure
from twisted.internet import reactor
from nevow import inevow, rend, appserver, static, guard, url, loaders, stan
from nevow.taglibrary import tabbedPane

# Tums imports
import Tree, Realm, Database, xmlrpc
from Core import Utils, FlowCollector
from Pages import Index

try:
    db = Database.DatabaseBroker('mysql://*****:*****@localhost/exilog')
except Exception, c:
    print "No database to initialise" 
    print c 
    print "--- End of DB failure ---" 

try:
    l = open(Settings.BaseDir+'/initial').read()
    if "1" in l:
        #Settings.BaseDir = '/usr/local/tcs/tums'
        db = "FIRSTRUN"
except:
    print "No first"
    # Not first run
    pass
Пример #42
0
import Database
from Query.Optimizer import Optimizer
from Query.GreedyOptimizer import GreedyOptimizer
from Catalog.Schema import DBSchema
from time import time

db = Database.Database()
deptSchema = DBSchema('department', [('d_id', 'int'), ('d_name', 'char(30)')]);
emplSchema = DBSchema('employee', [('e_id', 'int'), ('e_name', 'char(30)'), ('e_projectid', 'int')])
projSchema = DBSchema('project', [('p_id','int'), ('p_name', 'char(30)')])
gratSchema = DBSchema('grant', [('g_id','int'), ('g_projectid', 'int'), ('g_source', 'char(30)')])
synSchema1 = DBSchema('syn1', [('a','int'), ('b', 'char(30)')])
synSchema2 = DBSchema('syn2', [('c','int'), ('d', 'char(30)'), ('e','int')])

db.createRelation('department', [('d_id', 'int'), ('d_name', 'char(30)')])
db.createRelation('employee', [('e_id', 'int'), ('e_name', 'char(30)'), ('e_projectid', 'int')])
db.createRelation('project', [('p_id','int'), ('p_name', 'char(30)')])
db.createRelation('grant', [('g_id','int'), ('g_projectid', 'int'), ('g_source', 'char(30)')])
db.createRelation('syn1', [('a','int'), ('b', 'char(30)')]);
db.createRelation('syn2', [('c','int'), ('d', 'char(30)'), ('e','int')]);

for tup in [deptSchema.pack(deptSchema.instantiate(i, "Nature"+str(i))) for i in range(4000)]:
  _ = db.insertTuple('department', tup);
for tup in [deptSchema.pack(deptSchema.instantiate(i, "Science"+str(i))) for i in range(4000, 8000)]:
  _ = db.insertTuple('department', tup);
ename = ["John", "Mike", "Davis", "Alex"];
for tup in [emplSchema.pack(emplSchema.instantiate(i, ename[i%4], i%10)) for i in range(8000)]:
  _ = db.insertTuple('employee', tup);
projectName = ["CS","EE","Biophysics","Biostats","NeuroScience", "Cell Biology"];
for tup in [projSchema.pack(projSchema.instantiate(i, projectName[i%6])) for i in range(8000)]:
  _ = db.insertTuple('project', tup);
Пример #43
0
    def __init__(self, parent=None):

        QtGui.QSplitter.__init__(self, parent)
        self.setWindowTitle('Daign Image Organizer')

        self.selected_range = []
        self.selected_image = None

        Database.create_database()

        # View

        self.view = DioView(self)

        # Controls

        self.scan_dialog = DioScanDialog(None)

        scan_button = QtGui.QPushButton('Scan Folders', self)
        scan_button.clicked.connect(self.scan_dialog.show)

        search_tags_button = QtGui.QPushButton('Load Tags', self)
        search_tags_button.clicked.connect(self.load_tags)
        self.search_tags_list = QtGui.QListWidget(self)

        search_names_button = QtGui.QPushButton('Load Names', self)
        search_names_button.clicked.connect(self.load_names)
        self.search_names_list = QtGui.QListWidget(self)

        search_stars_label = QtGui.QLabel('Stars')
        self.search_stars_from_input = QtGui.QSpinBox(self)
        self.search_stars_from_input.setRange(0, 7)
        self.search_stars_from_input.setValue(0)
        search_stars_to_label = QtGui.QLabel('to')
        self.search_stars_to_input = QtGui.QSpinBox(self)
        self.search_stars_to_input.setRange(0, 7)
        self.search_stars_to_input.setValue(7)
        search_stars_layout = QtGui.QHBoxLayout()
        search_stars_layout.addWidget(search_stars_label)
        search_stars_layout.addWidget(self.search_stars_from_input)
        search_stars_layout.addWidget(search_stars_to_label)
        search_stars_layout.addWidget(self.search_stars_to_input)
        search_stars_layout.addStretch(1)
        search_stars_widget = QtGui.QWidget(self)
        search_stars_widget.setLayout(search_stars_layout)

        show_random_button = QtGui.QPushButton('Random Image', self)
        show_random_button.clicked.connect(self.show_random_image)
        show_all_button = QtGui.QPushButton('All Images', self)
        show_all_button.clicked.connect(self.show_all_images)

        search_box = QtGui.QGroupBox('Image Search', self)
        search_grid = QtGui.QGridLayout()
        search_grid.addWidget(search_tags_button, 0, 0, 1, 1)
        search_grid.addWidget(search_names_button, 0, 1, 1, 1)
        search_grid.addWidget(self.search_tags_list, 1, 0, 1, 1)
        search_grid.addWidget(self.search_names_list, 1, 1, 1, 1)
        search_grid.addWidget(search_stars_widget, 2, 0, 1, 2)
        search_grid.addWidget(show_random_button, 3, 0, 1, 1)
        search_grid.addWidget(show_all_button, 3, 1, 1, 1)
        search_box.setLayout(search_grid)

        self.details = DioDetails(self)

        controls_layout = QtGui.QVBoxLayout()
        controls_layout.addWidget(scan_button, 1)
        controls_layout.addWidget(search_box, 2)
        controls_layout.addWidget(self.details, 1)

        controls_widget = QtGui.QWidget(self)
        controls_widget.setLayout(controls_layout)

        self.addWidget(self.view)
        self.addWidget(controls_widget)
        self.setSizes([600, 200])
Пример #44
0
 def Publish(self, user, label):
     Database.PublishPlaylist(self.playlistID, user, label)
Пример #45
0
 def setUp(self):
     self.db = Database.get_connection_with_dict_cursor(
         '../database.info', 'uoftcourses')
     self.cursor = self.db.cursor()
Пример #46
0
api_key = os.getenv("MAPBOX_API_KEY")
api_url_stem = "/api/v1/nyc/livemap"

from config import config

#-----------------------------------------------------------------------------------------
# sources
#
# api approach adapted from https://www.codementor.io/@sagaragarwal94/building-a-basic-restful-api-in-python-58k02xsiq
# query parameter handling after https://stackoverflow.com/questions/30779584/flask-restful-passing-parameters-to-get-request
#-----------------------------------------------------------------------------------------

#--------------- INITIALIZATION ---------------

db_connect = create_engine(
    db.get_db_url(config.config['dbuser'], config.config['dbpassword'],
                  config.config['dbhost'], config.config['dbname'])
)  # todo need a production override for this to set to 'localhost' for debugging?
app = Flask(__name__,
            template_folder='./api-www/templates',
            static_url_path='/static',
            static_folder="api-www/static/")
api = Api(app)
CORS(app)

#--------------- HELPER FUNCTIONS ---------------


def unpack_query_results(query):
    return [dict(zip(tuple(query.keys()), i)) for i in query.cursor]

Пример #47
0
        search_button.grid(column=0, row=5, columnspan=2)

        add_button = tk.Button(self.root, text="Add Student", command=add_fn)
        add_button.grid(column=2, row=5, columnspan=2)

        add_button = tk.Button(self.root,
                               text="Edit Topics",
                               command=edit_tp_fn)
        add_button.grid(column=0, row=6, columnspan=2)

        add_button = tk.Button(self.root,
                               text="Export/Reset DB",
                               command=export_csv)
        add_button.grid(column=2, row=6, columnspan=2)

        self.root.grab_set()
        # self.root.lift()
        #make the window appears
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        self.root.geometry("290x230+%d+%d" %
                           (screen_width / 2 - 285, screen_height / 2 - 230))
        self.root.lift()
        self.root.mainloop()


if __name__ == "__main__":
    #connecting with the database
    db = DB.Database('database/cup.db')
    new = gui_search(db)
Пример #48
0
 def refresh(self):
     self.data =db.get_response('StudentInfo').get_all_data()
     self.update_user_info(self.data)
Пример #49
0
 def search_data(self):
     std_name = self.src_ent.get()
     obj = db.get_response('StudentInfo')
     req_data = obj.get_data_by_query(std_name)
     self.update_user_info(req_data)
Пример #50
0
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.mainframe = tk.Frame(self)

        lbl_frm_table = ttk.LabelFrame(self.mainframe, text = "Student Data")
        lbl_frm_data = ttk.LabelFrame(self.mainframe , text = "Information")
        lbl_frm_info = ttk.LabelFrame(self.mainframe , text = "Data Entry")

#       ----------------------------------------------------/\/\ micellaneous/\/\-----------------------------------------------
        self.v1 = tk.StringVar()            #textvar of src_ent 
        self.v2 = tk.StringVar()            #self.name_ent            
        self.v3 = tk.StringVar()            #self.class_ent
        self.v4 = tk.StringVar()            #self.sec_ent
        self.v5 = tk.StringVar()            #self.roll_ent
        self.v6 = tk.StringVar()            #
#       ----------------------------------------------------/\/\ micellaneous/\/\-----------------------------------------------

#       ----------------------------------------------------/\/\ Frame table (lbl_frm_table) (s)/\/\-----------------------------------------------
        self.trview = ttk.Treeview(lbl_frm_table , columns = (1,2,3,4),show = "headings" , height = 6)
        self.trview.pack(fill = "both" ,expand=True , ipady = 5)
        self.trview.heading(1,text="Name")
        self.trview.heading(2,text="Class")
        self.trview.heading(3,text="Section")
        self.trview.heading(4,text="Roll no")
        self.trview.bind("<Double-Button-1>" , self.idrow)
#       ----------------------------------------------------/\/\ Frame table (lbl_frm_table)(e) /\/\-----------------------------------------------

#       ----------------------------------------------------/\/\ Frame data (lbl_frm_data)(s) /\/\-----------------------------------------------
        src_lbl = ttk.Label(lbl_frm_data, text="Search by name : ")
        self.src_ent = ttk.Entry(lbl_frm_data , textvariable = self.v1 )
        src_btn = ttk.Button(lbl_frm_data, text="Search", command= self.search_data)
        src_lbl.pack(side = "left" , padx = 20)
        self.src_ent.pack(side="left" )
        src_btn.pack(side="left", padx = 10)
        rfs_btn = ttk.Button(lbl_frm_data , text = "Refresh" , command=self.refresh)
        rfs_btn.pack(side="left", padx=10)
#       ----------------------------------------------------/\/\ Frame data (lbl_frm_data)(e) /\/\-----------------------------------------------

#       ----------------------------------------------------/\/\ Frame info (lbl_frm_info)(s) /\/\-----------------------------------------------
        name_lbl = ttk.Label(lbl_frm_info , text = "Name ")
        class_lbl = ttk.Label(lbl_frm_info , text = "Class ")
        sec_lbl = ttk.Label(lbl_frm_info , text = "Section ")
        roll_lbl = ttk.Label(lbl_frm_info , text = "Roll no ")

        name_lbl.grid(row = 0 , column = 0 , pady = 10)
        class_lbl.grid(row = 1 , column = 0, pady = 10)
        sec_lbl.grid(row = 2 , column = 0, pady = 10)
        roll_lbl.grid(row = 3 , column = 0, pady = 10)

        self.name_ent = ttk.Entry(lbl_frm_info , width = 35 , textvariable = self.v2)
        self.class_ent = ttk.Entry(lbl_frm_info, width = 35, textvariable = self.v3)
        self.sec_ent = ttk.Entry(lbl_frm_info, width = 35, textvariable = self.v4)
        self.roll_ent = ttk.Entry(lbl_frm_info, width = 35, textvariable = self.v5)

        self.name_ent.grid(row = 0 , column = 1 , pady = 10)
        self.class_ent.grid(row = 1 , column = 1, pady = 10)
        self.sec_ent.grid(row = 2 , column = 1, pady = 10)
        self.roll_ent.grid(row = 3 , column = 1, pady = 10)

        frm_btn = tk.Frame(lbl_frm_info)
        frm_btn.grid(row = 4,column = 1)

        add_btn = ttk.Button(frm_btn , text = "Add " , command = self.add_user_info)
        update_btn = ttk.Button(frm_btn, text = "Update ",command = self.update_data)
        del_btn = ttk.Button(frm_btn, text = "Delete ",command = self.delete_user_info)

        add_btn.grid(row = 0 , column = 0 ,padx =10)
        update_btn.grid(row = 0 , column = 1,padx =10)
        del_btn.grid(row = 0 , column = 2,padx =10)

        std_data = db.get_response("StudentInfo")
        self.data =std_data.get_all_data()
        self.update_user_info(self.data)

        # ----------------------------------------------------/\/\ Frame info (lbl_frm_info)(e) /\/\-----------------------------------------------

        lbl_frm_table.pack(fill = "both" , expand = True , padx=20 , pady = 10)
        lbl_frm_data.pack(fill = "both" , expand = True , padx=20 , pady = 10)
        lbl_frm_info.pack(fill = "both" , expand = True , padx=20 , pady = 10)

        self.mainframe.pack(fill = "both" , expand = True)  # Packing of the mainframe
Пример #51
0
'''This file is deprecated.'''
import sys
sys.path.append('../util/')
import Database
import argparse
import json

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('instructor', help="The full name of instructor")
    parser.add_argument('campus', help="The campus where the instructor stays")
    args = parser.parse_args()

    instructorFullName = args.instructor
    campus = args.campus

    connection = Database.get_connection_with_dict_cursor(
        '../../database.info', 'uoftcourses')
    dict_cursor = connection.cursor()

    course_list = Database.get_course_list_by_instructor(
        dict_cursor, instructorFullName, campus)
    json_course_list = json.dumps(course_list)
    print(json_course_list)
    sys.stdout.flush()
Пример #52
0
    def __init__(self, querylist, config, parent, debug=True):
        """Constructor for GraphViewer"""
        self.sql = querylist
        self.conf = config
        self.debug = debug
        self.parent = parent
        #print "start of GraphViewer constructor"
        self.db = Database.Database(self.conf, sql=self.sql)

        filters_display = {
            "Heroes": True,
            "Sites": True,
            "Games": True,
            "Currencies": True,
            "Limits": True,
            "LimitSep": True,
            "LimitType": True,
            "Type": False,
            "UseType": 'ring',
            "Seats": False,
            "SeatSep": False,
            "Dates": True,
            "GraphOps": True,
            "Groups": False,
            "Button1": True,
            "Button2": True
        }

        self.filters = Filters.Filters(self.db,
                                       self.conf,
                                       self.sql,
                                       display=filters_display)
        self.filters.registerButton1Name(_("Refresh _Graph"))
        self.filters.registerButton1Callback(self.generateGraph)
        self.filters.registerButton2Name(_("_Export to File"))
        self.filters.registerButton2Callback(self.exportGraph)

        self.mainHBox = gtk.HBox(False, 0)
        self.mainHBox.show()

        self.leftPanelBox = self.filters.get_vbox()

        self.hpane = gtk.HPaned()
        self.hpane.pack1(self.leftPanelBox)
        self.mainHBox.add(self.hpane)
        # hierarchy:  self.mainHBox / self.hpane / self.graphBox / self.canvas / self.fig / self.ax

        self.graphBox = gtk.VBox(False, 0)
        self.graphBox.show()
        self.hpane.pack2(self.graphBox)
        self.hpane.show()

        self.fig = None
        #self.exportButton.set_sensitive(False)
        self.canvas = None

        self.exportFile = None

        self.db.rollback()

        #update the graph at entry (simulate a "Refresh Graph" click)
        gobject.GObject.emit(self.filters.Button1, "clicked")
Пример #53
0
    def __init__(self):
        # Version and Copyright
        self.VersionNumber = ("0.01" + " " + gBUILD_VERSION)
        self.Version = "%prog Version " + self.VersionNumber
        self.Copyright = "Copyright (c) 2009 - 2010, Intel Corporation  All rights reserved."

        self.InitDefaultConfigIni()
        self.OutputFile = 'output.txt'
        self.ReportFile = 'Report.csv'
        self.ExceptionFile = 'exception.xml'
        self.IsInit = True
        self.ScanSourceCode = True
        self.ScanMetaData = True
        self.MetaFile = ''
        self.OnlyScan = None

        # Parse the options and args
        self.ParseOption()

        #
        # Check EFI_SOURCE (Edk build convention). EDK_SOURCE will always point to ECP
        #
        WorkspaceDir = os.path.normcase(
            os.path.normpath(os.environ["WORKSPACE"]))
        os.environ["WORKSPACE"] = WorkspaceDir
        if "ECP_SOURCE" not in os.environ:
            os.environ["ECP_SOURCE"] = os.path.join(
                WorkspaceDir, GlobalData.gEdkCompatibilityPkg)
        if "EFI_SOURCE" not in os.environ:
            os.environ["EFI_SOURCE"] = os.environ["ECP_SOURCE"]
        if "EDK_SOURCE" not in os.environ:
            os.environ["EDK_SOURCE"] = os.environ["ECP_SOURCE"]

        #
        # Unify case of characters on case-insensitive systems
        #
        EfiSourceDir = os.path.normcase(
            os.path.normpath(os.environ["EFI_SOURCE"]))
        EdkSourceDir = os.path.normcase(
            os.path.normpath(os.environ["EDK_SOURCE"]))
        EcpSourceDir = os.path.normcase(
            os.path.normpath(os.environ["ECP_SOURCE"]))

        os.environ["EFI_SOURCE"] = EfiSourceDir
        os.environ["EDK_SOURCE"] = EdkSourceDir
        os.environ["ECP_SOURCE"] = EcpSourceDir

        GlobalData.gWorkspace = WorkspaceDir
        GlobalData.gEfiSource = EfiSourceDir
        GlobalData.gEdkSource = EdkSourceDir
        GlobalData.gEcpSource = EcpSourceDir

        GlobalData.gGlobalDefines["WORKSPACE"] = WorkspaceDir
        GlobalData.gGlobalDefines["EFI_SOURCE"] = EfiSourceDir
        GlobalData.gGlobalDefines["EDK_SOURCE"] = EdkSourceDir
        GlobalData.gGlobalDefines["ECP_SOURCE"] = EcpSourceDir

        # Generate checkpoints list
        EccGlobalData.gConfig = Configuration(self.ConfigFile)

        # Generate exception list
        EccGlobalData.gException = ExceptionCheck(self.ExceptionFile)

        # Init Ecc database
        EccGlobalData.gDb = Database.Database(Database.DATABASE_PATH)
        EccGlobalData.gDb.InitDatabase(self.IsInit)

        #
        # Get files real name in workspace dir
        #
        GlobalData.gAllFiles = DirCache(GlobalData.gWorkspace)

        # Build ECC database
        #         self.BuildDatabase()
        self.DetectOnlyScanDirs()

        # Start to check
        self.Check()

        # Show report
        self.GenReport()

        # Close Database
        EccGlobalData.gDb.Close()
Пример #54
0
 def test_get_avg_prof_quality_by_department(self):
     assert Database.get_avg_prof_quality_by_department(
         self.cursor, "CSC") == {
             'average_course_atmosphere': 3.9,
             'average_enthusiasm': 3.95
         }
Пример #55
0
    def read_stdin(self):  # This is the thread function
        """Do all the non-gui heavy lifting for the HUD program."""

        #    This db connection is for the read_stdin thread only. It should not
        #    be passed to HUDs for use in the gui thread. HUD objects should not
        #    need their own access to the database, but should open their own
        #    if it is required.
        self.db_connection = Database.Database(self.config, self.db_name,
                                               'temp')
        #        self.db_connection.init_hud_stat_vars(hud_days)
        tourny_finder = re.compile('(\d+) (\d+)')

        while 1:  # wait for a new hand number on stdin
            new_hand_id = sys.stdin.readline()
            new_hand_id = string.rstrip(new_hand_id)
            if new_hand_id == "":  # blank line means quit
                self.destroy()
                break  # this thread is not always killed immediately with gtk.main_quit()
#    get basic info about the new hand from the db
#    if there is a db error, complain, skip hand, and proceed
            try:
                (table_name, max, poker_game, type, fast, site_id,
                 numseats) = self.db_connection.get_table_name(new_hand_id)
                stat_dict = self.db_connection.get_stats_from_hand(
                    new_hand_id, aggregate_stats[type], hud_style, agg_bb_mult)

                cards = self.db_connection.get_cards(new_hand_id)
                comm_cards = self.db_connection.get_common_cards(new_hand_id)
                if comm_cards != {}:  # stud!
                    cards['common'] = comm_cards['common']
            except Exception, err:
                err = traceback.extract_tb(sys.exc_info()[2])[-1]
                #print _("db error: skipping ")+str(new_hand_id)+" "+err[2]+"("+str(err[1])+"): "+str(sys.exc_info()[1])
                if new_hand_id:  # new_hand_id is none if we had an error prior to the store
                    sys.stderr.write(
                        _("Database error %s in hand %d. Skipping.") %
                        (err, int(new_hand_id)) + "\n")
                continue

            if type == "tour":  # hand is from a tournament
                mat_obj = tourny_finder.search(table_name)
                if mat_obj:
                    (tour_number, tab_number) = mat_obj.group(1, 2)
                    temp_key = tour_number
                else:  # tourney, but can't get number and table
                    #print _("could not find tournament: skipping")
                    sys.stderr.write(
                        _("Could not find tournament %d in hand %d. Skipping.")
                        % (int(tour_number), int(new_hand_id)) + "\n")
                    continue

            else:
                temp_key = table_name

#    Update an existing HUD
            if temp_key in self.hud_dict:
                self.hud_dict[temp_key].stat_dict = stat_dict
                self.hud_dict[temp_key].cards = cards
                [
                    aw.update_data(new_hand_id, self.db_connection)
                    for aw in self.hud_dict[temp_key].aux_windows
                ]
                self.update_HUD(new_hand_id, temp_key, self.config)


#    Or create a new HUD
            else:
                if type == "tour":
                    tablewindow = Tables.discover_tournament_table(
                        self.config, tour_number, tab_number)
                else:
                    tablewindow = Tables.discover_table_by_name(
                        self.config, table_name)
                if tablewindow is None:
                    #    If no client window is found on the screen, complain and continue
                    if type == "tour":
                        table_name = "%s %s" % (tour_number, tab_number)
                    sys.stderr.write(
                        _("Table name %s not found, skipping.") % table_name)
                else:
                    self.create_HUD(new_hand_id, tablewindow, temp_key, max,
                                    poker_game, stat_dict, cards)
            self.db_connection.connection.rollback()
Пример #56
0
    def login(self):
        """
        Login to the user account.
        This involves setting all contact information by pulling and decrypting information from the database
        """
        self.username = input("Please enter email: ")
        password = input("Please enter your password: "******"Account not verified. Please check username and password and try again."
            )
            self.authenticate()
            return

        # Receive contact information that is stored in the database
        contacts = Database.get_user_contact_info(self.username)
        for contact in contacts:

            # Ensure necesary information is there
            keys = ("contact", "contact_aes", "hmac_key", "signature",
                    "iv_aes", "iv_hmac")
            invalid = False
            for key in keys:  # Make sure all the keys are present
                if key not in contact:
                    invalid = True
                    print("Not all fields in contact return")

            if invalid:
                continue

            for key in keys:
                if not contact[key]:  # Make sure each entry has a value
                    print("Not all fields in contact have value return")
                    invalid = True
            if invalid:
                continue

            # Get contact info
            recipient = contact["contact"]
            enc_aes_b64 = contact["contact_aes"].encode()[2:-1]
            enc_aes = base64.b64decode(enc_aes_b64)
            enc_hmac_b64 = contact["hmac_key"].encode()[2:-1]
            enc_hmac = base64.b64decode(enc_hmac_b64)
            signed_b64 = contact["signature"].encode()[2:-1]
            signed = base64.b64decode(signed_b64)
            iv_aes_b64 = contact["iv_aes"].encode()[2:-1]
            iv_aes = base64.b64decode(iv_aes_b64)
            iv_hmac_b64 = contact["iv_hmac"].encode()[2:-1]
            iv_hmac = base64.b64decode(iv_hmac_b64)

            # Check signature
            signature_contents = self.username + recipient + contact[
                "contact_aes"] + contact["hmac_key"] + contact[
                    "iv_aes"] + contact["iv_hmac"]
            if not Crypto_Functions.check_hmac_b64(signature_contents.encode(),
                                                   signed, self.password_hmac):
                print(
                    "The password you entered does not match the stored data. This could be caused by an incorrect password, or the data could be corrupted."
                )
                self.login()
                return

            # Decrypt keys
            try:
                aes_key = Crypto_Functions.aes_decrypt(enc_aes, iv_aes,
                                                       self.password_aes)
                aes_key = base64.b64decode(aes_key.encode()[2:-1])
                hmac_key = Crypto_Functions.aes_decrypt(
                    enc_hmac, iv_hmac, self.password_aes)
                hmac_key = base64.b64decode(hmac_key.encode()[2:-1])
                self.contacts[recipient] = {
                    "aes_key": aes_key,
                    "hmac_key": hmac_key
                }
            except:
                print("Incorrect Decryption")

        # Reveive group information that is stored in the database
        groups = Database.get_username_groups(self.username)
        for contact in groups:
            # Ensure necesary information is there
            # print("12", contact)
            keys = ("group_name", "participant", "aes_key", "hmac_key",
                    "signature", "aes_iv", "hmac_iv")
            invalid = False
            for key in keys:  # Make sure all the keys are present
                if key not in contact:
                    print("Not all fields in contact return 1")
                    invalid = True

            if invalid:
                continue

            for key in keys:
                if not contact[key]:  # Make sure each entry has a value
                    print("Not all fields in contact have value return 1")
                    invalid = True
            if invalid:
                continue

            # Get information from database line
            group_name = contact["group_name"]
            recipient = contact["participant"]
            enc_aes_b64 = contact["aes_key"].encode()[2:-1]
            enc_aes = base64.b64decode(enc_aes_b64)
            enc_hmac_b64 = contact["hmac_key"].encode()[2:-1]
            enc_hmac = base64.b64decode(enc_hmac_b64)
            signed_b64 = contact["signature"].encode()[2:-1]
            signed = base64.b64decode(signed_b64)
            iv_aes_b64 = contact["aes_iv"].encode()[2:-1]
            iv_aes = base64.b64decode(iv_aes_b64)
            iv_hmac_b64 = contact["hmac_iv"].encode()[2:-1]
            iv_hmac = base64.b64decode(iv_hmac_b64)

            # Check the signature
            # signature_contents = email + contact + enc_group_aes + enc_hmac_key + iv_aes + iv_hmac
            # signature = str(Crypto_Functions.hmac_b64(signature_contents.encode(), self.password_hmac))
            signature_contents = self.username + recipient + contact[
                "aes_key"] + contact["hmac_key"] + contact["aes_iv"] + contact[
                    "hmac_iv"]
            # print(signature_contents)
            if not Crypto_Functions.check_hmac_b64(signature_contents.encode(),
                                                   signed, self.password_hmac):
                print(
                    "The password you entered does not match the stored data. This could be caused by an incorrect password, or the data could be corrupted."
                )
                self.login()
                return

            # Decrypt keys
            try:
                aes_key = Crypto_Functions.aes_decrypt(enc_aes, iv_aes,
                                                       self.password_aes)
                aes_key = base64.b64decode(aes_key.encode()[2:-1])
                hmac_key = Crypto_Functions.aes_decrypt(
                    enc_hmac, iv_hmac, self.password_aes)
                hmac_key = base64.b64decode(hmac_key.encode()[2:-1])

                # Make sure group has been added to group dict
                if group_name not in self.groups:
                    self.groups[group_name] = {}

                # Group has already been added to groups dict
                self.groups[group_name]["aes_key"] = aes_key
                self.groups[group_name]["hmac_key"] = hmac_key

                # Member list already created and current recipient not in it
                if "members" in self.groups[
                        group_name] and recipient not in self.groups[
                            group_name]:
                    self.groups[group_name]["members"].append(recipient)

                # If the user isn't in list add them to a new list
                elif recipient not in self.groups[group_name]:
                    self.groups[group_name]["members"] = [recipient]

            except:
                print("Incorrect Decryption")

        request = Requests.login(self.username)
        self.s.send(request)
        self.loggedin = True
        print("Welcome, " + self.username + "!")
        print(
            "You're currently in the listening mode. To issue a command, press ENTER. You can type :help to see all the available commands."
        )
Пример #57
0
    def create_account(self):
        valid_username = False
        while not valid_username:
            self.username = input("Enter email: ")
            if (Database.check_user(self.username)):
                print("Username already exists in the system.")
            else:
                valid_username = True

        # Here for email verification
        valid_email = False
        while not valid_email:
            email = self.username
            print(email)
            if not self.check_email_valid(email):
                print("Email entered not valid")
                self.create_account()
            else:
                request = Requests.send_email(email)
                self.ca.send(request)
                code = input(
                    "Please enter the verification code sent to your email address: "
                )
                request2 = Requests.verify_email(code)
                self.ca.send(request2)
                data = self.ca.recv(4096)
                request = Requests.parse_request(data)
                if request.is_ca_response_email_valid():
                    print("Authentication was successful")
                    valid_email = True
                elif request.is_ca_response_email_invalid():
                    print("Code was not valid. Please try again.")

        strong_password = False
        while not strong_password:
            password = input("Create new password: "******"Waiting for CA...")
                    data = self.ca.recv(4096)
                    request = Requests.parse_request(data)
                    if len(request.data) == 0:
                        print(
                            "There was in issue with the received data. Received the following raw data: ",
                            data)
                    elif request.is_ca_response_valid():
                        print("Received a valid response from CA.")
                        print("Sending account information to the server.")
                        username = request.data["username"]
                        public_key = request.data["public_key"]
                        ca_signature = request.data["signature"]
                        request = Requests.create_new_account(
                            username, public_key, ca_signature)

                        private_key_b64 = base64.b64encode(self.private_key)
                        enc_private_key, aes_iv = Crypto_Functions.aes_encrypt(
                            str(private_key_b64), self.password_aes)
                        enc_private_key_b64 = base64.b64encode(enc_private_key)
                        aes_iv_b64 = base64.b64encode(aes_iv)

                        tag_contents = str(enc_private_key_b64) + str(
                            aes_iv_b64)
                        hmac = Crypto_Functions.hmac_b64(
                            tag_contents.encode(), self.password_hmac)
                        hmac_b64 = hmac

                        Database.add_user_account(self.username,
                                                  str(enc_private_key_b64),
                                                  str(aes_iv_b64),
                                                  str(hmac_b64))

                        self.s.send(request)
                        break
                    elif request.is_ca_response_invalid():
                        print(
                            "CA indicated an invalid request. Please try again with a different username."
                        )
                        self.create_account()
                        break

                # When we get to this point, we know CA sent back a valid response and that we sent a request
                # to the server to create an account. Now we wait for the server to send a confirmation that
                # the account has been created.
                while True:
                    print("Waiting for the server...")
                    data = self.s.recv(4096)
                    request = Requests.parse_request(data)
                    if len(request.data) == 0:
                        print(
                            "There was in issue with the received data. Received the following raw data: ",
                            data)
                    elif request.is_account_created():
                        print(
                            "Account successfully created! Please log in with your new credentials."
                        )
                        break
                    elif request.is_account_not_created():
                        print("Account was not created. Please try again.")
                        self.create_account()
            else:
                print(
                    "The password you typed was not secure. Password must use letters and numbers and must be at least 8 characters."
                )

        # When we get to this point, we know that the user's account has been created and we prompt the user to login
        # with their new credentials to proceed.
        self.login()
Пример #58
0
import Database
import datetime
import twitter_activities

test_act_db = Database.ActionDB(testing=1)
test_req_db = Database.RequestDB(testing=1)
# sample_a_dict = {'row_date': datetime.datetime.now(),
#                  'link': 'http:sample_a.like.com',
#                  'directive': 'like',
#                  'testing': 1}
#
# sample_b_dict = {'row_date': datetime.datetime.now(),
#                  'link': 'http:sample_b.comment',
#                  'directive': 'comment',
#                  'text': 'I am comment_text_var',
#                  'testing': 1}
#
# sample_c_dict = {'row_date': datetime.datetime.now(),
#                  'link': 'http:sample_c.retweet',
#                  'directive': 'retweet',
#                  'testing': 1}
#
# my_dicts_list = [Database.ActionRow(sample_a_dict),
#                  Database.ActionRow(sample_b_dict),
#                  Database.ActionRow(sample_c_dict)]
# #
# # x = my_dicts_list[0]
#
# for i in my_dicts_list:
#     test_act_db.add_to_db(row_obj=i)
Пример #59
0
    def handle_receive(self):
        """
        Handles all of the different receiving requests from server
        """
        while True:
            data = self.s.recv(4096)
            request = Requests.parse_request(data)
            with self.console_lock:
                # Handle different message types
                if request.is_direct_message():
                    Receive.receive_direct(request.data, self.contacts,
                                           self.received_timestamps)
                elif request.is_group_message():
                    Receive.receive_group(request.data, self.groups,
                                          self.received_timestamps)
                elif request.is_broadcast():
                    print(request.data["message"])

                # Initiate the group chat and save keys
                elif request.is_initiate_group_chat():
                    print("Initiating new group chat...")

                    requester = request.data["requester"]
                    # Make sure we have the contact
                    if requester not in self.contacts or "public_key" not in self.contacts[
                            requester].keys():
                        self.populate_public_keys(requester)

                    # Recieve the handshake
                    keys = Receive.receive_group_handshake(
                        request.data, self.username, self.groups,
                        self.contacts, self.private_key)
                    group_name = keys["group_name"]
                    aes_key = keys["aes"]
                    hmac_key = keys["hmac"]
                    members = keys["members"]

                    # This will completely overwrite or add a new one
                    self.groups[group_name] = {
                        "aes_key": aes_key,
                        "hmac_key": hmac_key,
                        "members": members
                    }

                    email = self.username

                    # Get encrypted aes under self.password_aes
                    group_aes = str(base64.b64encode(aes_key))
                    enc_goup_aes, iv_aes = Crypto_Functions.aes_encrypt(
                        group_aes, self.password_aes)
                    enc_goup_aes = str(base64.b64encode(enc_goup_aes))
                    iv_aes = str(base64.b64encode(iv_aes))

                    # get encrypted hmac under self.password_aes
                    hmac_key = str(base64.b64encode(hmac_key))
                    enc_hmac_key, iv_hmac = Crypto_Functions.aes_encrypt(
                        hmac_key, self.password_aes)
                    enc_hmac_key = str(base64.b64encode(enc_hmac_key))
                    iv_hmac = str(base64.b64encode(iv_hmac))

                    # Add line for each member
                    for member in members:
                        contact = member
                        signature_contents = email + contact + enc_goup_aes + enc_hmac_key + iv_aes + iv_hmac
                        signature = str(
                            Crypto_Functions.hmac_b64(
                                signature_contents.encode(),
                                self.password_hmac))

                        Database.add_group(self.username, group_name, contact,
                                           signature, enc_goup_aes, iv_aes,
                                           enc_hmac_key, iv_hmac)

                elif request.is_initiate_direct_message():
                    requester = request.data["requester"]
                    if requester not in self.contacts:
                        self.populate_public_keys(requester)

                    keys = Receive.receive_direct_handshake(
                        request.data, self.contacts,
                        self.contacts[requester]["public_key"],
                        self.private_key)
                    aes_key = keys["aes"]
                    hmac_key = keys["hmac"]

                    # This will add or overwrite two fields to the requester's contact, leaving the others
                    self.contacts[requester]["aes_key"] = aes_key
                    self.contacts[requester]["hmac_key"] = hmac_key

                    email = self.username
                    contact = requester

                    # Get encrypted aes under self.password_aes
                    contact_aes = str(base64.b64encode(aes_key))
                    enc_contact_aes, iv_aes = Crypto_Functions.aes_encrypt(
                        contact_aes, self.password_aes)
                    enc_contact_aes = str(base64.b64encode(enc_contact_aes))
                    iv_aes = str(base64.b64encode(iv_aes))

                    # Get encrypted hmac under self.password_aes
                    hmac_key = str(base64.b64encode(hmac_key))
                    enc_hmac_key, iv_hmac = Crypto_Functions.aes_encrypt(
                        hmac_key, self.password_aes)
                    enc_hmac_key = str(base64.b64encode(enc_hmac_key))
                    iv_hmac = str(base64.b64encode(iv_hmac))

                    # Create the signature
                    signature_contents = self.username + contact + enc_contact_aes + enc_hmac_key + iv_aes + iv_hmac
                    signature = str(
                        Crypto_Functions.hmac_b64(signature_contents.encode(),
                                                  self.password_hmac))

                    Database.add_contact_info(email, contact, enc_contact_aes,
                                              signature, iv_aes, enc_hmac_key,
                                              iv_hmac)
class Menu:
    def __init__(self):
        pygame.init()
        Var.infoObject = pygame.display.Info()
        self.tetris = Tetris()
        self.database = Database()
        self.w = Var.menu_display_w
        self.h = Var.menu_display_h
        self.Mode = Var.initial_mode
        self.id = Var.initial_id
        self.score = Var.initial_score
        self.page = Var.initial_page
        self.surface = pygame.display.set_mode((self.w, self.h), RESIZABLE)
        self.mytheme = Var.mytheme
        self.mytheme2 = Var.mytheme_help
        self.menu = pygame_menu.Menu(self.h, self.w, '', theme=self.mytheme)
        self.font_main = Var.font_main  # 메인 폰트 사이즈
        self.font_sub = Var.font_sub  # 서브 폰트 사이즈
        self.widget_margin_main = Var.widget_margin_main  #메인 위젯 사이 간격
        self.widget_margin_showpage = Var.widget_margin_showpage  #show 페이지 위젯 사이 간격
        self.widget_margin_rank = Var.widget_margin_rank  #rank 페이지 위젯 사이 간격
        self.margin_main = Var.margin_main  #메인 페이지 x,y 위젯 시작 위치
        self.margin_show = Var.margin_show  #show 페이지 x,y 위젯 시작 위치
        self.margin_help = Var.margin_help  #help 페이지 back 위치
        self.margin_rank = Var.margin_rank  #rank 페이지 x,y 위젯 시작 위치

    def run(self):
        print('test2')
        self.page = Var.initial_page
        self.menu.clear()
        self.mytheme.widget_margin = self.widget_margin_main
        self.menu.add_vertical_margin(self.margin_main)
        self.menu.add_button('   Select mode   ',
                             self.show_game,
                             font_size=self.font_main)
        self.menu.add_button('    Show Rank    ',
                             self.show_rank,
                             font_size=self.font_main)
        self.menu.add_button('  Help  ', self.help, font_size=self.font_main)
        self.menu.add_button('        Quit         ',
                             pygame_menu.events.EXIT,
                             font_size=self.font_main)

    def reset(self):  ## 뒤로 갈때 보여줄 목록들
        self.surface = pygame.display.set_mode((self.w, self.h), RESIZABLE)
        self.menu = pygame_menu.Menu(self.h, self.w, '', theme=self.mytheme)
        self.page = 'page0'
        self.mytheme.widget_margin = self.widget_margin_main
        Var.click.play()
        self.page = Var.initial_page
        self.menu.clear()
        self.menu.add_vertical_margin(self.margin_main)
        self.menu.add_button('   Select mode   ',
                             self.show_game,
                             font_size=self.font_main)
        self.menu.add_button('    Show Rank    ',
                             self.show_rank,
                             font_size=self.font_main)
        self.menu.add_button('  Help  ', self.help, font_size=self.font_main)
        self.menu.add_button('        Quit         ',
                             pygame_menu.events.EXIT,
                             font_size=self.font_main)

    def help(self):
        self.page = 'page7'
        self.surface = pygame.display.set_mode((self.w, self.h), RESIZABLE)
        self.menu = pygame_menu.Menu(self.h, self.w, '', theme=self.mytheme2)
        self.menu.add_vertical_margin(self.margin_help)
        self.menu.add_button(' back ', self.reset, font_size=self.font_sub)

    def show_game(self):  ## 게임 목록 들어가면 나오는 목록들
        self.page = 'page1'
        Var.click.play()
        self.menu.clear()
        self.mytheme.widget_margin = self.widget_margin_showpage
        self.menu.add_vertical_margin(self.margin_main)
        self.menu.add_label("    --Start game--    ",
                            selectable=False,
                            font_size=self.font_main)
        self.menu.add_vertical_margin(self.margin_show)
        self.menu.add_button('      Single mode      ',
                             self.start_the_game,
                             font_size=self.font_main)
        self.menu.add_button('       MiNi mode       ',
                             self.start_the_Mini,
                             font_size=self.font_main)
        self.menu.add_button('    Twohands mode   ',
                             self.start_the_Twohands,
                             font_size=self.font_main)
        self.menu.add_button('         Ai mode         ',
                             self.start_the_Ai,
                             font_size=self.font_main)
        self.menu.add_button('           back            ',
                             self.reset,
                             font_size=self.font_main)

    def show_rank(self):  ## 랭크 들어가면 나오는 목록들기
        self.page = 'page2'
        Var.click.play()
        self.menu.clear()
        self.mytheme.widget_margin = self.widget_margin_showpage
        self.menu.add_vertical_margin(self.margin_main)
        self.menu.add_label("     --Show Rank--     ",
                            max_char=0,
                            selectable=False,
                            font_size=self.font_main)
        self.menu.add_vertical_margin(self.margin_show)
        self.menu.add_button('      Single mode      ',
                             self.Single_the_rank,
                             font_size=self.font_main)
        self.menu.add_button('    Twohands mode   ',
                             self.Twohands_the_rank,
                             font_size=self.font_main)
        self.menu.add_button('       MiNi mode       ',
                             self.Mini_the_rank,
                             font_size=self.font_main)
        self.menu.add_button('           back            ',
                             self.reset,
                             font_size=self.font_main)

    def show_score(self, game_mode, game_score):
        self.page = 'page6'
        self.Mode = game_mode
        self.score = game_score
        self.surface = pygame.display.set_mode((self.w, self.h), RESIZABLE)
        self.mytheme.widget_margin = self.widget_margin_main
        self.menu.add_vertical_margin(self.margin_main)
        self.menu.add_button(self.Mode + ' Mode',
                             self.pass_,
                             font_size=self.font_main)
        self.menu.add_text_input('ID: ',
                                 maxchar=Var.rank_id_max,
                                 onreturn=self.save_id,
                                 font_size=self.font_main)
        self.menu.add_button("Exit",
                             pygame_menu.events.EXIT,
                             font_size=self.font_main)

    def save_id(self, value):
        self.id = value
        self.database.add_data(self.Mode, self.id, self.score)
        self.reset()

    def stop(self):
        Var.click.play()
        self.menu.disable()

    def Single_the_rank(self):
        self.page = 'page3'
        Var.click.play()
        self.menu.clear()
        self.mytheme.widget_margin = self.widget_margin_rank
        self.menu.add_vertical_margin(self.margin_main)
        self.menu.add_label("--Single Rank--",
                            selectable=False,
                            font_size=self.font_main)
        self.menu.add_vertical_margin(self.margin_rank)
        self.menu.add_button("       ID       Score",
                             self.Mini_the_rank,
                             font_size=self.font_sub)
        original_data = self.database.load_data("basic")
        for i in range(Var.rank_max):
            original_name = str(original_data[i]['ID'])
            original_score = '{0:>05s}'.format(str(original_data[i]['score']))
            r = "#{} : ".format(i +
                                1) + original_name + "    " + original_score
            self.menu.add_button(r, self.pass_, font_size=self.font_sub)
        self.menu.add_button('back', self.reset, font_size=self.font_sub)

    def Twohands_the_rank(self):
        self.page = 'page4'
        Var.click.play()
        self.menu.clear()
        self.mytheme.widget_margin = self.widget_margin_rank
        self.menu.add_vertical_margin(self.margin_main)
        twohadns_data = self.database.load_data("two")
        self.menu.add_label("--Two Rank--",
                            selectable=False,
                            font_size=self.font_main)
        self.menu.add_vertical_margin(self.margin_rank)
        self.menu.add_button("       ID       Score",
                             self.pass_,
                             font_size=self.font_sub)
        for i in range(Var.rank_max):
            original_name = str(twohadns_data[i]['ID'])
            original_score = '{0:>05s}'.format(str(twohadns_data[i]['score']))
            r = "#{} : ".format(i +
                                1) + original_name + "    " + original_score
            self.menu.add_button(r, self.pass_, font_size=self.font_sub)
        self.menu.add_button('back', self.reset, font_size=self.font_sub)

    def Mini_the_rank(self):
        self.page = 'page5'
        Var.click.play()
        self.menu.clear()
        self.mytheme.widget_margin = self.widget_margin_rank
        mini_data = self.database.load_data("mini")
        self.menu.add_vertical_margin(self.margin_main)
        self.menu.add_label("--Mini Rank--",
                            selectable=False,
                            font_size=self.font_main)
        self.menu.add_vertical_margin(self.margin_rank)
        self.menu.add_button("       ID       Score",
                             self.pass_,
                             font_size=self.font_sub)
        for i in range(Var.rank_max):
            original_name = str(mini_data[i]['ID'])
            original_score = '{0:>05s}'.format(str(mini_data[i]['score']))
            r = "#{} : ".format(i +
                                1) + original_name + "    " + original_score
            self.menu.add_button(r, self.pass_, font_size=self.font_sub)
        self.menu.add_button('back', self.reset, font_size=self.font_sub)

    def start_the_game(self):
        Var.click.play()
        self.Mode = 'basic'
        self.tetris.mode = 'basic'
        self.tetris.run()
        self.menu.clear()
        self.show_score(self.Mode, self.tetris.Score)

    def start_the_Mini(self):
        Var.click.play()
        self.Mode = 'mini'
        self.tetris.mode = 'mini'
        self.tetris.run()
        self.menu.clear()
        self.show_score(self.Mode, self.tetris.Score)

    def start_the_Twohands(self):
        Var.click.play()
        self.Mode = 'two'
        self.tetris.mode = 'two'
        self.tetris.run()
        self.menu.clear()
        self.show_score(self.Mode, self.tetris.Score)

    def start_the_Ai(self):
        Var.click.play()
        self.Mode = 'ai'
        self.tetris.mode = 'ai'
        self.tetris.run()
        self.reset()

    def pass_(self):
        pass