Ejemplo n.º 1
0
def reset_pass():
    if 'directorID' not in session and 'artistID' not in session and 'coachID' not in session:
        return redirect(
            url_for('login')
        )  # this means this post request is only accessible through previously logging in
    newPass = request.form['password']
    userID = request.form['userID']
    role = request.form['role']
    service = UserService()
    error = service.passwordCheck(newPass)
    print(error)
    if error is not True:
        return render_template(
            'resetPass.html', userID=userID, role=role,
            error=error)  # this means its the first time they logged in
    if service.resetPass(userID, newPass, role):
        print("updated")
        return redirect(
            url_for(role + '_home'))  # go to correct home page for the role
    else:
        return render_template(
            'resetPass.html',
            userID=userID,
            role=role,
            error="There was an error, please contact the director")
Ejemplo n.º 2
0
def create_artist():
    if 'directorID' not in session:  #authentication - least authorized principle
        return redirect(url_for('login'))
    error = None
    service = DirectorService()
    if request.method == "POST":
        username = request.form['username']
        password = request.form['password']
        birthdate = request.form['birthdate']
        email = request.form['email']
        userService = UserService()
        if userService.checkEmail(email) is False:
            error = "Not a valid email"
        else:
            classID = request.form['classID']
            response = service.register_artist(username, password, birthdate,
                                               email, classID)
            if response != True:
                error = response
            else:
                return redirect(url_for('director_home'))
    classDetails = service.get_all_class_details()
    date = datetime.date(datetime.today()) - timedelta(days=7 * 365)
    return render_template('registerArtist.html',
                           minAge=date,
                           error=error,
                           classDetails=classDetails)
Ejemplo n.º 3
0
    def get(self):
        user = UserService.getCurrentUserOrRedirect(self)
        if not user:
            return
        if self.request.get("redirect"):
            self.response.headers.add_header(
                'Set-Cookie',
                UserService.makeCookieString(
                    user.getLoginExpirationTime().strftime(time_format),
                    {"access_token": user.accessToken}))
            self.response.headers.add_header('Content Type', "text/Html")
            self.redirect(self.request.get("redirect"))
            self.error(302)
            return

        DATA = temp()
        DATA.user = user
        DATA.accessToken = user.accessToken
        DATA.lastAccessTime = user.dateLastAccessed
        try:
            DATA.settings = json.loads(user.settings)
        except Exception, err:
            obj = {"TwitterShortenURL": False, "TwitterSplitStatus": False}
            user.settings = json.dumps(obj)
            user.put()
            DATA.settings = obj
Ejemplo n.º 4
0
    def get(self,job):
        if job not in ['authenticate','authenticated','follow','unfollow','longtweet','feed']:
            self.error(404)
            return
            
        user = UserService.getCurrentUser(self)
        if not user:
            if job in ('follow','unfollow'):
                self.response.headers.add_header("Content-Type","application/json")
                self.response.out.write(json.dumps({"result":"error","message":"Unauthenticated User"}))
                return
            UserService.getCurrentUserOrRedirect(self)
            return

        getattr(self,job)(user)
Ejemplo n.º 5
0
    def get(self):
        class temp:
            pass
        DATA = temp()
        
        DATA.user = UserService.getCurrentUser(self)
        
        self.response.headers['Content-Type'] = "text/html"
        
        if self.request.get("t") in (None,""):
            DATA.threads = Thread.all().order("-time").fetch(10)
            for thread in DATA.threads:
                thread.posts_expanded = map(Post.get_by_id,thread.posts)
        else:
            obj = Thread.get_by_id(int(self.request.get("t")))
            if obj is None:
                self.error(404)
                return
            DATA.threads = []
            for thread in DATA.threads:
                thread.posts_expanded = map(Post.get_by_id,thread.posts)

        path = os.path.join(os.path.dirname(__file__), 'html/sidebar.html')
        f = open(path,"r")
        DATA.sidebar = f.read()
        f.close()
        path = os.path.join(os.path.dirname(__file__), 'html/forum.html')
        self.response.out.write(render(path, {'DATA':DATA}))
Ejemplo n.º 6
0
    def getProfileDetails(self):
        userID = self.request.get('UserID')
        if userID in (None, ""):
            self.response.out.write(
                json.dumps({
                    "result": "error",
                    "message": "UserID not specified!"
                }))
            return

        if userID == "@me":
            curUser = UserService.getCurrentUserOrJsonError(self)
            if curUser is None:
                return
            self.response.out.write(
                json.dumps({
                    "result": "success",
                    "data": self._getProfileDetails(curUser)
                }))
            return

        c = GrafiteUser.all().filter("nickname =", userID)
        curUser = None
        if c.count():
            curUser = c.fetch(1)[0]
        else:
            try:
                curUser = GrafiteUser.get(db.Key(encoded=userID))
            except Exception, e:
                self.response.out.write(
                    json.dumps({
                        "result": "error",
                        "message": "No User!"
                    }))
                return
