im1.paste(house,(orighousec1,orighousec2)) return im1 myjson={'Fname':'Dummy','Lname':'Dummy','Username':'******'} obj=RetrieveIntermediary(myjson) result=obj.retrieveIntermediaryInDB() intermediaries_tuple=json.loads(result) intermediaries_emails=[] orig_emails=[] beneficiary_ids=[] posn=0 gardens=[] competitors_counter=0 try: for record in intermediaries_tuple.items(): key,user =record if(user["D2"]=="None"):
d2 = c2 + 1 im2x = im2x + 1 #for each foreground in the xaxis except Exception as e: print "Exception was thrown in function plantTrees: %s" % e im1.paste(house, (orighousec1, orighousec2)) return im1 myjson = {'Fname': 'Dummy', 'Lname': 'Dummy', 'Username': '******'} obj = RetrieveIntermediary(myjson) result = obj.retrieveIntermediaryInDB() intermediaries_tuple = json.loads(result) intermediaries_emails = [] orig_emails = [] beneficiary_ids = [] posn = 0 gardens = [] competitors_counter = 0 try: for record in intermediaries_tuple.items(): key, user = record if (user["D2"] == "None"):
def twoWeeksSteps(self): result = {} try: day = self.myjson["Day"] except Exception as e: #print "Content-type: text/html\n" result["message"] = "Error%s" % e.message return (json.JSONEncoder().encode(result)) if day is not None: #if day=="Today": # today_date=datetime.date.today() # date_str="%s"%today_date #else: date_str = "%s" % day else: result["message"] = "Error: The option '%s' is invalid" % day return (json.JSONEncoder().encode(result)) myjson = {'Fname': 'Dummy', 'Lname': 'Dummy', 'Username': '******'} obj = RetrieveIntermediary(myjson) res = obj.retrieveIntermediaryInDB() intermediaries_tuple = json.loads(res) intermediaries_emails = [] intermediary_names = [] orig_emails = [] beneficiary_ids = [] beneficiary_names = [] beneficiary_relations = [ ] # The relationships between intermediaries and beneficiaries. beneficiary_genders = [] posn = 0 gardens = [] competitors_counter = 0 garden_label = date_str.replace("-", "_") first_posn = 0 second_posn = 0 key2 = "D" tree_array = [] flower_array = [] total_plants = [] urls = [] usage_points = [] bonus_points_start = [] bonus_points_end = [] badges = [] badges_urls = [] intermediary_mobiles = [] for record in intermediaries_tuple.items(): key, user = record if (user["D2"] == "None"): continue else: orig_emails.append(user["D1"]) #keep original email addresses orig_email = user["D1"] user["D1"] = user["D1"].replace("@", "_at_") user["D1"] = user["D1"].replace(".", "_dot_") intermediaries_emails.append(user["D1"]) intermediary_names.append(user["D0"]) beneficiary_names.append( user["D2"][0:user["D2"].index('.')]) # get the name only beneficiary_relations.append( user["D3"][(user["D3"].index(':') + 1):(len(user["D3"]))]) beneficiary_genders.append(user["D4"][(user["D4"].index(':') + 1):(len(user["D4"]))]) intermediary_mobiles.append(user["D5"][(user["D5"].index(':') + 1):(len(user["D5"]))]) myjson = { 'Fname': 'Dummy', 'Lname': 'Dummy', 'Username': orig_email } obj = RetrieveIntermediary(myjson) result2 = obj.isAssignedBeneficiary() beneficiary_tuple = json.loads(result2) beneficiary_ids.append(beneficiary_tuple["Id"]) file_path = "django_facebook/images/garden/%s/%s_%s.jpeg" % ( intermediaries_emails[posn], beneficiary_ids[posn], garden_label) file_name = "%s_%s" % (beneficiary_ids[posn], garden_label) urls.append(file_path) varmyjson = {'Day': day} stepsPointsObj = RetrievePoints(varmyjson, orig_email, 1) ressteps = stepsPointsObj.getSteps(beneficiary_tuple["Id"]) ressteps = json.loads(ressteps) #stepspoints=int(ressteps["steps"]/(100*ressteps["dates_counter"])) stepspoints_last_week = int(ressteps["steps1"]) stepspoints_last_last_week = int(ressteps["steps2"]) #append an array of total steps for each each week for the last two weeks. bonus_points_start.append(stepspoints_last_week) bonus_points_end.append(stepspoints_last_last_week) posn = posn + 1 posn = 0 for beneficiary in beneficiary_ids: urls_tuple = {} if first_posn < 10: key1 = "R0" else: key1 = "R" urls_tuple[key2 + "%s" % second_posn] = "%s" % intermediary_names[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % beneficiary_names[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % bonus_points_start[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % bonus_points_end[posn] second_posn = second_posn + 1 #urls_tuple[key2+"%s"%second_posn]="%s"%badges[posn] #second_posn=second_posn+1 urls_tuple[key2 + "%s" % second_posn] = "%s" % beneficiary_relations[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % beneficiary_genders[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % intermediary_mobiles[posn] second_posn = second_posn + 1 second_posn = 0 result[key1 + "%s" % first_posn] = (OrderedDict( sorted(urls_tuple.items(), key=lambda t: t[0]))) first_posn = first_posn + 1 posn = posn + 1 return (json.JSONEncoder().encode( OrderedDict(sorted(result.items(), key=lambda t: t[0]))))
def retrieveScoreGardensUrls(self): result={} try: day=self.myjson["Day"] except Exception as e: #print "Content-type: text/html\n" result["message"]="Error%s"%e.message return (json.JSONEncoder().encode(result)) if day is not None: #if day=="Today": # today_date=datetime.date.today() # date_str="%s"%today_date #else: date_str="%s"%day else: result["message"]="Error: The option '%s' is invalid"%day return (json.JSONEncoder().encode(result)) myjson={'Fname':'Dummy','Lname':'Dummy','Username':'******'} obj=RetrieveIntermediary(myjson) res=obj.retrieveIntermediaryInDB() intermediaries_tuple=json.loads(res) intermediaries_emails=[] intermediary_names=[] orig_emails=[] beneficiary_ids=[] beneficiary_names=[] intermediary_mobiles=[] posn=0 gardens=[] competitors_counter=0 garden_label=date_str.replace("-","_") first_posn=0 second_posn=0 key2="D" tree_array=[] flower_array=[] total_plants=[] urls=[] usage_points=[] bonus_points=[] badges=[] badge_posn=[] for record in intermediaries_tuple.items(): key,user =record if(user["D2"]=="None"): continue else: orig_emails.append(user["D1"]) #keep original email addresses orig_email=user["D1"] user["D1"]=user["D1"].replace("@","_at_") user["D1"]=user["D1"].replace(".","_dot_") intermediaries_emails.append(user["D1"]) intermediary_names.append(user["D0"]) beneficiary_names.append(user["D2"][0:user["D2"].index('.')])# get the name only myjson={'Fname':'Dummy','Lname':'Dummy','Username':orig_email} obj=RetrieveIntermediary(myjson) result2=obj.isAssignedBeneficiary() beneficiary_tuple=json.loads(result2) beneficiary_ids.append(beneficiary_tuple["Id"]) intermediary_mobiles.append(user["D5"][(user["D5"].index(':')+1):(len(user["D5"]))]) file_path="django_facebook/images/garden/%s/%s_%s.jpeg"%(intermediaries_emails[posn],beneficiary_ids[posn],garden_label) file_name="%s_%s"%(beneficiary_ids[posn],garden_label) urls.append(file_path) varmyjson={'Day':day} clickPointsObj=RetrievePoints(varmyjson,orig_email,1) resclickpoints=clickPointsObj.retrieveIntermediaryClickPoints() resclickpoints=json.loads(resclickpoints) #clickpoints=int(resclickpoints["points"]/resclickpoints["dates_counter"]) clickpoints=int(resclickpoints["points"]) if clickpoints>18: clickpoints=18 usage_points.append(clickpoints) ressteps=clickPointsObj.getSteps(beneficiary_tuple["Id"]) ressteps=json.loads(ressteps) #stepspoints=int(ressteps["steps"]/(100*ressteps["dates_counter"])) stepspoints=int(ressteps["steps"]) if stepspoints>70000: stepspoints=70000 bonus_points.append(stepspoints) trees=int(stepspoints*100/70000) flowers=int(clickpoints*67/18) #print file_name,trees, flowers tree_array.append(trees) flower_array.append(flowers) total=trees+flowers total_plants.append(total) #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) engine=db # create a Session Session = sessionmaker(bind=engine) session = Session() res2=session.query(AttainedUserBadges,Badges).filter(AttainedUserBadges.intermediary_id==orig_email).filter(AttainedUserBadges.status==1).filter(AttainedUserBadges.badge_id==Badges.rank).first() if res2 is None: sys.exit()# exit and wait until the user has atleast been assigned some badge else: print res2.Badges.badgename badges.append(res2.Badges.badgename) badge_posn.append(res2.Badges.rank) ''' if stepspoints>=70000: if clickpoints>=18: badges.append("Queen") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/queen.jpeg") else: badges.append("No promotion") elif stepspoints>=63000: if clickpoints>=16: badges.append("Princess") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/princess.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/duchess.jpeg") elif stepspoints>=56000: if clickpoints>=14: badges.append("Duchess") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/duchess.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/grandmaster.jpeg") elif stepspoints>=49000: if clickpoints>=12: badges.append("Grand Master") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/grandmaster.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniormaster.jpeg") elif stepspoints>=42000: if clickpoints>=10: badges.append("Senior Master") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniormaster.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/master.jpeg") elif stepspoints>=31500: if clickpoints>=8: badges.append("Master") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/master.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/juniormaster.jpeg") if stepspoints>=21000: if clickpoints>=4: badges.append("Junior Master") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/juniormaster.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniorservant.jpeg") elif stepspoints>=14000: if clickpoints>=2: badges.append("Senior Servant") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniorservant.jpeg") else: badges.append("No Promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/servant.jpeg") elif stepspoints>=7000: if clickpoints>=1: badges.append("Servant") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/servant.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/slave.jpeg") else: badges.append("Slave") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/slave.jpeg") ''' posn=posn+1 posn=0 #sort in descending order bubblesort(badge_posn,urls,beneficiary_ids,tree_array,flower_array,intermediary_names,beneficiary_names,usage_points,bonus_points,badges,total_plants) #print badges posn=0 file_path_alt="django_facebook/images/garden/blank.jpg" for beneficiary in beneficiary_ids: urls_tuple={} if first_posn<10: key1="R0" else: key1="R" urls_tuple[key2+"%s"%second_posn]="(%s, %s)"%(intermediary_names[posn],beneficiary_names[posn]) second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]=urls[posn] if total_plants[posn]==0: urls_tuple[key2+"%s"%second_posn]=file_path_alt second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%tree_array[posn] second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%flower_array[posn] second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%total_plants[posn] second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%usage_points[posn] second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%bonus_points[posn] second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%badges[posn] second_posn=second_posn+1 #urls_tuple[key2+"%s"%second_posn]="%s"%badges_urls[posn] #second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%intermediary_mobiles[posn] second_posn=second_posn+1 second_posn=0 result[key1+"%s"%first_posn]=(OrderedDict(sorted(urls_tuple.items(), key=lambda t: t[0]))) first_posn=first_posn+1 posn=posn+1 return (json.JSONEncoder().encode(OrderedDict(sorted(result.items(), key=lambda t: t[0]))))
def retrieveScoreGardensUrls(self): result = {} try: day = self.myjson["Day"] except Exception as e: # print "Content-type: text/html\n" result["message"] = "Error%s" % e.message return json.JSONEncoder().encode(result) if day is not None: if day == "Today": today_date = datetime.date.today() date_str = "%s" % today_date else: date_str = "%s" % day else: result["message"] = "Error: The option '%s' is invalid" % day return json.JSONEncoder().encode(result) myjson = {"Fname": "Dummy", "Lname": "Dummy", "Username": "******"} obj = RetrieveIntermediary(myjson) res = obj.retrieveIntermediaryInDB() intermediaries_tuple = json.loads(res) intermediaries_emails = [] intermediary_names = [] orig_emails = [] beneficiary_ids = [] beneficiary_names = [] posn = 0 gardens = [] competitors_counter = 0 garden_label = date_str.replace("-", "_") first_posn = 0 second_posn = 0 key2 = "D" tree_array = [] flower_array = [] total_plants = [] urls = [] usage_points = [] bonus_points = [] badges = [] badges_urls = [] for record in intermediaries_tuple.items(): key, user = record if user["D2"] == "None": continue else: orig_emails.append(user["D1"]) # keep original email addresses orig_email = user["D1"] user["D1"] = user["D1"].replace("@", "_at_") user["D1"] = user["D1"].replace(".", "_dot_") intermediaries_emails.append(user["D1"]) intermediary_names.append(user["D0"]) beneficiary_names.append(user["D2"][0 : user["D2"].index(".")]) # get the name only myjson = {"Fname": "Dummy", "Lname": "Dummy", "Username": orig_email} obj = RetrieveIntermediary(myjson) result2 = obj.isAssignedBeneficiary() beneficiary_tuple = json.loads(result2) beneficiary_ids.append(beneficiary_tuple["Id"]) file_path = "django_facebook/images/garden/%s/%s_%s.jpeg" % ( intermediaries_emails[posn], beneficiary_ids[posn], garden_label, ) file_name = "%s_%s" % (beneficiary_ids[posn], garden_label) urls.append(file_path) varmyjson = {"Day": day} clickPointsObj = RetrievePoints(varmyjson, orig_email, 1) resclickpoints = clickPointsObj.retrieveIntermediaryClickPoints() resclickpoints = json.loads(resclickpoints) clickpoints = int(resclickpoints["points"] / resclickpoints["dates_counter"]) if clickpoints > 60: clickpoints = 60 usage_points.append(clickpoints) ressteps = clickPointsObj.getSteps(beneficiary_tuple["Id"]) ressteps = json.loads(ressteps) stepspoints = int(ressteps["steps"] / (100 * ressteps["dates_counter"])) if stepspoints > 100: stepspoints = 100 bonus_points.append(stepspoints) trees = int(stepspoints * 100.0 / 100) flowers = int(clickpoints * 67.0 / 60) # print file_name,trees, flowers tree_array.append(trees) flower_array.append(flowers) total = trees + flowers total_plants.append(total) if stepspoints >= 100: if clickpoints >= 6: badges.append("Queen") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/queen.jpeg" ) else: badges.append("Princess") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/princess.jpeg" ) elif stepspoints >= 90: if clickpoints >= 12: badges.append("Princess") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/princess.jpeg" ) else: badges.append("Duchess") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/duchess.jpeg" ) elif stepspoints >= 80: if clickpoints >= 18: badges.append("Duchess") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/duchess.jpeg" ) else: badges.append("Grand Master") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/grandmaster.jpeg" ) elif stepspoints >= 70: if clickpoints >= 24: badges.append("Grand Master") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/grandmaster.jpeg" ) else: badges.append("Senior Master") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniormaster.jpeg" ) elif stepspoints >= 60: if clickpoints >= 30: badges.append("Senior Master") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniormaster.jpeg" ) else: badges.append("Master") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/master.jpeg" ) elif stepspoints >= 45: if clickpoints >= 36: badges.append("Master") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/master.jpeg" ) else: badges.append("Junior Master") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/juniormaster.jpeg" ) if stepspoints >= 30: if clickpoints >= 42: badges.append("Junior Master") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/juniormaster.jpeg" ) else: badges.append("Senior Servant") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniorservant.jpeg" ) elif stepspoints >= 20: if clickpoints >= 48: badges.append("Senior Servant") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniorservant.jpeg" ) else: badges.append("Servant") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/servant.jpeg" ) if stepspoints >= 10: if clickpoints >= 54: badges.append("Servant") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/servant.jpeg" ) else: badges.append("Slave") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/slave.jpeg" ) else: badges.append("Slave") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/slave.jpeg") posn = posn + 1 posn = 0 bubblesort( total_plants, urls, beneficiary_ids, tree_array, flower_array, intermediary_names, beneficiary_names, usage_points, bonus_points, badges, badges_urls, ) posn = 0 file_path_alt = "django_facebook/images/garden/blank.jpg" for beneficiary in beneficiary_ids: urls_tuple = {} if first_posn < 10: key1 = "R0" else: key1 = "R" urls_tuple[key2 + "%s" % second_posn] = "(%s, %s)" % (intermediary_names[posn], beneficiary_names[posn]) second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = urls[posn] if total_plants[posn] == 0: urls_tuple[key2 + "%s" % second_posn] = file_path_alt second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % tree_array[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % flower_array[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % total_plants[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % usage_points[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % bonus_points[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % badges[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % badges_urls[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % beneficiary second_posn = second_posn + 1 second_posn = 0 result[key1 + "%s" % first_posn] = OrderedDict(sorted(urls_tuple.items(), key=lambda t: t[0])) first_posn = first_posn + 1 posn = posn + 1 return json.JSONEncoder().encode(OrderedDict(sorted(result.items(), key=lambda t: t[0])))
def retrieveScoreGardensUrls(self): result = {} try: day = self.myjson["Day"] except Exception as e: #print "Content-type: text/html\n" result["message"] = "Error%s" % e.message return (json.JSONEncoder().encode(result)) if day is not None: if day == "Today": today_date = datetime.date.today() date_str = "%s" % today_date else: date_str = "%s" % day else: result["message"] = "Error: The option '%s' is invalid" % day return (json.JSONEncoder().encode(result)) myjson = {'Fname': 'Dummy', 'Lname': 'Dummy', 'Username': '******'} obj = RetrieveIntermediary(myjson) res = obj.retrieveIntermediaryInDB() intermediaries_tuple = json.loads(res) intermediaries_emails = [] intermediary_names = [] orig_emails = [] beneficiary_id = 0 beneficiary_names = [] posn = 0 gardens = [] competitors_counter = 0 garden_label = date_str.replace("-", "_") first_posn = 0 second_posn = 0 key2 = "D" trees = 0 flowers = 0 fishnum = 0 fish_size = 0.0 total_plants = "" url = "" usage_points = "" bonus_points = "" badge = "" badge_url = "" team_members = "" team_name = "" team_features = [] for record in intermediaries_tuple.items(): key, user = record if (user["D2"] == "None"): continue else: orig_emails.append(user["D1"]) #keep original email addresses orig_email = user["D1"] user["D1"] = user["D1"].replace("@", "_at_") user["D1"] = user["D1"].replace(".", "_dot_") intermediaries_emails.append(user["D1"]) intermediary_names.append(user["D0"]) beneficiary_names.append( user["D2"][0:user["D2"].index('.')]) # get the name only myjson = { 'Fname': 'Dummy', 'Lname': 'Dummy', 'Username': orig_email } obj = RetrieveIntermediary(myjson) result2 = obj.isAssignedBeneficiary() beneficiary_tuple = json.loads(result2) team_identifier = "%s_%s" % (beneficiary_tuple["Id"], garden_label) beneficiary_id = team_identifier #Beneficiary file_path = "django_facebook/images/garden/%s/%s_%s.jpeg" % ( intermediaries_emails[posn], beneficiary_tuple["Id"], garden_label) file_name = "%s_%s" % (beneficiary_ids[posn], garden_label) url = file_path # url team_name = beneficiary_tuple["TeamName"] # Team Name one_team_members = "(%s, %s)" % ( intermediary_names[posn], beneficiary_names[posn] ) # put together team members team_members = one_team_members #Team Members varmyjson = {'Day': day} clickPointsObj = RetrievePoints(varmyjson, orig_email, 1) resclickpoints = clickPointsObj.retrieveIntermediaryClickPoints( ) resclickpoints = json.loads(resclickpoints) clickpoints = int(resclickpoints["points"]) clickpoints = clickpoints * 1000 usage_points = clickpoints #Usage Points ressteps = clickPointsObj.getSteps(beneficiary_tuple["Id"]) ressteps = json.loads(ressteps) stepspoints = int(ressteps["steps"] / ressteps["dates_counter"]) bonus_points = stepspoints #Bonus points resbadge = self.retrieveIndividualBadge() resbadge = json.loads(resbadge) #get badge name for this individual badge = resbadge["R00"]["D3"] #Badge #get a badge url for this person badge_url = resbadge["R00"]["D1"] #Badge URL trees = int( 10 * (11 - resbadge["R00"]["D4"])) # the number of trees in a garden fishnum = int( 11 - resbadge["R00"]["D4"]) # the number of fish in a tank fishsize = float( float(fish) / float(10) ) # fish size is determined by how many fish are in the tank. The more fish the bigger the size. This weill also be used to detrmine the quality of a fish tank resmealcounter = self.countRecordedMeals( beneficiary_tuple["Id"]) resmealcounter = json.loads(resmealcounter) flowers = (10 * resmealcounter["NumberOfMeals"] ) # number of flowers in the garden #print file_name,trees, flowers total = trees + flowers total_plants = total one_team_features = TeamFeatures(team_name, team_members, url, trees, flowers, total_plants, usage_points, bonus_points, badge, badge_url, beneficiary_id, fishnum, fishsize) team_features.append(one_team_features) posn = posn + 1 posn = 0 #bubblesort(total_plants,team_name,team_members,urls,beneficiary_ids,tree_array,flower_array,usage_points,bonus_points,badges,badges_urls,fish_array,fish_size_array) bubblesort(team_features) posn = 0 file_path_alt = "django_facebook/images/garden/blank.jpg" for one_team in team_features: urls_tuple = {} if first_posn < 10: key1 = "R0" else: key1 = "R" urls_tuple[key2 + "%s" % second_posn] = "%s" % one_team.team_name # D0 team name second_posn = second_posn + 1 urls_tuple[ key2 + "%s" % second_posn] = "%s" % one_team.team_members # D1 team members second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = one_team.url #D2 url for garden if total_plants[posn] == 0: urls_tuple[key2 + "%s" % second_posn] = file_path_alt second_posn = second_posn + 1 urls_tuple[ key2 + "%s" % second_posn] = "%s" % one_team.trees #D3 Number of trees second_posn = second_posn + 1 urls_tuple[ key2 + "%s" % second_posn] = "%s" % one_team.flowers # D4 Number of flowers second_posn = second_posn + 1 urls_tuple[ key2 + "%s" % second_posn] = "%s" % one_team.total_plants #D5 Total number of plants including flowers and tree second_posn = second_posn + 1 urls_tuple[ key2 + "%s" % second_posn] = "%s" % one_team.usage_points #D6 Number of days an application has been used multiply by 1000 by a team. second_posn = second_posn + 1 urls_tuple[ key2 + "%s" % second_posn] = "%s" % one_team.bonus_points #D7 average steps walked by an individual second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % one_team.badge #D8 Badge name second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % one_team.badge_url #D9 Badge Url second_posn = second_posn + 1 urls_tuple[ key2 + "%s" % second_posn] = "%s" % one_team.beneficiary_id #D10 Beneficiary ID second_posn = second_posn + 1 urls_tuple[ key2 + "%s" % second_posn] = "%s" % one_team.fishnum # D11 Number of fish in the tank. second_posn = second_posn + 1 urls_tuple[ key2 + "%s" % second_posn] = "%s" % one_team.fishsize #D12 size of fish in the tank second_posn = second_posn + 1 second_posn = 0 result[key1 + "%s" % first_posn] = (OrderedDict( sorted(urls_tuple.items(), key=lambda t: t[0]))) first_posn = first_posn + 1 posn = posn + 1 return (json.JSONEncoder().encode( OrderedDict(sorted(result.items(), key=lambda t: t[0]))))
def retrieveScoreGardensUrls(self): result = {} try: day = self.myjson["Day"] except Exception as e: #print "Content-type: text/html\n" result["message"] = "Error%s" % e.message return (json.JSONEncoder().encode(result)) if day is not None: #if day=="Today": # today_date=datetime.date.today() # date_str="%s"%today_date #else: date_str = "%s" % day else: result["message"] = "Error: The option '%s' is invalid" % day return (json.JSONEncoder().encode(result)) myjson = {'Fname': 'Dummy', 'Lname': 'Dummy', 'Username': '******'} obj = RetrieveIntermediary(myjson) res = obj.retrieveIntermediaryInDB() intermediaries_tuple = json.loads(res) intermediaries_emails = [] intermediary_names = [] orig_emails = [] beneficiary_ids = [] beneficiary_names = [] intermediary_mobiles = [] posn = 0 gardens = [] competitors_counter = 0 garden_label = date_str.replace("-", "_") first_posn = 0 second_posn = 0 key2 = "D" tree_array = [] flower_array = [] total_plants = [] urls = [] usage_points = [] bonus_points = [] badges = [] badge_posn = [] for record in intermediaries_tuple.items(): key, user = record if (user["D2"] == "None"): continue else: orig_emails.append(user["D1"]) #keep original email addresses orig_email = user["D1"] user["D1"] = user["D1"].replace("@", "_at_") user["D1"] = user["D1"].replace(".", "_dot_") intermediaries_emails.append(user["D1"]) intermediary_names.append(user["D0"]) beneficiary_names.append( user["D2"][0:user["D2"].index('.')]) # get the name only myjson = { 'Fname': 'Dummy', 'Lname': 'Dummy', 'Username': orig_email } obj = RetrieveIntermediary(myjson) result2 = obj.isAssignedBeneficiary() beneficiary_tuple = json.loads(result2) beneficiary_ids.append(beneficiary_tuple["Id"]) intermediary_mobiles.append(user["D5"][(user["D5"].index(':') + 1):(len(user["D5"]))]) file_path = "django_facebook/images/garden/%s/%s_%s.jpeg" % ( intermediaries_emails[posn], beneficiary_ids[posn], garden_label) file_name = "%s_%s" % (beneficiary_ids[posn], garden_label) urls.append(file_path) varmyjson = {'Day': day} clickPointsObj = RetrievePoints(varmyjson, orig_email, 1) resclickpoints = clickPointsObj.retrieveIntermediaryClickPoints( ) resclickpoints = json.loads(resclickpoints) #clickpoints=int(resclickpoints["points"]/resclickpoints["dates_counter"]) clickpoints = int(resclickpoints["points"]) if clickpoints > 18: clickpoints = 18 usage_points.append(clickpoints) ressteps = clickPointsObj.getSteps(beneficiary_tuple["Id"]) ressteps = json.loads(ressteps) #stepspoints=int(ressteps["steps"]/(100*ressteps["dates_counter"])) stepspoints = int(ressteps["steps"]) if stepspoints > 70000: stepspoints = 70000 bonus_points.append(stepspoints) trees = int(stepspoints * 100 / 70000) flowers = int(clickpoints * 67 / 18) #print file_name,trees, flowers tree_array.append(trees) flower_array.append(flowers) total = trees + flowers total_plants.append(total) #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) engine = db # create a Session Session = sessionmaker(bind=engine) session = Session() res2 = session.query(AttainedUserBadges, Badges).filter( AttainedUserBadges.intermediary_id == orig_email).filter(AttainedUserBadges.status == 1).filter( AttainedUserBadges.badge_id == Badges.rank).first() if res2 is None: sys.exit( ) # exit and wait until the user has atleast been assigned some badge else: print res2.Badges.badgename badges.append(res2.Badges.badgename) badge_posn.append(res2.Badges.rank) ''' if stepspoints>=70000: if clickpoints>=18: badges.append("Queen") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/queen.jpeg") else: badges.append("No promotion") elif stepspoints>=63000: if clickpoints>=16: badges.append("Princess") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/princess.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/duchess.jpeg") elif stepspoints>=56000: if clickpoints>=14: badges.append("Duchess") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/duchess.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/grandmaster.jpeg") elif stepspoints>=49000: if clickpoints>=12: badges.append("Grand Master") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/grandmaster.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniormaster.jpeg") elif stepspoints>=42000: if clickpoints>=10: badges.append("Senior Master") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniormaster.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/master.jpeg") elif stepspoints>=31500: if clickpoints>=8: badges.append("Master") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/master.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/juniormaster.jpeg") if stepspoints>=21000: if clickpoints>=4: badges.append("Junior Master") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/juniormaster.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniorservant.jpeg") elif stepspoints>=14000: if clickpoints>=2: badges.append("Senior Servant") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniorservant.jpeg") else: badges.append("No Promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/servant.jpeg") elif stepspoints>=7000: if clickpoints>=1: badges.append("Servant") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/servant.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/slave.jpeg") else: badges.append("Slave") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/slave.jpeg") ''' posn = posn + 1 posn = 0 #sort in descending order bubblesort(badge_posn, urls, beneficiary_ids, tree_array, flower_array, intermediary_names, beneficiary_names, usage_points, bonus_points, badges, total_plants) #print badges posn = 0 file_path_alt = "django_facebook/images/garden/blank.jpg" for beneficiary in beneficiary_ids: urls_tuple = {} if first_posn < 10: key1 = "R0" else: key1 = "R" urls_tuple[key2 + "%s" % second_posn] = "(%s, %s)" % ( intermediary_names[posn], beneficiary_names[posn]) second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = urls[posn] if total_plants[posn] == 0: urls_tuple[key2 + "%s" % second_posn] = file_path_alt second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % tree_array[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % flower_array[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % total_plants[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % usage_points[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % bonus_points[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % badges[posn] second_posn = second_posn + 1 #urls_tuple[key2+"%s"%second_posn]="%s"%badges_urls[posn] #second_posn=second_posn+1 urls_tuple[key2 + "%s" % second_posn] = "%s" % intermediary_mobiles[posn] second_posn = second_posn + 1 second_posn = 0 result[key1 + "%s" % first_posn] = (OrderedDict( sorted(urls_tuple.items(), key=lambda t: t[0]))) first_posn = first_posn + 1 posn = posn + 1 return (json.JSONEncoder().encode( OrderedDict(sorted(result.items(), key=lambda t: t[0]))))
def twoWeeksSteps(self): result={} try: day=self.myjson["Day"] except Exception as e: #print "Content-type: text/html\n" result["message"]="Error%s"%e.message return (json.JSONEncoder().encode(result)) if day is not None: #if day=="Today": # today_date=datetime.date.today() # date_str="%s"%today_date #else: date_str="%s"%day else: result["message"]="Error: The option '%s' is invalid"%day return (json.JSONEncoder().encode(result)) myjson={'Fname':'Dummy','Lname':'Dummy','Username':'******'} obj=RetrieveIntermediary(myjson) res=obj.retrieveIntermediaryInDB() intermediaries_tuple=json.loads(res) intermediaries_emails=[] intermediary_names=[] orig_emails=[] beneficiary_ids=[] beneficiary_names=[] beneficiary_relations=[]# The relationships between intermediaries and beneficiaries. beneficiary_genders=[] posn=0 gardens=[] competitors_counter=0 garden_label=date_str.replace("-","_") first_posn=0 second_posn=0 key2="D" tree_array=[] flower_array=[] total_plants=[] urls=[] usage_points=[] bonus_points_start=[] bonus_points_end=[] badges=[] badges_urls=[] intermediary_mobiles=[] for record in intermediaries_tuple.items(): key,user =record if(user["D2"]=="None"): continue else: orig_emails.append(user["D1"]) #keep original email addresses orig_email=user["D1"] user["D1"]=user["D1"].replace("@","_at_") user["D1"]=user["D1"].replace(".","_dot_") intermediaries_emails.append(user["D1"]) intermediary_names.append(user["D0"]) beneficiary_names.append(user["D2"][0:user["D2"].index('.')])# get the name only beneficiary_relations.append(user["D3"][(user["D3"].index(':')+1):(len(user["D3"]))]) beneficiary_genders.append(user["D4"][(user["D4"].index(':')+1):(len(user["D4"]))]) intermediary_mobiles.append(user["D5"][(user["D5"].index(':')+1):(len(user["D5"]))]) myjson={'Fname':'Dummy','Lname':'Dummy','Username':orig_email} obj=RetrieveIntermediary(myjson) result2=obj.isAssignedBeneficiary() beneficiary_tuple=json.loads(result2) beneficiary_ids.append(beneficiary_tuple["Id"]) file_path="django_facebook/images/garden/%s/%s_%s.jpeg"%(intermediaries_emails[posn],beneficiary_ids[posn],garden_label) file_name="%s_%s"%(beneficiary_ids[posn],garden_label) urls.append(file_path) varmyjson={'Day':day} stepsPointsObj=RetrievePoints(varmyjson,orig_email,1) ressteps=stepsPointsObj.getSteps(beneficiary_tuple["Id"]) ressteps=json.loads(ressteps) #stepspoints=int(ressteps["steps"]/(100*ressteps["dates_counter"])) stepspoints_last_week=int(ressteps["steps1"]) stepspoints_last_last_week=int(ressteps["steps2"]) #append an array of total steps for each each week for the last two weeks. bonus_points_start.append(stepspoints_last_week) bonus_points_end.append(stepspoints_last_last_week) posn=posn+1 posn=0 for beneficiary in beneficiary_ids: urls_tuple={} if first_posn<10: key1="R0" else: key1="R" urls_tuple[key2+"%s"%second_posn]="%s"%intermediary_names[posn] second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%beneficiary_names[posn] second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%bonus_points_start[posn] second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%bonus_points_end[posn] second_posn=second_posn+1 #urls_tuple[key2+"%s"%second_posn]="%s"%badges[posn] #second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%beneficiary_relations[posn] second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%beneficiary_genders[posn] second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%intermediary_mobiles[posn] second_posn=second_posn+1 second_posn=0 result[key1+"%s"%first_posn]=(OrderedDict(sorted(urls_tuple.items(), key=lambda t: t[0]))) first_posn=first_posn+1 posn=posn+1 return (json.JSONEncoder().encode(OrderedDict(sorted(result.items(), key=lambda t: t[0]))))
def assignBadges(self): result = {} try: day = self.myjson["Day"] except Exception as e: #print "Content-type: text/html\n" result["message"] = "Error%s" % e.message return (json.JSONEncoder().encode(result)) if day is not None: #if day=="Today": # today_date=datetime.date.today() # date_str="%s"%today_date #else: date_str = "%s" % day else: result["message"] = "Error: The option '%s' is invalid" % day return (json.JSONEncoder().encode(result)) try: myjson = {'Fname': 'Dummy', 'Lname': 'Dummy', 'Username': '******'} obj = RetrieveIntermediary(myjson) res = obj.retrieveIntermediaryInDB() intermediaries_tuple = json.loads(res) intermediaries_emails = [] intermediary_names = [] orig_emails = [] beneficiary_ids = [] beneficiary_names = [] intermediary_mobiles = [] beneficiary_relations = [] posn = 0 gardens = [] competitors_counter = 0 garden_label = date_str.replace("-", "_") first_posn = 0 second_posn = 0 key2 = "D" tree_array = [] flower_array = [] total_plants = [] urls = [] usage_points = [] bonus_points = [] badges = [] badges_urls = [] for record in intermediaries_tuple.items(): key, user = record if (user["D2"] == "None"): continue else: orig_emails.append( user["D1"]) #keep original email addresses orig_email = user["D1"] user["D1"] = user["D1"].replace("@", "_at_") user["D1"] = user["D1"].replace(".", "_dot_") intermediaries_emails.append(user["D1"]) intermediary_names.append(user["D0"]) beneficiary_names.append( user["D2"] [0:user["D2"].index('.')]) # get the name only beneficiary_relations.append( user["D3"][(user["D3"].index(':') + 1):(len(user["D3"]))]) intermediary_mobiles.append( user["D5"][(user["D5"].index(':') + 1):(len(user["D5"]))]) myjson = { 'Fname': 'Dummy', 'Lname': 'Dummy', 'Username': orig_email } obj = RetrieveIntermediary(myjson) result2 = obj.isAssignedBeneficiary() beneficiary_tuple = json.loads(result2) beneficiary_ids.append(beneficiary_tuple["Id"]) file_path = "django_facebook/images/garden/%s/%s_%s.jpeg" % ( intermediaries_emails[posn], beneficiary_ids[posn], garden_label) file_name = "%s_%s" % (beneficiary_ids[posn], garden_label) urls.append(file_path) varmyjson = {'Day': day} clickPointsObj = RetrievePoints(varmyjson, orig_email, 1) resclickpoints = clickPointsObj.retrieveIntermediaryClickPoints( ) resclickpoints = json.loads(resclickpoints) #clickpoints=int(resclickpoints["points"]/resclickpoints["dates_counter"]) clickpoints = int(resclickpoints["points"]) if clickpoints > 18: clickpoints = 18 usage_points.append(clickpoints) ressteps = clickPointsObj.getSteps(beneficiary_tuple["Id"]) ressteps = json.loads(ressteps) #stepspoints=int(ressteps["steps"]/(100*ressteps["dates_counter"])) stepspoints = int(ressteps["steps"]) if stepspoints > 70000: stepspoints = 70000 bonus_points.append(stepspoints) #trees=int(stepspoints*100/70000) #flowers=int(clickpoints*67/18) #print file_name,trees, flowers #tree_array.append(trees) #flower_array.append(flowers) #total=trees+flowers #total_plants.append(total) #Get the current badge of this individual engine = db # create a Session Session = sessionmaker(bind=engine) session = Session() #get the current badge res = session.query(AttainedUserBadges).filter( AttainedUserBadges.intermediary_id == orig_email ).filter(AttainedUserBadges.status == 1).first() if res is None: #this user is not assigned a bagde currentbadge = 0 #start with slave badge else: currentbadge = res.badge_id old_badge = currentbadge if stepspoints >= 10000 and currentbadge == 2: if clickpoints >= 18: badges.append("Queen/King") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/queen.jpeg" ) else: badges.append("No promotion") elif stepspoints >= 9000 and currentbadge == 3: if clickpoints >= 16: badges.append("Princess/Prince") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/princess.jpeg" ) else: badges.append("No promotion") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/duchess.jpeg" ) elif stepspoints >= 8000 and currentbadge == 4: if clickpoints >= 14: badges.append("Duchess/Duke") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/duchess.jpeg" ) else: badges.append("No promotion") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/grandmaster.jpeg" ) elif stepspoints >= 7000 and currentbadge == 5: if clickpoints >= 12: badges.append("Grand Master") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/grandmaster.jpeg" ) else: badges.append("No promotion") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniormaster.jpeg" ) elif stepspoints >= 6000 and currentbadge == 6: if clickpoints >= 10: badges.append("Senior Master") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniormaster.jpeg" ) else: badges.append("No promotion") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/master.jpeg" ) elif stepspoints >= 5000 and currentbadge == 7: if clickpoints >= 8: badges.append("Master") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/master.jpeg" ) else: badges.append("No promotion") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/juniormaster.jpeg" ) if stepspoints >= 4000 and currentbadge == 8: if clickpoints >= 4: badges.append("Junior Master") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/juniormaster.jpeg" ) else: badges.append("No promotion") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniorservant.jpeg" ) elif stepspoints >= 3000 and currentbadge == 9: if clickpoints >= 2: badges.append("Senior Servant") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniorservant.jpeg" ) else: badges.append("No Promotion") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/servant.jpeg" ) elif stepspoints >= 2500 and currentbadge == 10: if clickpoints >= 1: badges.append("Servant") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/servant.jpeg" ) else: badges.append("No promotion") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/slave.jpeg" ) else: badges.append("Slave") badges_urls.append( "http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/slave.jpeg" ) try: #get the rank of the badge if badges[posn] == "No promotion": print "No Promotion" else: #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) engine = db # create a Session Session = sessionmaker(bind=engine) session = Session() res = session.query(Badges).filter( Badges.badgename == badges[posn]).first() if res == None: rank = 0 else: rank = res.rank #new acquired rank first_name = intermediary_names[posn][0:( intermediary_names[posn].index(' ') + 1)] # #new_attained_badge #first get the current badge of this res = session.query(AttainedUserBadges).filter( AttainedUserBadges.intermediary_id == orig_email).filter( AttainedUserBadges.status == 1).first() if res is None: #first promotion #insert a new badge into the database new_attained_badge = AttainedUserBadges( orig_email, datetime.date.today(), rank) session.add(new_attained_badge) session.commit() # Commit this transaction #first_name=intermediary_names[posn][0:(intermediary_names[posn].index(' ')+1)] # print "First Promotion" feedback_message = "Hey %s " % first_name feedback_message = feedback_message + "your team's first badge is %s . You and your %s need to work harder to progress to higher badges. You can only obtain higher badges if you keep on using the app everyday and motivate your %s to walk more steps everyday." % ( badges[posn], beneficiary_relations[posn], beneficiary_relations[posn]) myjson2 = { "recipient": intermediary_mobiles[posn], "message": feedback_message } obj = QueueFeedback(myjson2) res = obj.saveFeedbackInDB() else: #check if the current badge rank is less than the new badge rank if rank < res.badge_id: #promote to new higher badge res.status = 0 # make the current badge obsolete session.commit() session = Session() #create a new session #insert a new badge into the database new_attained_badge = AttainedUserBadges( orig_email, datetime.date.today(), rank) session.add(new_attained_badge) session.commit() # Commit this transaction print "Promoted to new rank" feedback_message = "Hey %s " % first_name feedback_message = feedback_message + "your team has been promoted to a new badge. Your old badge was %s and now your new badge is %s. Keep on using your app every day and keep on motivating your %s to walk more steps so that your team can continue to shine." % ( old_badge, badges[posn], beneficiary_relations[posn]) myjson2 = { "recipient": intermediary_mobiles[posn], "message": feedback_message } obj = QueueFeedback(myjson2) res = obj.saveFeedbackInDB() #else: # print "No new promotion" # #pass# no new promotion except Exception as e: print "Exception thrown: %s" % e return -1 posn = posn + 1 except Exception as e: print "Exception thrown %s " % e return -1 return 1
def retrieveScoreGardensUrls(self): result = {} try: day = self.myjson["Day"] except Exception as e: #print "Content-type: text/html\n" result["message"] = "Error%s" % e.message return (json.JSONEncoder().encode(result)) #day="Today" #startdate="2013-12-06" #enddate="2013-12-06" #intermediary_id=self.sessionvar['username'] #self.b_id='KTLNTW001' if day == "Today": date_int = datetime.date.today() date_str = "%s" % date_int elif day == "Yesterday": #Yesterday date_int = datetime.date.today() - datetime.timedelta(days=1) else: result["message"] = "Error: The option '%s' is invalid" % day return (json.JSONEncoder().encode(result)) date_str = "%s" % date_int myjson = {'Fname': 'Dummy', 'Lname': 'Dummy', 'Username': '******'} obj = RetrieveIntermediary(myjson) res = obj.retrieveIntermediaryInDB() intermediaries_tuple = json.loads(res) intermediaries_emails = [] intermediary_names = [] orig_emails = [] beneficiary_ids = [] posn = 0 gardens = [] competitors_counter = 0 garden_label = date_str.replace("-", "_") first_posn = 0 second_posn = 0 key2 = "D" tree_array = [] flower_array = [] total_plants = [] urls = [] for record in intermediaries_tuple.items(): key, user = record if (user["D2"] == "None"): continue else: orig_emails.append(user["D1"]) #keep original email addresses orig_email = user["D1"] user["D1"] = user["D1"].replace("@", "_at_") user["D1"] = user["D1"].replace(".", "_dot_") intermediaries_emails.append(user["D1"]) intermediary_names.append(user["D0"]) myjson = { 'Fname': 'Dummy', 'Lname': 'Dummy', 'Username': orig_email } obj = RetrieveIntermediary(myjson) result2 = obj.isAssignedBeneficiary() beneficiary_tuple = json.loads(result2) beneficiary_ids.append(beneficiary_tuple["Id"]) #image_path="/static/wellnessapp/images/garden/%s/%s_%s.jpeg"%(intermediaries_emails[posn],beneficiary_ids[posn],garden_label) #file_path=os.path.dirname(os.path.abspath(__file__)) #if not os.path.isfile(image_path): # file_path="wellnessapp/images/garden/%s/blank.jpeg"%intermediaries_emails[posn] #else: file_path = "wellnessapp/images/garden/%s/%s_%s.jpeg" % ( intermediaries_emails[posn], beneficiary_ids[posn], garden_label) file_path_alt = "wellnessapp/images/garden/blank.jpeg" file_name = "%s_%s" % (beneficiary_ids[posn], garden_label) urls.append(file_path) myjson = {'FactorId': file_name} obj = ManageFactors(myjson) res = obj.retrieveFactorsFromDB() res = json.loads(res) trees = int(res["R00"]["TreeFactor"] * 100.0) flowers = int(res["R00"]["FlowerFactor"] * 67.0) tree_array.append(trees) flower_array.append(flowers) total = trees + flowers total_plants.append(total) posn = posn + 1 posn = 0 ''' for beneficiary in beneficiary_ids: file_path="{{STATIC_URL}}wellnessapp/images/garden/%s/%s_%s"%(intermediaries_emails[posn],beneficiary_ids[posn],garden_label) file_name="%s_%s"%(beneficiary_ids[posn],garden_label) urls.append(file_path) myjson={'FactorId':file_name} obj=ManageFactors(myjson) res=obj.retrieveFactorsFromDB() res=json.loads(res) trees=int(res["R00"]["TreeFactor"]*100.0) flowers=int(res["R00"]["FlowerFactor"]*67.0) tree_array.append(trees) flower_array.append(flowers) total=trees+flowers total_plants.append(total) posn=posn+1 ''' bubblesort(total_plants, urls, beneficiary_ids, tree_array, flower_array, intermediary_names) posn = 0 file_path_alt = "wellnessapp/images/garden/blank.jpeg" for beneficiary in beneficiary_ids: urls_tuple = {} if first_posn < 10: key1 = "R0" else: key1 = "R" urls_tuple[key2 + "%s" % second_posn] = urls[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = file_path_alt second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % tree_array[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % flower_array[posn] second_posn = second_posn + 1 urls_tuple[key2 + "%s" % second_posn] = "%s" % intermediary_names[posn] second_posn = second_posn + 1 second_posn = 0 result[key1 + "%s" % first_posn] = urls_tuple first_posn = first_posn + 1 posn = posn + 1 return (json.JSONEncoder().encode( OrderedDict(sorted(result.items(), key=lambda t: t[0]))))
def retrieveScoreGardensUrls(self): result={} try: day=self.myjson["Day"] except Exception as e: #print "Content-type: text/html\n" result["message"]="Error%s"%e.message return (json.JSONEncoder().encode(result)) if day is not None: if day=="Today": today_date=datetime.date.today() date_str="%s"%today_date else: date_str="%s"%day else: result["message"]="Error: The option '%s' is invalid"%day return (json.JSONEncoder().encode(result)) myjson={'Fname':'Dummy','Lname':'Dummy','Username':'******'} obj=RetrieveIntermediary(myjson) res=obj.retrieveIntermediaryInDB() intermediaries_tuple=json.loads(res) intermediaries_emails="" intermediary_names="" #orig_emails=[] beneficiary_id=0 beneficiary_names="" posn=0 gardens=[] competitors_counter=0 garden_label=date_str.replace("-","_") first_posn=0 second_posn=0 key2="D" trees=0 flowers=0 fishnum=0 fish_size=0.0 total_plants="" url="" usage_points="" bonus_points="" badge="" badge_url="" team_members="" team_name="" team_features=[] for record in intermediaries_tuple.items(): key,user =record if(user["D2"]=="None"): continue else: #orig_emails.append(user["D1"]) #keep original email addresses orig_email=user["D1"] user["D1"]=user["D1"].replace("@","_at_") user["D1"]=user["D1"].replace(".","_dot_") intermediary_email=user["D1"] intermediary_names=user["D0"] beneficiary_names=user["D2"][0:user["D2"].index('.')]# get the name only myjson={'Fname':'Dummy','Lname':'Dummy','Username':orig_email} obj=RetrieveIntermediary(myjson) result2=obj.isAssignedBeneficiary() beneficiary_tuple=json.loads(result2) team_identifier="%s_%s"%(beneficiary_tuple["Id"],garden_label) beneficiary_id=team_identifier #Beneficiary file_path="django_facebook/images/garden/%s/%s_%s.jpeg"%(intermediary_email,beneficiary_tuple["Id"],garden_label) file_name="%s_%s"%(beneficiary_id,garden_label) url=file_path # url team_name=beneficiary_tuple["TeamName"] # Team Name one_team_members="(%s, %s)"%(intermediary_names,beneficiary_names) # put together team members team_members=one_team_members #Team Members varmyjson={'Day':day} clickPointsObj=RetrievePoints(varmyjson,orig_email,self.last_date_specified) resclickpoints=clickPointsObj.retrieveIntermediaryClickPoints() resclickpoints=json.loads(resclickpoints) clickpoints=int(resclickpoints["points"]) clickpoints=clickpoints*1000 usage_points=clickpoints #Usage Points ressteps=clickPointsObj.getSteps(beneficiary_tuple["Id"]) ressteps=json.loads(ressteps) stepspoints=int(ressteps["steps"]/ressteps["dates_counter"]) bonus_points=stepspoints #Bonus points total_points=usage_points+bonus_points resbadge=clickPointsObj.retrieveIndividualBadge() resbadge=json.loads(resbadge) #get badge name for this individual badge=resbadge["R00"]["D3"] #Badge #get a badge url for this person badge_url=resbadge["R00"]["D1"] #Badge URL trees=int(10*(11-resbadge["R00"]["D4"])) # the number of trees in a garden fishnum=int(11-resbadge["R00"]["D4"]) # the number of fish in a tank fishsize=float(float(fishnum)/float(10)) # fish size is determined by how many fish are in the tank. The more fish the bigger the size. This weill also be used to detrmine the quality of a fish tank resmealcounter=self.countRecordedMeals(beneficiary_tuple["Id"]) resmealcounter=json.loads(resmealcounter) flowers=(10*resmealcounter["NumberOfMeals"]) # number of flowers in the garden #print file_name,trees, flowers #total=trees+flowers total_plants=fishnum*10 # these are the total points obj=SaveComment(myjson,beneficiary_tuple["Id"],orig_email) res=obj.getComments("Aquarium") aquariumcomments=json.loads(res) #newaquariumcomments=json.loads(newaquariumcomments) res=obj.getComments("Garden") gardencomments=json.loads(res) one_team_features=TeamFeatures(team_name,team_members,url,trees,flowers,total_plants,usage_points,bonus_points,badge,badge_url,beneficiary_tuple["Id"],fishnum,fishsize,aquariumcomments,gardencomments,total_points) team_features.append(one_team_features) posn=posn+1 posn=0 #bubblesort(total_plants,team_name,team_members,urls,beneficiary_ids,tree_array,flower_array,usage_points,bonus_points,badges,badges_urls,fish_array,fish_size_array) bubblesort(team_features) posn=0 file_path_alt="django_facebook/images/garden/blank.jpg" for one_team in team_features: urls_tuple={} if first_posn<10: key1="R0" else: key1="R" urls_tuple[key2+"%s"%second_posn]="%s"%one_team.team_name # D0 team name second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%one_team.team_members # D1 team members second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]=one_team.url #D2 url for garden if one_team.total_plants==0: urls_tuple[key2+"%s"%second_posn]=file_path_alt second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%one_team.trees #D3 Number of trees second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%one_team.flowers # D4 Number of flowers second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%one_team.total_plants #D5 Total number of plants including flowers and tree second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%one_team.usage_points #D6 Number of days an application has been used multiply by 1000 by a team. second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%one_team.bonus_points #D7 average steps walked by an individual second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%one_team.badge #D8 Badge name second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%one_team.badge_url #D9 Badge Url second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%one_team.beneficiary_id #D10 Beneficiary ID second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%one_team.fishnum # D11 Number of fish in the tank. second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%one_team.fishsize #D12 size of fish in the tank second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]=OrderedDict(sorted(one_team.aquariumcomments.items(), key=lambda t: t[0])) #D13 Aquarium comments second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]=OrderedDict(sorted(one_team.gardencomments.items(), key=lambda t: t[0])) #D14 Garden comments second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%one_team.total_points #D15 Total points second_posn=second_posn+1 second_posn=0 result[key1+"%s"%first_posn]=(OrderedDict(sorted(urls_tuple.items(), key=lambda t: t[0]))) first_posn=first_posn+1 posn=posn+1 return (json.JSONEncoder().encode(OrderedDict(sorted(result.items(), key=lambda t: t[0]))))
def retrieveScoreGardensUrls(self): result={} try: day=self.myjson["Day"] except Exception as e: #print "Content-type: text/html\n" result["message"]="Error%s"%e.message return (json.JSONEncoder().encode(result)) #day="Today" #startdate="2013-12-06" #enddate="2013-12-06" #intermediary_id=self.sessionvar['username'] #self.b_id='KTLNTW001' if day=="Today": date_int=datetime.date.today() date_str ="%s"%date_int elif day=="Yesterday": #Yesterday date_int=datetime.date.today()-datetime.timedelta(days=1) else: result["message"]="Error: The option '%s' is invalid"%day return (json.JSONEncoder().encode(result)) date_str ="%s"%date_int myjson={'Fname':'Dummy','Lname':'Dummy','Username':'******'} obj=RetrieveIntermediary(myjson) res=obj.retrieveIntermediaryInDB() intermediaries_tuple=json.loads(res) intermediaries_emails=[] intermediary_names=[] orig_emails=[] beneficiary_ids=[] posn=0 gardens=[] competitors_counter=0 garden_label=date_str.replace("-","_") first_posn=0 second_posn=0 key2="D" tree_array=[] flower_array=[] total_plants=[] urls=[] for record in intermediaries_tuple.items(): key,user =record if(user["D2"]=="None"): continue else: orig_emails.append(user["D1"]) #keep original email addresses orig_email=user["D1"] user["D1"]=user["D1"].replace("@","_at_") user["D1"]=user["D1"].replace(".","_dot_") intermediaries_emails.append(user["D1"]) intermediary_names.append(user["D0"]) myjson={'Fname':'Dummy','Lname':'Dummy','Username':orig_email} obj=RetrieveIntermediary(myjson) result2=obj.isAssignedBeneficiary() beneficiary_tuple=json.loads(result2) beneficiary_ids.append(beneficiary_tuple["Id"]) #image_path="/static/wellnessapp/images/garden/%s/%s_%s.jpeg"%(intermediaries_emails[posn],beneficiary_ids[posn],garden_label) #file_path=os.path.dirname(os.path.abspath(__file__)) #if not os.path.isfile(image_path): # file_path="wellnessapp/images/garden/%s/blank.jpeg"%intermediaries_emails[posn] #else: file_path="wellnessapp/images/garden/%s/%s_%s.jpeg"%(intermediaries_emails[posn],beneficiary_ids[posn],garden_label) file_path_alt="wellnessapp/images/garden/blank.jpeg" file_name="%s_%s"%(beneficiary_ids[posn],garden_label) urls.append(file_path) myjson={'FactorId':file_name} obj=ManageFactors(myjson) res=obj.retrieveFactorsFromDB() res=json.loads(res) trees=int(res["R00"]["TreeFactor"]*100.0) flowers=int(res["R00"]["FlowerFactor"]*67.0) tree_array.append(trees) flower_array.append(flowers) total=trees+flowers total_plants.append(total) posn=posn+1 posn=0 ''' for beneficiary in beneficiary_ids: file_path="{{STATIC_URL}}wellnessapp/images/garden/%s/%s_%s"%(intermediaries_emails[posn],beneficiary_ids[posn],garden_label) file_name="%s_%s"%(beneficiary_ids[posn],garden_label) urls.append(file_path) myjson={'FactorId':file_name} obj=ManageFactors(myjson) res=obj.retrieveFactorsFromDB() res=json.loads(res) trees=int(res["R00"]["TreeFactor"]*100.0) flowers=int(res["R00"]["FlowerFactor"]*67.0) tree_array.append(trees) flower_array.append(flowers) total=trees+flowers total_plants.append(total) posn=posn+1 ''' bubblesort(total_plants,urls,beneficiary_ids,tree_array,flower_array,intermediary_names) posn=0 file_path_alt="wellnessapp/images/garden/blank.jpeg" for beneficiary in beneficiary_ids: urls_tuple={} if first_posn<10: key1="R0" else: key1="R" urls_tuple[key2+"%s"%second_posn]=urls[posn] second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]=file_path_alt second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%tree_array[posn] second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%flower_array[posn] second_posn=second_posn+1 urls_tuple[key2+"%s"%second_posn]="%s"%intermediary_names[posn] second_posn=second_posn+1 second_posn=0 result[key1+"%s"%first_posn]=urls_tuple first_posn=first_posn+1 posn=posn+1 return (json.JSONEncoder().encode(OrderedDict(sorted(result.items(), key=lambda t: t[0]))))
def assignBadges(self): result={} try: day=self.myjson["Day"] except Exception as e: #print "Content-type: text/html\n" result["message"]="Error%s"%e.message return (json.JSONEncoder().encode(result)) if day is not None: #if day=="Today": # today_date=datetime.date.today() # date_str="%s"%today_date #else: date_str="%s"%day else: result["message"]="Error: The option '%s' is invalid"%day return (json.JSONEncoder().encode(result)) try: myjson={'Fname':'Dummy','Lname':'Dummy','Username':'******'} obj=RetrieveIntermediary(myjson) res=obj.retrieveIntermediaryInDB() intermediaries_tuple=json.loads(res) intermediaries_emails=[] intermediary_names=[] orig_emails=[] beneficiary_ids=[] beneficiary_names=[] intermediary_mobiles=[] beneficiary_relations=[] posn=0 gardens=[] competitors_counter=0 garden_label=date_str.replace("-","_") first_posn=0 second_posn=0 key2="D" tree_array=[] flower_array=[] total_plants=[] urls=[] usage_points=[] bonus_points=[] badges=[] badges_urls=[] for record in intermediaries_tuple.items(): key,user =record if(user["D2"]=="None"): continue else: orig_emails.append(user["D1"]) #keep original email addresses orig_email=user["D1"] user["D1"]=user["D1"].replace("@","_at_") user["D1"]=user["D1"].replace(".","_dot_") intermediaries_emails.append(user["D1"]) intermediary_names.append(user["D0"]) beneficiary_names.append(user["D2"][0:user["D2"].index('.')])# get the name only beneficiary_relations.append(user["D3"][(user["D3"].index(':')+1):(len(user["D3"]))]) intermediary_mobiles.append(user["D5"][(user["D5"].index(':')+1):(len(user["D5"]))]) myjson={'Fname':'Dummy','Lname':'Dummy','Username':orig_email} obj=RetrieveIntermediary(myjson) result2=obj.isAssignedBeneficiary() beneficiary_tuple=json.loads(result2) beneficiary_ids.append(beneficiary_tuple["Id"]) file_path="django_facebook/images/garden/%s/%s_%s.jpeg"%(intermediaries_emails[posn],beneficiary_ids[posn],garden_label) file_name="%s_%s"%(beneficiary_ids[posn],garden_label) urls.append(file_path) varmyjson={'Day':day} clickPointsObj=RetrievePoints(varmyjson,orig_email,1) resclickpoints=clickPointsObj.retrieveIntermediaryClickPoints() resclickpoints=json.loads(resclickpoints) #clickpoints=int(resclickpoints["points"]/resclickpoints["dates_counter"]) clickpoints=int(resclickpoints["points"]) if clickpoints>18: clickpoints=18 usage_points.append(clickpoints) ressteps=clickPointsObj.getSteps(beneficiary_tuple["Id"]) ressteps=json.loads(ressteps) #stepspoints=int(ressteps["steps"]/(100*ressteps["dates_counter"])) stepspoints=int(ressteps["steps"]) if stepspoints>70000: stepspoints=70000 bonus_points.append(stepspoints) #trees=int(stepspoints*100/70000) #flowers=int(clickpoints*67/18) #print file_name,trees, flowers #tree_array.append(trees) #flower_array.append(flowers) #total=trees+flowers #total_plants.append(total) #Get the current badge of this individual engine=db # create a Session Session = sessionmaker(bind=engine) session = Session() #get the current badge res=session.query(AttainedUserBadges).filter(AttainedUserBadges.intermediary_id==orig_email).filter(AttainedUserBadges.status==1).first() if res is None: #this user is not assigned a bagde currentbadge=0 #start with slave badge else: currentbadge=res.badge_id old_badge=currentbadge if stepspoints>=10000 and currentbadge==2: if clickpoints>=18: badges.append("Queen/King") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/queen.jpeg") else: badges.append("No promotion") elif stepspoints>=9000 and currentbadge==3: if clickpoints>=16: badges.append("Princess/Prince") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/princess.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/duchess.jpeg") elif stepspoints>=8000 and currentbadge==4: if clickpoints>=14: badges.append("Duchess/Duke") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/duchess.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/grandmaster.jpeg") elif stepspoints>=7000 and currentbadge==5: if clickpoints>=12: badges.append("Grand Master") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/grandmaster.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniormaster.jpeg") elif stepspoints>=6000 and currentbadge==6: if clickpoints>=10: badges.append("Senior Master") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniormaster.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/master.jpeg") elif stepspoints>=5000 and currentbadge==7: if clickpoints>=8: badges.append("Master") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/master.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/juniormaster.jpeg") if stepspoints>=4000 and currentbadge==8: if clickpoints>=4: badges.append("Junior Master") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/juniormaster.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniorservant.jpeg") elif stepspoints>=3000 and currentbadge==9: if clickpoints>=2: badges.append("Senior Servant") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/seniorservant.jpeg") else: badges.append("No Promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/servant.jpeg") elif stepspoints>=2500 and currentbadge==10: if clickpoints>=1: badges.append("Servant") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/servant.jpeg") else: badges.append("No promotion") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/slave.jpeg") else: badges.append("Slave") badges_urls.append("http://ict4d01.cs.uct.ac.za/static/django_facebook/images/badges/slave.jpeg") try: #get the rank of the badge if badges[posn] == "No promotion": print "No Promotion" else: #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) engine=db # create a Session Session = sessionmaker(bind=engine) session = Session() res=session.query(Badges).filter(Badges.badgename==badges[posn]).first() if res ==None: rank=0 else: rank=res.rank #new acquired rank first_name=intermediary_names[posn][0:(intermediary_names[posn].index(' ')+1)] # #new_attained_badge #first get the current badge of this res=session.query(AttainedUserBadges).filter(AttainedUserBadges.intermediary_id==orig_email).filter(AttainedUserBadges.status==1).first() if res is None: #first promotion #insert a new badge into the database new_attained_badge=AttainedUserBadges(orig_email,datetime.date.today(),rank) session.add(new_attained_badge) session.commit()# Commit this transaction #first_name=intermediary_names[posn][0:(intermediary_names[posn].index(' ')+1)] # print "First Promotion" feedback_message="Hey %s "%first_name feedback_message=feedback_message+"your team's first badge is %s . You and your %s need to work harder to progress to higher badges. You can only obtain higher badges if you keep on using the app everyday and motivate your %s to walk more steps everyday."%(badges[posn],beneficiary_relations[posn],beneficiary_relations[posn]) myjson2={"recipient":intermediary_mobiles[posn],"message":feedback_message} obj=QueueFeedback(myjson2) res=obj.saveFeedbackInDB() else: #check if the current badge rank is less than the new badge rank if rank<res.badge_id: #promote to new higher badge res.status=0# make the current badge obsolete session.commit() session = Session()#create a new session #insert a new badge into the database new_attained_badge=AttainedUserBadges(orig_email,datetime.date.today(),rank) session.add(new_attained_badge) session.commit()# Commit this transaction print "Promoted to new rank" feedback_message="Hey %s "%first_name feedback_message=feedback_message+"your team has been promoted to a new badge. Your old badge was %s and now your new badge is %s. Keep on using your app every day and keep on motivating your %s to walk more steps so that your team can continue to shine."%(old_badge,badges[posn],beneficiary_relations[posn]) myjson2={"recipient":intermediary_mobiles[posn],"message":feedback_message} obj=QueueFeedback(myjson2) res=obj.saveFeedbackInDB() #else: # print "No new promotion" # #pass# no new promotion except Exception as e: print "Exception thrown: %s"%e return -1 posn=posn+1 except Exception as e: print "Exception thrown %s "%e return -1 return 1
def assignBadges(self): result = {} try: day = self.myjson["Day"] except Exception as e: #print "Content-type: text/html\n" result["message"] = "Error%s" % e.message return (json.JSONEncoder().encode(result)) if day is not None: #if day=="Today": # today_date=datetime.date.today() # date_str="%s"%today_date #else: date_str = "%s" % day else: result["message"] = "Error: The option '%s' is invalid" % day return (json.JSONEncoder().encode(result)) try: myjson = {'Fname': 'Dummy', 'Lname': 'Dummy', 'Username': '******'} obj = RetrieveIntermediary(myjson) res = obj.retrieveIntermediaryInDB() intermediaries_tuple = json.loads(res) intermediaries_emails = [] intermediary_names = [] orig_emails = [] beneficiary_ids = [] beneficiary_names = [] intermediary_mobiles = [] beneficiary_relations = [] posn = 0 gardens = [] competitors_counter = 0 garden_label = date_str.replace("-", "_") first_posn = 0 second_posn = 0 key2 = "D" tree_array = [] flower_array = [] total_plants = [] urls = [] usage_points = [] bonus_points = [] badges = [] badges_urls = [] currentdate = datetime.datetime.today() #get the date for the first day of this week day_of_week = currentdate.weekday() week_start_date = currentdate - datetime.timedelta( days=day_of_week) #get the first and end date of last week previous_week_end_date = week_start_date - datetime.timedelta( days=1) #go to last sunday previous_week_start_date = previous_week_end_date - datetime.timedelta( days=6) #go to last monday #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) engine = db # create a Session Session = sessionmaker(bind=engine) session = Session() res2 = session.query( AttainedUserBadges, Badges, Intermediary).filter( Intermediary.intermediary_id == AttainedUserBadges.intermediary_id).filter( AttainedUserBadges.status == 1).filter( AttainedUserBadges.badge_id == Badges.rank).filter( AttainedUserBadges.date_attained >= previous_week_start_date).filter( AttainedUserBadges.date_attained <= previous_week_end_date).all() users_with_progress_str = "|" users_with_progress = 0 for rel1, rel2, rel3 in res2: users_with_progress_str = users_with_progress_str + rel3.intermediary_fname users_with_progress_str = users_with_progress_str + " " #users_with_progress_str=users_with_progress_str+rel3.intermediary_lname users_with_progress_str = users_with_progress_str + ", Badge:" users_with_progress_str = users_with_progress_str + rel2.badgename users_with_progress_str = users_with_progress_str + "|" users_with_progress = users_with_progress + 1 for record in intermediaries_tuple.items(): key, user = record if (user["D2"] == "None"): continue else: orig_emails.append( user["D1"]) #keep original email addresses orig_email = user["D1"] user["D1"] = user["D1"].replace("@", "_at_") user["D1"] = user["D1"].replace(".", "_dot_") intermediaries_emails.append(user["D1"]) intermediary_names.append(user["D0"]) beneficiary_names.append( user["D2"] [0:user["D2"].index('.')]) # get the name only beneficiary_relations.append( user["D3"][(user["D3"].index(':') + 1):(len(user["D3"]))]) intermediary_mobiles.append( user["D5"][(user["D5"].index(':') + 1):(len(user["D5"]))]) first_name = intermediary_names[posn][0:( intermediary_names[posn].index(' ') + 1)] # myjson = { 'Fname': 'Dummy', 'Lname': 'Dummy', 'Username': orig_email } obj = RetrieveIntermediary(myjson) result2 = obj.isAssignedBeneficiary() beneficiary_tuple = json.loads(result2) beneficiary_ids.append(beneficiary_tuple["Id"]) file_path = "django_facebook/images/garden/%s/%s_%s.jpeg" % ( intermediaries_emails[posn], beneficiary_ids[posn], garden_label) file_name = "%s_%s" % (beneficiary_ids[posn], garden_label) urls.append(file_path) varmyjson = {'Day': day} clickPointsObj = RetrievePoints(varmyjson, orig_email, 1) resclickpoints = clickPointsObj.retrieveIntermediaryClickPoints( ) resclickpoints = json.loads(resclickpoints) #clickpoints=int(resclickpoints["points"]/resclickpoints["dates_counter"]) clickpoints = int(resclickpoints["points"]) if clickpoints > 18: clickpoints = 18 usage_points.append(clickpoints) ressteps = clickPointsObj.getSteps(beneficiary_tuple["Id"]) ressteps = json.loads(ressteps) #stepspoints=int(ressteps["steps"]/(100*ressteps["dates_counter"])) stepspoints = int(ressteps["steps"]) if stepspoints > 70000: stepspoints = 70000 bonus_points.append(stepspoints) trees = int(stepspoints * 100 / 70000) flowers = int(clickpoints * 67 / 18) #print file_name,trees, flowers tree_array.append(trees) flower_array.append(flowers) total = trees + flowers total_plants.append(total) #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) #engine=db # create a Session #Session = sessionmaker(bind=engine) #session = Session() #check if there a new badge attained in last week res2 = session.query(AttainedUserBadges, Badges).filter( AttainedUserBadges.intermediary_id == orig_email ).filter(AttainedUserBadges.status == 1).filter( AttainedUserBadges.badge_id == Badges.rank).filter( AttainedUserBadges.date_attained >= previous_week_start_date).filter( AttainedUserBadges.date_attained <= previous_week_end_date).first() if res2 is None: # select one message out of five messages num = randint(0, 4) message_bank = [] if users_with_progress > 0: if users_with_progress > 1: feedback_message = "Hi %s, " % first_name feedback_message = feedback_message + "these are the people who got new badges last week, %s. If you and your %s work harder this week then you can also attain a new higher badge. To progrees on a new badge you need to login to the app every day and motivate your %s to walk more steps in each day" % ( users_with_progress_str, beneficiary_relations[posn], beneficiary_relations[posn]) else: feedback_message = "Hi %s, " % first_name feedback_message = feedback_message + "this is the only person who got a new badge last week, %s. If you and your %s work harder this week then you can also attain a new higher badge. To progrees on a new badge you need to login to the app every day and motivate your %s to walk more steps in each day" % ( users_with_progress_str, beneficiary_relations[posn], beneficiary_relations[posn]) message_bank.append(feedback_message) # select one message out of six messages NB: There one additional message from this if statement num = randint(0, 5) feedback_message = "Hey %s " % first_name feedback_message = feedback_message + "your team has not been promoted to a new badge for the past seven days. You and your %s need to work harder to progress to higher badges. You can only obtain higher badges if you keep on using the app everyday and motivate your %s to walk more steps everyday." % ( beneficiary_relations[posn], beneficiary_relations[posn]) message_bank.append(feedback_message) feedback_message = "Hallo %s " % first_name feedback_message = feedback_message + "your team has not progressed to a higher badge for a while. This week you have another chance to progress. You and your %s need to work harder to progress to higher badges. You can only obtain higher badges if you keep on using the app everyday and motivate your %s to walk more steps everyday." % ( beneficiary_relations[posn], beneficiary_relations[posn]) message_bank.append(feedback_message) feedback_message = "Molo %s " % first_name feedback_message = feedback_message + " Your team never got any new badge for the all of last week. You and your %s can attain new higher badges if you keep on using the app everyday and motivate your %s to walk more steps everyday. Log on the app now to check your current badge" % ( beneficiary_relations[posn], beneficiary_relations[posn]) message_bank.append(feedback_message) feedback_message = "Kunjani %s ? " % first_name feedback_message = feedback_message + " It is monday again. Last week your badge never changed. It is time your team get a new badge. Keep on using the app every day and motivate your %s to walk more steps this week so that your team gets higher badges. Log on the app now to check your progress" % beneficiary_relations[ posn] message_bank.append(feedback_message) feedback_message = "Heita %s ? " % first_name feedback_message = feedback_message + " Here is another monday, the week begins. You have been on the same badge for too long. It is time for a change. Keep on using the app every day and motivate your %s to walk more steps this week so that your team gets higher badges. Log on the app now to check your progress" % beneficiary_relations[ posn] message_bank.append(feedback_message) print message_bank[num] myjson2 = { "recipient": intermediary_mobiles[posn], "message": message_bank[num] } obj = QueueFeedback(myjson2) res = obj.saveFeedbackInDB() else: # select one message out of four messages num = randint(0, 3) message_bank = [] if users_with_progress > 0: if users_with_progress > 1: feedback_message = "Hi %s. " % first_name feedback_message = feedback_message + "you are among the people who scored new badges last week.%s. Here is a another week and you have a chance to progress more.You can only obtain higher badges if you keep on using the app everyday and motivate your %s to walk more steps everyday. Login on the app to check steps walked by %s and increase your chance to score higher badges." % ( users_with_progress_str, beneficiary_relations[posn], beneficiary_relations[posn]) else: feedback_message = "Hi %s," % first_name feedback_message = feedback_message + "you are the only person to attain a new in the past seven days. Big up for that. Here is a another week and you have a chance to progress more.You can only obtain higher badges if you keep on using the app everyday and motivate your %s to walk more steps everyday. Log on the app now to check your current badge " % beneficiary_relations[ posn] # select one message out of four messages num = randint(0, 4) feedback_message = "Holaa %s, " % first_name feedback_message = feedback_message + " congratulations for achieving a new badge last week. Here is another week. You and your %s have chance to work together to progress to higher badges. You can only obtain higher badges if you keep on using the app everyday and motivate your %s to walk more steps everyday. Log on the app now to check your current badge" % ( beneficiary_relations[posn], beneficiary_relations[posn]) message_bank.append(feedback_message) feedback_message = "Molo %s, " % first_name feedback_message = feedback_message + " big up for getting a new badge last week. It is the begining of a new week. You and your %s can attain higher badges if you keep on using the app everyday and motivate your %s to walk more steps everyday. Log on the app now to check your current badge" % ( beneficiary_relations[posn], beneficiary_relations[posn]) message_bank.append(feedback_message) feedback_message = "Kunjani %s ? " % first_name feedback_message = feedback_message + "Kudos for achieving a new badge in the last week. It is another monday again. Keep on using the app every day and motivate your %s to walk more steps this week so that your team gets higher badges. Log on the app now to check your progress" % ( beneficiary_relations[posn]) message_bank.append(feedback_message) feedback_message = "Heita %s ? " % first_name feedback_message = feedback_message + "last week you nailed it by geting a new badge. Here is another monday, the week begins. Keep on using the app every day and motivate your %s to walk more steps this week so that your team gets higher badges. Log on the app now to check your progress" % ( beneficiary_relations[posn]) message_bank.append(feedback_message) myjson2 = { "recipient": intermediary_mobiles[posn], "message": message_bank[num] } obj = QueueFeedback(myjson2) res = obj.saveFeedbackInDB() ''' try: old_badge="" #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) engine=db # create a Session Session = sessionmaker(bind=engine) session = Session() res=session.query(Badges).filter(Badges.badgename==badges[posn]).first() if res ==None: rank=0 else: old_badge=res.badgename rank=res.rank first_name=intermediary_names[posn][0:(intermediary_names[posn].index(' ')+1)] # #new_attained_badge #first get the current badge of this res=session.query(AttainedUserBadges).filter(AttainedUserBadges.intermediary_id==orig_email).filter(AttainedUserBadges.status==1).first() if res is None: #first promotion #insert a new badge into the database new_attained_badge=AttainedUserBadges(orig_email,datetime.date.today(),rank) session.add(new_attained_badge) session.commit()# Commit this transaction #first_name=intermediary_names[posn][0:(intermediary_names[posn].index(' ')+1)] # print "First Promotion" feedback_message="Hey %s "%first_name feedback_message=feedback_message+"your team's first badge is %s . You and your %s need to work harder to progress to higher badges. You can only obtain higher badges if you keep on using the app everyday and motivate your %s to walk more steps everyday."%(badges[posn],beneficiary_relations[posn],beneficiary_relations[posn]) myjson2={"recipient":intermediary_mobiles[posn],"message":feedback_message} obj=QueueFeedback(myjson2) res=obj.saveFeedbackInDB() else: #check if the current badge rank is less than the new badge rank if rank<res.badge_id: #promote to new higher badge res.status=0# make the current badge obsolete session.commit() session = Session()#create a new session #insert a new badge into the database new_attained_badge=AttainedUserBadges(orig_email,datetime.date.today(),rank) session.add(new_attained_badge) session.commit()# Commit this transaction print "Promoted to new rank" feedback_message="Hey %s "%first_name feedback_message=feedback_message+"your team has been promoted to a new badge. Your old badge was %s and now your new badge is %. Keep on using your app every day and keep on motivating your %s to walk more steps so that your team can continue to shine."%(old_badge,badges[posn],beneficiary_relations[posn]) myjson2={"recipient":intermediary_mobiles[posn],"message":feedback_message} obj=QueueFeedback(myjson2) res=obj.saveFeedbackInDB() print feedback_message else: print "No new promotion" pass# no new promotion except Exception as e: print "Exception thrown: %s"%e return -1 ''' posn = posn + 1 except Exception as e: print "Exception thrown %s " % e return -1 return 1