Ejemplo n.º 7
0
 def post(self):
     self.response.headers.add_header("Content-Type","application/json")
     if self.request.get("type") != "add":
         self.response.out.write(json.dumps({"result":"error","message":"Bad type"}))
         return
     user = UserService.getCurrentUserOrJsonError(self)
     if not user:
         return
     if self.request.get("text") in (None,""):
         self.response.out.write(json.dumps({"result":"error","message":"Bad text"}))
         return
     if self.request.get("time") in (None,""):
         self.response.out.write(json.dumps({"result":"error","message":"Bad Time"}))
         return
     text = self.request.get('text')
     time = self.request.get('time')
     try:
         [v,t] = time.split(' ')
         res = ReminderService.addReminder(v,t,text,user)
         if not res:
             self.response.out.write(json.dumps({"result":"error","message":"Bad Time Specification"}))
             return
     except:
         self.response.out.write(json.dumps({"result":"error","message":"Bad Time Specification format"}))
         return
     self.response.out.write(json.dumps({"result":"success"}))
Ejemplo n.º 8
0
    def get(self):
        class temp:
            pass

        DATA = temp()

        DATA.user = UserService.getCurrentUser(self)

        self.response.headers['Content-Type'] = "text/html"

        if self.request.get("t") in (None, ""):
            DATA.threads = Thread.all().order("-time").fetch(10)
            for thread in DATA.threads:
                thread.posts_expanded = map(Post.get_by_id, thread.posts)
        else:
            obj = Thread.get_by_id(int(self.request.get("t")))
            if obj is None:
                self.error(404)
                return
            DATA.threads = []
            for thread in DATA.threads:
                thread.posts_expanded = map(Post.get_by_id, thread.posts)

        path = os.path.join(os.path.dirname(__file__), 'html/sidebar.html')
        f = open(path, "r")
        DATA.sidebar = f.read()
        f.close()
        path = os.path.join(os.path.dirname(__file__), 'html/forum.html')
        self.response.out.write(render(path, {'DATA': DATA}))
Ejemplo n.º 9
0
 def post(self, job):
     user = UserService.getCurrentUserOrRedirect(self)
     if not user:
         return
     if job not in ['update', 'status']:
         self.error(404)
         return
     getattr(self, job)(user)
Ejemplo n.º 10
0
 def post(self,job):
     user = UserService.getCurrentUserOrRedirect(self)
     if not user:
         return
     if job not in ['status','update']:
         self.error(404)
         return
     getattr(self,job)(user)
Ejemplo n.º 11
0
 def post(self, job):
     user = UserService.getCurrentUserOrRedirect(self)
     if not user:
         return
     if job not in ["update", "status", "like", "comment"]:
         self.error(404)
         return
     getattr(self, job)(user)
Ejemplo n.º 12
0
 def get(self):
     at = GrafiteUserUnregistered.new()
     self.response.headers.add_header('Set-Cookie', UserService.makeCookieString(
     (datetime.now() + timedelta(minutes=10)).strftime(time_format),{"at":at}))
     self.response.out.write("")
     res = GrafiteUserUnregistered.all().filter("dateJoined <=", datetime.now() - timedelta(minutes=10))
     arr = res.fetch(res.count())
     db.delete(arr)
Ejemplo n.º 13
0
    def get(self):
	class temp:
	    pass
	DATA = temp()
	DATA.user = UserService.getCurrentUser(self)
	
	path = os.path.join(os.path.dirname(__file__), 'html/help/chatbot.html')
        self.response.out.write(render(path, {'DATA':DATA}))
Ejemplo n.º 14
0
 def get(self,job):
     user = UserService.getCurrentUserOrRedirect(self)
     if not user:
         return
     
     if job not in ['authenticate','authenticated','follow','unfollow','feed']:
         self.error(404)
         return
     getattr(self,job)(user)
Ejemplo n.º 15
0
def create_coach():
    if 'directorID' not in session:  #authentication - least authorized principle
        return redirect(url_for('login'))
    if request.method == "POST":
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']
        userService = UserService()
        if userService.checkEmail(email) is False:
            return render_template('registerCoach.html',
                                   error="Email is not valid")
        service = DirectorService()
        response = service.register_coach(username, password, email)
        if response == False:
            return render_template(
                'registerCoach.html',
                error="There was an error creating the profile")
        return redirect(url_for('director_home'))
    return render_template('registerCoach.html')
Ejemplo n.º 16
0
 def get(self, job):
     user = UserService.getCurrentUser(self)
     if not user and job in ['authenticate', 'authenticated']:
         UserService.getCurrentUserOrRedirect(self)
         return
     elif not user:
         self.response.out.write(
             json.dumps({
                 "result": "error",
                 "message": "unauthorised"
             }))
         return
     if job not in [
             'authenticate', 'authenticated', 'feed', 'comments',
             'birthdays', 'notifications', 'accessToken'
     ]:
         self.error(404)
         return
     getattr(self, job)(user)
Ejemplo n.º 17
0
    def get(self):
        class temp:
            pass

        DATA = temp()
        DATA.user = UserService.getCurrentUser(self)

        path = os.path.join(os.path.dirname(__file__),
                            'html/help/chatbot.html')
        self.response.out.write(render(path, {'DATA': DATA}))
Ejemplo n.º 18
0
    def post(self):
        user = UserService.getCurrentUserOrJsonError(self)
        if not user:
            return
        
        s = []
        if self.request.get("services"):
            s = self.request.get("services").split(",")

        self.response.headers.add_header("Content-Type","application/json")
        self.response.out.write(json.dumps(StatusService.updateStatus(self.request.get("status"),user,s,{})))
Ejemplo n.º 19
0
    def get(self, job):
        user = UserService.getCurrentUserOrRedirect(self)
        if not user:
            return

        if job not in [
                'authenticate', 'authenticated', 'follow', 'unfollow', 'feed'
        ]:
            self.error(404)
            return
        getattr(self, job)(user)
Ejemplo n.º 20
0
 def get(self, job):
     user = UserService.getCurrentUser(self)
     if not user and job in ["authenticate", "authenticated"]:
         UserService.getCurrentUserOrRedirect(self)
         return
     elif not user:
         self.response.out.write(json.dumps({"result": "error", "message": "unauthorised"}))
         return
     if job not in [
         "authenticate",
         "authenticated",
         "feed",
         "comments",
         "birthdays",
         "notifications",
         "accessToken",
     ]:
         self.error(404)
         return
     getattr(self, job)(user)
Ejemplo n.º 21
0
def artist_edit():
    if 'artistID' not in session:  #authentication - least authorized principle
        return redirect(url_for('login'))
    artistID = session['artistID']
    service = ArtistService()
    error = None
    if request.method == "POST":
        newUsername = request.form['username']
        newEmail = request.form['email']
        userService = UserService()
        if userService.checkEmail(newEmail) is False:
            error = "Not a valid email"
        else:
            response = service.update_details(newUsername, newEmail, artistID)
            if response is False:
                error = "Error editing data. Please contact the director"
    response = service.get_details(artistID)
    if response is None:
        return redirect(url_for('artist_home'))
    return render_template('artistDetails.html', data=response, error=error)
Ejemplo n.º 22
0
    def get(self):
	class temp:
	    pass
	DATA = temp()
	DATA.user = UserService.getCurrentUser(self)
	DATA.to = "/userHome"
	if self.request.get("to") not in (None,""):
	    DATA.to = self.request.get("to")

	path = os.path.join(os.path.dirname(__file__), 'html/login.html')
        self.response.out.write(render(path, {'DATA':DATA}))
Ejemplo n.º 23
0
    def get(self):
        class temp:
            pass

        DATA = temp()
        DATA.user = UserService.getCurrentUser(self)
        DATA.to = "/userHome"
        if self.request.get("to") not in (None, ""):
            DATA.to = self.request.get("to")

        path = os.path.join(os.path.dirname(__file__), 'html/login.html')
        self.response.out.write(render(path, {'DATA': DATA}))
Ejemplo n.º 24
0
 def renderSearchPage(self):
     class temp:
         pass
     
     DATA = temp()
     DATA.user = UserService.getCurrentUser(self)
     
     DATA.allUsers = GrafiteUser.all().fetch(300)
     DATA.allUsers = map(lambda x: UserProfilePage._getProfileDetails(x), DATA.allUsers)
     
     path = os.path.join(os.path.dirname(__file__), 'html/users.html')
     self.response.out.write(render(path, {'DATA':DATA}))
Ejemplo n.º 25
0
 def get(self):
     if self.request.get("password")=="thrustmaximum":
         ReminderService.executeReminders()
         return
     self.response.headers.add_header("Content-Type","application/json")
     user = UserService.getCurrentUserOrJsonError(self)
     if not user:
         return
     res = {}
     res['old'] = map(lambda x:{"text":x.text,"time":x.remindTime.isoformat()},RemindersOld.all().filter("user = "******"text":x.text,"time":x.remindTime.isoformat()},Reminder.all().filter("user = "******"result":"success","data":res}))
Ejemplo n.º 26
0
 def post(self):
     self.response.headers["Content-Type"] = "application/json"
     user = UserService.getCurrentUserOrJsonError(self)
     if not user:
         return
     msg = self.request.get("message")
     shouts = ShoutBoxMessages.getShouts()
     if msg in (None,""):
         self.response.out.write(json.dumps({"result":"error","message":"No body!"}))
         return
     res = ShoutBoxMessages.shout(msg,user)
     shouts.extend(map(lambda x: {"user":{"nickname":x.user.Nickname, "dp":x.user.displayPicture,"url":x.user.profileUrl}, "message":x.message, "time":x.time.isoformat()}, [res]))
     self.response.out.write(json.dumps({"result":"success","data":shouts}))
Ejemplo n.º 27
0
    def renderSearchPage(self):
        class temp:
            pass

        DATA = temp()
        DATA.user = UserService.getCurrentUser(self)

        DATA.allUsers = GrafiteUser.all().fetch(300)
        DATA.allUsers = map(lambda x: UserProfilePage._getProfileDetails(x),
                            DATA.allUsers)

        path = os.path.join(os.path.dirname(__file__), 'html/users.html')
        self.response.out.write(render(path, {'DATA': DATA}))
Ejemplo n.º 28
0
    def post_pinged(self,usr):
        res = GrafiteUser.all().filter("emailId =",usr.emailId)
        if res.count()!=1:
            return {"result":"error","message":"EmailId not found!"}
        
        user = res.fetch(1)[0]
        res1,at, expire = GrafiteUser.login(user.key().name(), user.password, "Web-browser")
        if res1!="success":
            return {"result":"error","message":"Unable to login"}

        self.response.headers.add_header('Set-Cookie',UserService.makeCookieString(
            expire.strftime(time_format),{"access_token":at}))
                
        return {"result":"success","value":res.count()==1}
Ejemplo n.º 29
0
    def get(self, job):
        if job not in [
                'authenticate', 'authenticated', 'follow', 'unfollow',
                'longtweet', 'feed'
        ]:
            self.error(404)
            return

        user = UserService.getCurrentUser(self)
        if not user:
            if job in ('follow', 'unfollow'):
                self.response.headers.add_header("Content-Type",
                                                 "application/json")
                self.response.out.write(
                    json.dumps({
                        "result": "error",
                        "message": "Unauthenticated User"
                    }))
                return
            UserService.getCurrentUserOrRedirect(self)
            return

        getattr(self, job)(user)
Ejemplo n.º 30
0
    def get(self):
        user = UserService.getCurrentUserOrRedirect(self)
        if not user:
            return
        if self.request.get("redirect"):
            self.response.headers.add_header('Set-Cookie',UserService.makeCookieString(
            user.getLoginExpirationTime().strftime(time_format),{"access_token":user.accessToken}))
            self.response.headers.add_header('Content Type',"text/Html")
            self.redirect(self.request.get("redirect"))
            self.error(302)
            return

        DATA = temp()
        DATA.user = user
        DATA.accessToken = user.accessToken
        DATA.lastAccessTime = user.dateLastAccessed
        try:
            DATA.settings = json.loads(user.settings)
        except Exception,err:
            obj = {"TwitterShortenURL":False,"TwitterSplitStatus":False}
            user.settings = json.dumps(obj)
            user.put()
            DATA.settings = obj
Ejemplo n.º 31
0
    def post(self):
        user = UserService.getCurrentUserOrJsonError(self)
        if not user:
            return

        s = []
        if self.request.get("services"):
            s = self.request.get("services").split(",")

        self.response.headers.add_header("Content-Type", "application/json")
        self.response.out.write(
            json.dumps(
                StatusService.updateStatus(self.request.get("status"), user, s,
                                           {})))
Ejemplo n.º 32
0
    def get(self):
	print ""
	user = UserService.getCurrentUserOrRedirect(self)
	#print str(user)
	if not user:
	    return

	if self.request.get("oauth_verifier") not in (None,""):
	    b = LinkedInStatusUpdater(user)
	    b.setCredentials(self.request.get("oauth_verifier"))
	    self.redirect('/userHome')
	    self.error(302)
	else:
	    b = LinkedInStatusUpdater(user)
	    self.response.out.write(b.requestAuthenticationURL())
Ejemplo n.º 33
0
def createUser():
  print('Insertar Dni:')
  dni = input().strip()

  print('Insertar Nombre:')
  name = input().strip().upper()

  print('Insertar Apellido Paterno:')
  patLastname = input().strip().upper()

  print('Insertar Apellido Materno:')
  matLastname = input().strip().upper()

  user = User(dni, name, patLastname, matLastname, None, None)
  userService = UserService()
  userService.insert(user)
  userService.commit()
  userService.close()
  return dni
Ejemplo n.º 34
0
    def userProfileView(self,userID):
        user = UserService.getCurrentUser(self)

        DATA = temp()
        if user:
            DATA.user = user
        
        c = GrafiteUser.all().filter("nickname =",userID)
        if c.count():
            DATA.profileUser = c.fetch(1)[0]
        else:
            try:
                DATA.profileUser = GrafiteUser.get(db.Key(encoded=userID))
                DATA.profileUser.gUserId = str(DATA.profileUser.key())
            except Exception, e:
                self.response.out.write("OOPS! no such profile exists! Whence did you come?")
                self.error(404)
                return
Ejemplo n.º 35
0
 def get(self):
     self.response.headers.add_header('Content-Type','application/json')
     res = dict(result="success")
     res['TotalUsers'] = GrafiteUser.all().count()
     user = GrafiteUser.all().order("-dateJoined").fetch(1)[0]
     res['LatestUserHTML'] = '<a href="%s">%s</a>'%(user.profileUrl,user.Nickname)
     obj = GrafiteUser.getOnlineUsers()
     res['OnlineUsersList'] = obj['value']
     res['OnlineUsersCount'] = obj['count']
     res['TotalStatuses'] = Status.getTotalStatuses()
     res['TotalReminders'] = ReminderService.getCount()
     
     user = UserService.getCurrentUser(self)
     if user:
         res['user'] = {}
         res['user']['Statuses'] = StatusService.getUserStatusCount(user)
         res['user']['Reminders'] = ReminderService.getUserCount(user)
     self.response.out.write(json.dumps(res))
Ejemplo n.º 36
0
    def userProfileView(self, userID):
        user = UserService.getCurrentUser(self)

        DATA = temp()
        if user:
            DATA.user = user

        c = GrafiteUser.all().filter("nickname =", userID)
        if c.count():
            DATA.profileUser = c.fetch(1)[0]
        else:
            try:
                DATA.profileUser = GrafiteUser.get(db.Key(encoded=userID))
                DATA.profileUser.gUserId = str(DATA.profileUser.key())
            except Exception, e:
                self.response.out.write(
                    "OOPS! no such profile exists! Whence did you come?")
                self.error(404)
                return
Ejemplo n.º 37
0
    def get(self, job):
        appid = self.request.get("appid")
        if appid in (None, ""):
            self.error(404)
            return
        if job not in ("register", ):
            self.error(404)
            return

        class temp:
            pass

        DATA = temp()
        #check user logged in.
        DATA.user = UserService.getCurrentUser(self)
        if not DATA.user:
            url = urllib.quote("/api/register?appid=%s" % appid)
            self.redirect("/login?to=" + url)
            self.error(302)
            return

        app = RegisteredApplications.get_by_key_name(appid)
        if app is None:
            self.response.out.write("Invalid application!")
            return

        res = PermanentAccessCodes.all().filter("user = "******"app =", app)

        if res.count():
            DATA.apiAccess = res.fetch(1)[0]
            DATA.apiAccess.passCode = str(uuid.uuid4())
        else:
            DATA.apiAccess = PermanentAccessCodes.new()
            DATA.apiAccess.user = DATA.user
            DATA.apiAccess.app = app
        DATA.apiAccess.put()
        path = os.path.join(os.path.dirname(__file__), 'html/appaccess.html')
        self.response.out.write(render(path, {'DATA': DATA}))
Ejemplo n.º 38
0
    def getProfileDetails(self):
        userID = self.request.get('UserID')
        if userID in (None,""):
            self.response.out.write(json.dumps({"result":"error","message":"UserID not specified!"}))
            return

        if userID == "@me":
            curUser = UserService.getCurrentUserOrJsonError(self)
            if curUser is None:
                return
            self.response.out.write(json.dumps({"result":"success", "data":self._getProfileDetails(curUser)}))
            return

        c = GrafiteUser.all().filter("nickname =",userID)
        curUser = None
        if c.count():
            curUser = c.fetch(1)[0]
        else:
            try:
                curUser = GrafiteUser.get(db.Key(encoded=userID))
            except Exception, e:
                self.response.out.write(json.dumps({"result":"error","message":"No User!"}))
                return
Ejemplo n.º 39
0
    def get(self,job):
        appid = self.request.get("appid")
        if appid in (None,""):
            self.error(404)
            return
        if job not in ("register",):
            self.error(404)
            return

        class temp:
            pass
        DATA = temp()
        #check user logged in.
        DATA.user = UserService.getCurrentUser(self)
        if not DATA.user:
            url = urllib.quote("/api/register?appid=%s"%appid)
            self.redirect("/login?to="+url)
            self.error(302)
            return
        
        app = RegisteredApplications.get_by_key_name(appid)
        if app is None:
            self.response.out.write("Invalid application!")
            return

        res = PermanentAccessCodes.all().filter("user = "******"app =",app)
        
        if res.count():
            DATA.apiAccess = res.fetch(1)[0]
            DATA.apiAccess.passCode = str(uuid.uuid4())
        else:
            DATA.apiAccess = PermanentAccessCodes.new()
            DATA.apiAccess.user = DATA.user
            DATA.apiAccess.app = app
        DATA.apiAccess.put()
        path = os.path.join(os.path.dirname(__file__), 'html/appaccess.html')
        self.response.out.write(render(path, {'DATA':DATA}))
Ejemplo n.º 40
0
 def work(self):
     print("***** Welcome to Aerospike Developer Training *****\n")
     print("INFO: Connecting to Aerospike cluster...")
     #  Establish connection to Aerospike server
     if not self.client:
         print(
             "\nERROR: Connection to Aerospike cluster failed! Please check the server settings and try again!"
         )
     else:
         print("\nINFO: Connection to Aerospike cluster succeeded!\n")
         #  Create instance of UserService
         us = UserService(self.client)
         #  Create instance of TweetService
         ts = TweetService(self.client)
         #  Present options
         print("\nWhat would you like to do:\n")
         print("1> Create A User And A Tweet\n")
         print("2> Read A User Record\n")
         print("3> Batch Read Tweets For A User\n")
         print("4> Scan All Tweets For All Users\n")
         print("5> Record UDF -- Update User Password\n")
         print(
             "6> Query Tweets By Username And Users By Tweet Count Range\n")
         print(
             "7> Stream UDF -- Aggregation Based on Tweet Count By Region\n"
         )
         print("0> Exit\n")
         print("\nSelect 0-7 and hit enter:\n")
         try:
             feature = int(raw_input('Input:'))
         except ValueError:
             print("Input a valid feature number")
             sys.exit(0)
         if feature != 0:
             if feature == 1:
                 print(
                     "\n********** Your Selection: Create User And A Tweet **********\n"
                 )
                 us.createUser()
                 ts.createTweet()
             elif feature == 2:
                 print(
                     "\n********** Your Selection: Read A User Record **********\n"
                 )
                 us.getUser()
             elif feature == 3:
                 print(
                     "\n********** Your Selection: Batch Read Tweets For A User **********\n"
                 )
                 us.batchGetUserTweets()
             elif feature == 4:
                 print(
                     "\n********** Your Selection: Scan All Tweets For All Users **********\n"
                 )
                 ts.scanAllTweetsForAllUsers()
             elif feature == 5:
                 print(
                     "\n********** Your Selection: Record UDF -- Update User Password **********\n"
                 )
                 us.updatePasswordUsingUDF()
             elif feature == 6:
                 print(
                     "\n********** Your Selection: Query Tweets By Username And Users By Tweet Count Range **********\n"
                 )
                 ts.queryTweetsByUsername()
                 ts.queryUsersByTweetCount()
             elif feature == 7:
                 print(
                     "\n********** Your Selection: Stream UDF -- Aggregation Based on Tweet Count By Region **********\n"
                 )
                 us.aggregateUsersByTweetCountByRegion()
             elif feature == 12:
                 print("\n********** Create Users **********\n")
                 us.createUsers()
             elif feature == 23:
                 print("\n********** Create Tweets **********\n")
                 ts.createTweets()
             else:
                 print("Enter a Valid number from above menue !!")
Ejemplo n.º 41
0
 def work(self):
     print("***** Welcome to Aerospike Developer Training *****\n")
     print("INFO: Connecting to Aerospike cluster...")
         #  Establish connection to Aerospike server
     if not self.client:
         print("\nERROR: Connection to Aerospike cluster failed! Please check the server settings and try again!")
     else:
           print("\nINFO: Connection to Aerospike cluster succeeded!\n")
           #  Create instance of UserService
           us = UserService(self.client)
           #  Create instance of TweetService
           ts = TweetService(self.client)
           #  Present options
           print("\nWhat would you like to do:\n")
           print("1> Create A User And A Tweet\n")
           print("2> Read A User Record\n")
           print("3> Batch Read Tweets For A User\n")
           print("4> Scan All Tweets For All Users\n")
           print("5> Record UDF -- Update User Password\n")
           print("6> Query Tweets By Username And Users By Tweet Count Range\n")
           print("7> Stream UDF -- Aggregation Based on Tweet Count By Region\n")
           print("0> Exit\n")
           print("\nSelect 0-7 and hit enter:\n")
           try:
             feature=int(raw_input('Input:'))
           except ValueError:
             print("Input a valid feature number")
             sys.exit(0)
           if feature != 0:
               if feature==1:
                   print("\n********** Your Selection: Create User And A Tweet **********\n")
                   us.createUser()
                   ts.createTweet()
               elif feature==2:
                   print("\n********** Your Selection: Read A User Record **********\n")
                   us.getUser()
               elif feature==3:
                   print("\n********** Your Selection: Batch Read Tweets For A User **********\n")
                   us.batchGetUserTweets()
               elif feature==4:
                   print("\n********** Your Selection: Scan All Tweets For All Users **********\n")
                   ts.scanAllTweetsForAllUsers()
               elif feature==5:
                   print("\n********** Your Selection: Record UDF -- Update User Password **********\n")
                   us.updatePasswordUsingUDF()
               elif feature==6:
                   print("\n********** Your Selection: Query Tweets By Username And Users By Tweet Count Range **********\n")
                   ts.queryTweetsByUsername()
                   ts.queryUsersByTweetCount()
               elif feature==7:
                   print("\n********** Your Selection: Stream UDF -- Aggregation Based on Tweet Count By Region **********\n")
                   us.aggregateUsersByTweetCountByRegion()
               elif feature==12:
                   print("\n********** Create Users **********\n")
                   us.createUsers()
               elif feature==23:
                   print("\n********** Create Tweets **********\n")
                   ts.createTweets()
               else:
                 print ("Enter a Valid number from above menue !!")
Ejemplo n.º 42
0
from UserService import UserService
from QuestionSerializer import QuestionSerializer

service = UserService(userName='******')
questionsData = service.getFavoriteQuestions()
questions = []
for questionData in questionsData:
    question = QuestionSerializer.crateQuestionFromDict(questionData)
    questions.append(question)
user = service.getUser()
user.setFavoriteQuestions(questions)
print(user.getTopTags().keys())
Ejemplo n.º 43
0
    def work(self):
        print("***** Welcome to Aerospike Developer Training *****\n")

        if self.client:
            print("\nINFO: Connection to Aerospike cluster succeeded!\n")
            #  Create instance of UserService
            us = UserService(self.client)
            #  Create instance of TweetService
            ts = TweetService(self.client)
            #  Present options
            print("\nWhat would you like to do:")
            print("1> Create A User")
            print("2> Create A Tweet By A User")
            print("3> Read A User Record")
            print("4> Batch Read Tweets For A User")
            print("5> Scan All Tweets For All Users")
            print("6> Update User Password using CAS")
            print("7> Update User Password using Record UDF")
            print("8> Query Tweets By Username")
            print("9> Query Users By Tweet Count Range")
            print(
                "10> Stream UDF -- Aggregation Based on Tweet Count By Region")
            print("11> Create A Test Set of Users")
            print("12> Create A Test Set of Tweets")
            print("0> Exit\n")
            print("\nSelect 0-12 and hit enter:\n")
            try:
                feature = int(input('Input:'))
            except ValueError:
                print("Input a valid feature number")
                sys.exit(0)
            if feature != 0:
                if feature == 1:
                    print(
                        "\n********** Your Selection: Create A User **********\n"
                    )
                    us.createUser()
                elif feature == 2:
                    print(
                        "\n********** Your Selection: Create A Tweet By A User **********\n"
                    )
                    ts.createTweet()
                elif feature == 3:
                    print(
                        "\n********** Your Selection: Read A User Record **********\n"
                    )
                    us.getUser()
                elif feature == 4:
                    print(
                        "\n********** Your Selection: Batch Read Tweets For A User **********\n"
                    )
                    us.batchGetUserTweets()
                elif feature == 5:
                    print(
                        "\n********** Your Selection: Scan All Tweets For All Users **********\n"
                    )
                    ts.scanAllTweetsForAllUsers()
                elif feature == 6:
                    print(
                        "\n********** Your Selection: Update User Password using CAS **********\n"
                    )
                    us.updatePasswordUsingCAS()
                elif feature == 7:
                    print(
                        "\n********** Your Selection: Update User Password using Record UDF **********\n"
                    )
                    us.updatePasswordUsingUDF()
                elif feature == 8:
                    print(
                        "\n********** Your Selection: Query Tweets By Username **********\n"
                    )
                    ts.queryTweetsByUsername()
                elif feature == 9:
                    print(
                        "\n********** Your Selection: Query Users By Tweet Count Range **********\n"
                    )
                    ts.queryUsersByTweetCount()
                elif feature == 10:
                    print(
                        "\n********** Your Selection: Stream UDF -- Aggregation Based on Tweet Count By Region **********\n"
                    )
                    us.aggregateUsersByTweetCountByRegion()
                elif feature == 11:
                    print(
                        "\n********** Create A Test Set of Users **********\n")
                    us.createUsers()
                elif feature == 12:
                    print(
                        "\n********** Create A Test Set of Tweets **********\n"
                    )
                    ts.createTweets()
                else:
                    print("Enter a Valid number from above menu !!")
            #Exercise K1
            self.client.close()
Ejemplo n.º 44
0
        sys.exit(4)

    # Get the required tags for the meta data from the config file
    required_tags = props.tag_config

    # Create meta data service
    meta_data_service = MetaDataService.MetaDataService(
        connection,
        archive_connection,
        props.database_config,
        props.archive_database_config)
    meta_data_service.set_console_logger(console_logger)
    meta_data_service.set_file_logger(file_logger)

    # Create user service
    user_service = UserService(connection, archive_connection, ms)
    user_service.set_console_logger(console_logger)
    user_service.set_file_logger(file_logger)

    # Get the elasticsearch config
    elastic_config = props.elasticsearch_config

    # Initialize the data indexer
    indexer = DataIndexer(elastic_config)
    indexer.set_console_logger(console_logger)
    indexer.set_file_logger(file_logger)

    # Initialize permission service
    permission_service = PermissionService(archive_conf, SDE_ARCHIVE_DB)

    if elastic_config["activated"]:
Ejemplo n.º 45
0
from flask import Response
from waitress import serve

DB_WORDS_PATH = 'sqlite:///../db/words.db'
DB_WORDSEN_PATH = 'sqlite:///../db/wordsen.db'
DB_USERS_PATH = 'sqlite:///../db/user.db'

app = Flask(__name__)

wordsDatabase = Database(DB_WORDS_PATH)
wordsenDatabase = Database(DB_WORDSEN_PATH)
userDatabase = Database(DB_USERS_PATH)

dictionaryService = DictionaryService(wordsDatabase)
dictionaryServiceen = DictionaryServiceen(wordsenDatabase)
userService = UserService(userDatabase)
verificationService = VerificationService(userDatabase)

SECRET_KEY = b'\xffJ/,"\xa3\x85]\x19\x94\'\xed\xd6\x07\x1a\x96'
ENVIRONMENT_DEV = "dev"
ENVIRONMENT_PROD = "prod"


def map_boolean(value):
    if value is True or value == 'True' or value == 'true' or value == 1:
        return True
    return False


def create_response(code, data={}):
    response_string = json.dumps(data)
Ejemplo n.º 46
0
from UserService import UserService, Authentication
from VerificationService import VerificationService
from Database import Database

import spacy
import DefinitionService

DB_USERS_PATH = 'sqlite:///../db/user.db'
DB_WORDS_PATH = 'sqlite:///../db/wordsen.db'

userDatabase = Database(DB_USERS_PATH)
wordsDatabase = Database(DB_WORDS_PATH)

dictionaryService = DictionaryService(wordsDatabase)
verificationService = VerificationServiceen(userDatabase)
userService = UserService(userDatabase)

user = userService.get_user('*****@*****.**')
print(user.json())

#text = '!@#$%^&*()_Die Metall- und Elektroindustrie schrumpft, statt 32.000 Menschen leben nur noch 17.000 Einwohner dort.'
#text = 'Wir haben in den vergangenen Tagen bereits häufiger über ihn berichtet, jetzt ist es Gewissheit: Nach 37 Jahren ist die Regierungszeit von Diktator Robert Mugabe in Simbabwe zu Ende, die Details dazu hat die Süddeutsche Zeitung. Der 93-Jährige hatte zuletzt vergeblich versucht, seine Frau Grace ins Präsidentschaftsamt zu heben, nun soll stattdessen der Anfang November von Mugabe gefeuerte Emmerson Mnangagwa übernehmen. Der Schweizer SRF porträtiert diesen Nachfolger, den reichsten Mann des Landes, der von vielen „Krokodil“ genannt wird. Ob er wirkliche Veränderung bringt, ist völlig offen. Eine Analyse von Mugabes Amtszeit hat die Deutsche Welle.'
#text = 'Asylum-seekers in eastern Germany are 10 times more likely to be hate crime victims as those who live in the west, a study published on Sunday found.'
#text = 'a Sunday'
text = 'Am Sonntag werde ich ausschlafen.'

#response = DefinitionService.findDef('love','noun')
#print(response)

#response = DefinitionService.findDef('this','adv')
#print(response)
Ejemplo n.º 47
0
def authUser():
    data = request.get_data()
    res = UserService(configReader).authUser(data)
    return json.dumps({'isAuthorized}': res}), 200, {
        'ContentType': 'application/json'
    }
Ejemplo n.º 48
0
def deleteUser():
    data = request.get_data()
    res = UserService(configReader).deleteUser(data)
    return json.dumps(res), 200, {'ContentType': 'application/json'}
Ejemplo n.º 49
0
    def post(self):
        user = UserService.getCurrentUserOrRedirect(self)
        if not user:
            return
        typ = self.request.get("type")
        if typ == "CreateThreadPost":
            self.response.headers.add_header("Content-Type","application/json")
            text = self.request.get("text")
            
            p = Post(user=user.key(), comment=text) 
            tp = Thread(user=user.key(),posts=[p.put().id()], totalPosts = 1)
            p.threadId = tp.put()
            p.put()

            path = os.path.join(os.path.dirname(__file__), 'html/forum/CreateNewPost.html')
            html = render(path, {'post':p})

            self.response.out.write(json.dumps({"result":"success",
                "html":html,
                "divId":"divThread_%d"%long(tp.key().id())}))

        elif typ == "ReplyPost":
            self.response.headers.add_header("Content-Type","application/json")
            text = self.request.get("text")
            threadId = long(self.request.get("threadId"))
            thread = Thread.get_by_id(threadId)
            
            p = Post(user=user, comment=text, threadId = thread)
            
            thread.posts.append(p.put().id())
            thread.totalPosts = thread.totalPosts + 1
            thread.put()

            path = os.path.join(os.path.dirname(__file__), 'html/forum/NewReply.html')
            html = render(path, {'post':p})

            self.response.out.write(json.dumps({
            "result":"success",
            "html":html,
            "divId":"rowComment_%d"%long(p.key().id())}))

        elif typ == "DeletePost":
            self.response.headers.add_header("Content-Type","application/json")
            if self.request.get("postId") in (None,""):
                self.response.out.write(json.dumps({"result":"error","message":"Invalid Parameters"}))
                return
            postId = long(self.request.get("postId"))
            post,thread = None,None
            try:
                post = Post.get_by_id(postId)
                thread = post.threadId
                if post.key().id() not in thread.posts:
                    raise Exception("")
            except Exception,e:
                self.response.out.write(json.dumps({"result":"error","message":"Thread or post Id is invalid"}))
                return
            pos = thread.posts.index(post.key().id())
            res = {"result":"success"}
            if not pos:
                res['toDelete'] = "divThread_%d"%long(thread.key().id())
                res['deleteType'] = 'Thread'
                #delete the entire thread!
                for everyPost in map(Post.get_by_id, thread.posts):
                    everyPost.delete()
                thread.delete()
            else:
                res['toDelete'] = "rowComment_%d"%long(post.key().id())
                res['deleteType'] = 'Comment'
                del thread.posts[pos]
                thread.put()
                post.delete()
            self.response.out.write(json.dumps(res))
Ejemplo n.º 50
0
    def work(self):
        print("***** Welcome to Aerospike Developer Training *****\n")
        print("INFO: Connecting to Aerospike cluster...")
            #  Establish connection to Aerospike server
        if not self.client:
            print("\nERROR: Connection to Aerospike cluster failed! Please check the server settings and try again!")
            self.readLine()
        else:
              print("\nINFO: Connection to Aerospike cluster succeeded!\n")
              #  Create instance of UserService
              us = UserService(self.client)
              #  Create instance of RoleService
              rs = RoleService(self.client)
              #  Present options
              print("\nWhat would you like to do:\n")
              print("1> Create User\n")
              print("2> Read User\n")
              print("3> Grant Role to User\n")
              print("4> Revoke Role from User\n")
              print("5> Drop User\n")
              print("6> Create Role\n")
              print("7> Read Role\n")
              print("8> Grant Privilege to Role\n")
              print("9> Revoke Privilege from Role\n")
              print("10> Drop Role\n")
              print("0> Exit\n")
              print("\nSelect 0-10 and hit enter:\n")

              try:
                feature=int(raw_input('Input:'))
              except ValueError:
                print("Input a valid feature number")
                sys.exit(0)
              if feature != 0:
                  if feature==1:
                      print("\n********** Your Selection: Create User **********\n")
                      us.create_user()
                  elif feature==2:
                      print("\n********** Your Selection: Read User **********\n")
                      us.get_user()
                  elif feature==3:
                      print("\n********** Your Selection: Grant Role to User **********\n")
                      us.grant_role()
                  elif feature==4:
                      print("\n********** Your Selection: Revoke Role from User **********\n")
                      us.revoke_role()
                  elif feature==5:
                      print("\n********** Your Selection: Drop User **********\n")
                      us.drop_user()
                  elif feature==6:
                      print("\n********** Your Selection: Create Role **********\n")
                      rs.create_role()
                  elif feature==7:
                      print("\n********** Your Selection: Read Role **********\n")
                      rs.read_role()
                  elif feature==8:
                      print("\n********** Your Selection: Grant Privilege to Role **********\n")
                      rs.grant_privilege()
                  elif feature==9:
                      print("\n********** Your Selection: Revoke Privilege from Role **********\n")
                      rs.revoke_privilege()
                  elif feature==10:
                      print("\n********** Your Selection: Drop Role **********\n")
                      rs.drop_role()
                  else:
                    print ("Enter a Valid number from above menue !!")