def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, request=None): """ Generates a one-use only link for resetting password and sends to the user """ from utils.emails import send_email for user in self.users_cache: if not domain_override: current_site = Site.objects.get_current() site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override #t = loader.get_template(email_template_name) send_email( _("Password reset on %s") % site_name, '*****@*****.**', user.email, { 'email': user.email, 'domain': domain, 'site_name': site_name, 'uid': int_to_base36(user.id), 'user': user, 'token': token_generator.make_token(user), 'protocol': use_https and 'https' or 'http', }, {'plain': 'registration/email/forgot_password.txt','html': email_template_name}, )
def handle(self, *args, **options): councils = Council.objects.all() accepte_credit = get_credit() for council in councils: for event in council.events.all(): if event.sent_datetime == None and (event.event_datetime - timedelta(days=1)) < datetime.now(): if accepte_credit > 0: recipients = event.sms_recipients() sendsms(event.originator, recipients, event.message, datetime.now()) event.sent_datetime = datetime.now() event.save() accepte_credit = accepte_credit - len(recipients) else: message = 'ERROR: Accepte has not enough credit bought to send queued sms\'s. Buy credits imediately! To identify how many, run credits_left command. Then Purchase required amount. Then Manually run sms_send command again.' send_email( 'Credits Negative -- Error', '*****@*****.**', '*****@*****.**', {'message': message }, {'plain': 'elections/credits_low.txt'}, ) return False return True
def handle(self, *args, **options): councils = Council.objects.all() accepte_credit = get_credit() for council in councils: for event in council.events.all(): if event.sent_datetime == None and ( event.event_datetime - timedelta(days=1)) < datetime.now(): if accepte_credit > 0: recipients = event.sms_recipients() sendsms(event.originator, recipients, event.message, datetime.now()) event.sent_datetime = datetime.now() event.save() accepte_credit = accepte_credit - len(recipients) else: message = 'ERROR: Accepte has not enough credit bought to send queued sms\'s. Buy credits imediately! To identify how many, run credits_left command. Then Purchase required amount. Then Manually run sms_send command again.' send_email( 'Credits Negative -- Error', '*****@*****.**', '*****@*****.**', {'message': message}, {'plain': 'elections/credits_low.txt'}, ) return False return True
def register(self, request, **kwargs): email, password = kwargs['email'], kwargs['password'] if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) username = self._generate_username() new_user = RegistrationProfile.objects.create_inactive_user(username, email, password, site, send_email=False) reg_profile = RegistrationProfile.objects.get(user=new_user) send_email( _('Wiekiesjij - User Registration'), '*****@*****.**', email, {'site': site, 'activation_key': reg_profile.activation_key }, {'plain': 'registration/activation_email.txt','html': 'registration/_activation_email.html'}, ) ProfileModel = get_profile_model('visitor') ProfileModel.objects.create( first_name=kwargs['first_name'], middle_name=kwargs['middle_name'], last_name=kwargs['last_name'], user=new_user, ) signals.user_registered.send(sender=self.__class__, user=new_user, request=request) return new_user
def handle(self, *args, **options): accepte_credits = get_credit() for election_instance in ElectionInstance.objects.all(): if election_instance.modules.filter(slug='SMS').count() != 0: phone_nums = VisitorResult.objects.filter(election_instance=election_instance).exclude(telephone=None).values('telephone').distinct() for phone_num in phone_nums: if accepte_credits > 0: visitor_results = VisitorResult.objects.filter(election_instance=election_instance, telephone=phone_num['telephone']).latest() if visitor_results.sent == None: #get(election_instance=election_instance, telephone=phone_num). top_3 = visitor_results.candidate_answers.order_by('-candidates_score')[:3] message = 'Voting is tomorrow, your top three candidates were ' for candidate in top_3: message= message + str(candidate.candidate.profile.full_name()) + ', score: ' + str(candidate.candidates_score) + ' ' sendsms(election_instance.council.name[0:11], phone_num['telephone'], message, datetime.now()) visitor_results.sent = datetime.now() visitor_results.save() accepte_credits = accepte_credits - 1 else: message = 'ERROR: Accepte has not enough credit bought to send queued sms\'s. Buy credits imediately! To identify how many, run credits_left command. Then Purchase required amount. Then Manually run sms_results command again.' send_email( 'Credits Negative -- Error', '*****@*****.**', '*****@*****.**', {'message': message }, {'plain': 'elections/credits_low.txt'}, ) return False return True
def main(): try: old_followers = read_old_followers() api = connect_to_api() api_followers = handle_rate_limit(tweepy.Cursor(api.followers).items()) current_followers = format_api_followers(api_followers) save(current_followers) unfollower_ids = find_unfollowers(old_followers=old_followers, current_followers=current_followers) logger.info( f'{len(unfollower_ids)} user(s) unfollowed you {format_unfollowers(old_followers=old_followers, unfollower_ids=unfollower_ids)}' ) ids_to_unfollow = find_ids_to_unfollow(old_followers=old_followers, unfollower_ids=unfollower_ids) no_need_to_unfollow_ids = find_no_need_to_unfollow_ids( unfollower_ids=unfollower_ids, ids_to_unfollow=ids_to_unfollow) success_user_ids, error_user_ids = unfollow(api, ids_to_unfollow) send_email_with_results( success_user_ids=success_user_ids, error_user_ids=error_user_ids, no_need_to_unfollow_ids=no_need_to_unfollow_ids) except Exception as e: logger.exception(e) send_email(subject=GENERIC_ERROR, content=traceback.format_exc())
def Notify(self, prediction): if prediction['eventid'] not in self.pastNotifs: subject = f"ALFRED: NOTIFICATION : {prediction['host_short_name']} in {prediction['host_environment']}" body = f"{prediction['description']} \n" body = f"{body} {json.dumps(prediction,default=dateConverter)}" send_email(subject,body, notified_people) self.pastNotifs.append(prediction['eventid']) client.zabbix.notifications.find_one_and_update( { 'eventid' : prediction['eventid'] }, { '$set' : prediction }, upsert=True )
def startMonitoring(self, ai, delay=90, added_delay=90): print("Monitoring started !") delay = 90 lastCheckTime = int( time.time() ) - delay #init at current time -90 secs to simulate previous call and start immediately #every 90 seconds, we check for events of the past 90 + 90 seconds to - timenow -90seconds while True: timenow = int(time.time()) if timenow > lastCheckTime + delay: from_ts = lastCheckTime - added_delay to_ts = timenow - added_delay logging.warning( f"NEW REQUEST ON ZABBIX SERVER at {from_ts} : {to_ts}") #self.updateUnresolvedProblems() problems = self.getProblems(from_ts, to_ts) p = [] for problem in problems: p.append(problem.to_dict()) if len(p) > 0: #here we could check if there is a value ==0 event predictions = ai.predict(p) for prediction in predictions: db['events'].find_one_and_update( {'eventid': prediction['eventid']}, {'$set': prediction}, upsert=True) with open('./data/results.txt', 'a') as the_file: the_file.write( json.dumps(prediction, default=dateConverter) + ',\n') if prediction['proba'] > 0.50: subject = f"ALFRED Monitoring Event : high priority, we should create a ticket for this host {prediction['host_short_name']} in {prediction['host_environment']}" body = "This event has been found to have a high importance based on past data, here is a dump of the event data : \n" body = f"{body} {json.dumps(prediction,default=dateConverter)}" send_email(subject, body, notified_people) logging.warning( f"WARNING !!!!!!! We should look at this event ! {prediction['description']}, proba : {prediction['proba']}" ) logging.warning(prediction) elif prediction['proba'] > 0.02: subject = f"ALFRED Monitoring Event : medium priority, we might want to look at this host : {prediction['host_short_name']} in {prediction['host_environment']}" body = "Probability of something going wrong is higher than usual. Here is a dump of the event data: \n" body = f"{body} {json.dumps(prediction,default=dateConverter)}" send_email(subject, body, notified_people) logging.warning( f"HEY ! you might want to look at this event, probability is relelatively high on this one :" ) logging.warning(prediction) else: logging.warning( f"{prediction['time']} : Low importance event : {prediction['description']}, proba : {prediction['proba']} on host : {prediction['host_short_name']}" ) #logging.warning(prediction) lastCheckTime = timenow time.sleep(delay)
def OpenTicket(self, prediction): subject = f"ALFRED: TICKET WOULD HAVE BEEN CREATED : {prediction['host_short_name']} in {prediction['host_environment']}" body = f"{prediction['description']} \n" body = f"{body} {json.dumps(prediction,default=dateConverter)}" send_email(subject,body, notified_people) self.openedTickets.append(prediction['eventid']) client.zabbix.tickets.find_one_and_update( { 'eventid' : prediction['eventid'] }, { '$set' : prediction }, upsert=True )
def credit_left(self): total_credits = 0 phone_nums = [] if self.election_instances: for election_instance in self.election_instances.all(): dict_phones = election_instance.visitor_results.filter(election_instance=election_instance, sent=None).exclude(telephone=None).values('telephone') for dict_phone in dict_phones: if 'telephone' in dict_phone.keys(): phone_nums.append(dict_phone['telephone']) total_credits = len(set(phone_nums)) for event in self.events.all(): if event.sent_datetime == None: recipients = event.sms_recipients() total_credits = total_credits + len(recipients) #print self.name, total_credits, phone_nums credits_left = self.credit - total_credits if self.credit_warning == None: if credits_left < 500: message = self.name + ' has only ' + str(credits_left) + ' credits left.' try: send_email( _('A Councils Credit is Low'), '*****@*****.**', '*****@*****.**', {'message': message }, {'plain': 'elections/credits_low.txt'}, ) self.credit_warning = datetime.now() self.save() except: pass message = '%s has only %s credits left. Please contact us if you would like to purchase more credit. If you do not have enough pre-bought credit when a message is sent you will be charged at a higher rate for that text message.'%(self.name, str(credits_left)) try: send_email( _('Your Credit is Low'), '*****@*****.**', '*****@*****.**', {'message': message }, {'plain': 'elections/credits_low.txt'}, ) #'*****@*****.**', #'*****@*****.**', self.credit_warning = datetime.now() self.save() except: pass return credits_left
def handle_rate_limit(cursor): while True: try: yield cursor.next() except tweepy.RateLimitError: logger.error('RateLimitError, sleeping for 15 minutes...') send_email(subject=RATE_LIMIT_ERROR, content='RateLimitError, sleeping for 15 minutes...') time.sleep(15 * 60) except StopIteration: break
def send(self): """ Sends the invitation """ send_email( self.subject, '*****@*****.**', self.user_to.email, {'invitation': self}, {'html': self.html_template, 'plain': self.plain_template} ) self.send_on = datetime.datetime.now() self.save()
def credit_left(): councils_credit = 0 over_drawn = 0 for council in Council.objects.all(): if council.election_instances: councils_credit_left = council.credit_left() councils_credit = councils_credit + council.credit if councils_credit_left < 0: over_drawn = over_drawn - councils_credit_left credit_left = get_credit() margin = credit_left - councils_credit - over_drawn if margin < 0: message = ( "WARINING: Accepte has not enough credit bought. Currently Accepte has %s credits left. Councils have reserved: %s. %s credits have not been reserved. Total (Acceptes credits - reserver - non_reserved): %s" % (str(credit_left), str(councils_credit), str(over_drawn), str(margin)) ) send_email( "Credits Negative -- IMPORTANT", "*****@*****.**", "*****@*****.**", {"message": message}, {"plain": "elections/credits_low.txt"}, ) return False elif margin < 2000: message = ( "Accepte may not have enough credit bought. Currently Accepte has %s credits left. Councils have reserved: %s. %s credits have not been reserved. Total (Acceptes credits - reserver - non_reserved): %s" % (str(credit_left), str(councils_credit), str(over_drawn), str(margin)) ) send_email( "Credits Low", "*****@*****.**", "*****@*****.**", {"message": message}, {"plain": "elections/credits_low.txt"}, ) else: pass return True
def credit_left(): councils_credit = 0 over_drawn = 0 for council in Council.objects.all(): if council.election_instances: councils_credit_left = council.credit_left() councils_credit = councils_credit + council.credit if councils_credit_left < 0: over_drawn = over_drawn - councils_credit_left credit_left = get_credit() margin = credit_left - councils_credit - over_drawn if margin < 0: message = 'WARINING: Accepte has not enough credit bought. Currently Accepte has %s credits left. Councils have reserved: %s. %s credits have not been reserved. Total (Acceptes credits - reserver - non_reserved): %s' % ( str(credit_left), str(councils_credit), str(over_drawn), str(margin)) send_email( 'Credits Negative -- IMPORTANT', '*****@*****.**', '*****@*****.**', {'message': message}, {'plain': 'elections/credits_low.txt'}, ) return False elif margin < 2000: message = 'Accepte may not have enough credit bought. Currently Accepte has %s credits left. Councils have reserved: %s. %s credits have not been reserved. Total (Acceptes credits - reserver - non_reserved): %s' % ( str(credit_left), str(councils_credit), str(over_drawn), str(margin)) send_email( 'Credits Low', '*****@*****.**', '*****@*****.**', {'message': message}, {'plain': 'elections/credits_low.txt'}, ) else: pass return True
def handle(self, *args, **options): accepte_credits = get_credit() for election_instance in ElectionInstance.objects.all(): if election_instance.modules.filter(slug='SMS').count() != 0: phone_nums = VisitorResult.objects.filter( election_instance=election_instance).exclude( telephone=None).values('telephone').distinct() for phone_num in phone_nums: if accepte_credits > 0: visitor_results = VisitorResult.objects.filter( election_instance=election_instance, telephone=phone_num['telephone']).latest() if visitor_results.sent == None: #get(election_instance=election_instance, telephone=phone_num). top_3 = visitor_results.candidate_answers.order_by( '-candidates_score')[:3] message = 'Voting is tomorrow, your top three candidates were ' for candidate in top_3: message = message + str( candidate.candidate.profile.full_name( )) + ', score: ' + str( candidate.candidates_score) + ' ' sendsms(election_instance.council.name[0:11], phone_num['telephone'], message, datetime.now()) visitor_results.sent = datetime.now() visitor_results.save() accepte_credits = accepte_credits - 1 else: message = 'ERROR: Accepte has not enough credit bought to send queued sms\'s. Buy credits imediately! To identify how many, run credits_left command. Then Purchase required amount. Then Manually run sms_results command again.' send_email( 'Credits Negative -- Error', '*****@*****.**', '*****@*****.**', {'message': message}, {'plain': 'elections/credits_low.txt'}, ) return False return True
def register(self, request, **kwargs): email, password = kwargs['email'], kwargs['password'] if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) username = self._generate_username() new_user = RegistrationProfile.objects.create_inactive_user( username, email, password, site, send_email=False) reg_profile = RegistrationProfile.objects.get(user=new_user) send_email( _('Wiekiesjij - User Registration'), '*****@*****.**', email, { 'site': site, 'activation_key': reg_profile.activation_key }, { 'plain': 'registration/activation_email.txt', 'html': 'registration/_activation_email.html' }, ) ProfileModel = get_profile_model('visitor') ProfileModel.objects.create( first_name=kwargs['first_name'], middle_name=kwargs['middle_name'], last_name=kwargs['last_name'], user=new_user, ) signals.user_registered.send(sender=self.__class__, user=new_user, request=request) return new_user
def send_transfer_email(transfer): if not transfer.email: return data = { 'sender': { 'id': transfer.sender_id }, 'receiver': { 'email': transfer.email, }, 'amount': int(transfer.amount), 'created': transfer.created.strftime('%d.%m.%Y'), 'sender_title': transfer.sender_title, 'signup_url': transfer.signup_url, 'login_url': transfer.login_url } if transfer.sender_remote_user: data['sender']['name'] = transfer.sender_remote_user.get_full_name() data['sender']['avatar'] = transfer.sender_remote_user.get_avatar() data['sender']['url'] = transfer.sender_remote_user.get_absolute_url() if (transfer.backend == 'email' or transfer.backend == 'ppuser') and \ transfer.receiver_remote_user: data['receiver']['name'] = transfer.receiver_remote_user\ .get_full_name() data['receiver']['url'] = transfer.receiver_remote_user\ .get_absolute_url() if transfer.backend == 'ppuser' and transfer.receiver_remote_contact: name = transfer.receiver_remote_contact.get_full_name() if name != data['receiver']['email']: data['receiver']['name'] = name if transfer.receiver_remote_contact.target: data['receiver']['url'] = transfer.receiver_remote_contact\ .target.get_absolute_url() send_email(transfer.email, 'email_ums_send', data)
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, request=None): """ Generates a one-use only link for resetting password and sends to the user """ from utils.emails import send_email for user in self.users_cache: if not domain_override: current_site = Site.objects.get_current() site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override #t = loader.get_template(email_template_name) send_email( _("Password reset on %s") % site_name, '*****@*****.**', user.email, { 'email': user.email, 'domain': domain, 'site_name': site_name, 'uid': int_to_base36(user.id), 'user': user, 'token': token_generator.make_token(user), 'protocol': use_https and 'https' or 'http', }, { 'plain': 'registration/email/forgot_password.txt', 'html': email_template_name }, )
def credit_left(self): total_credits = 0 phone_nums = [] if self.election_instances: for election_instance in self.election_instances.all(): dict_phones = ( election_instance.visitor_results.filter(election_instance=election_instance, sent=None) .exclude(telephone=None) .values("telephone") ) for dict_phone in dict_phones: if "telephone" in dict_phone.keys(): phone_nums.append(dict_phone["telephone"]) total_credits = len(set(phone_nums)) for event in self.events.all(): if event.sent_datetime == None: recipients = event.sms_recipients() total_credits = total_credits + len(recipients) # print self.name, total_credits, phone_nums credits_left = self.credit - total_credits if self.credit_warning == None: if credits_left < 500: message = self.name + " has only " + str(credits_left) + " credits left." try: send_email( _("A Councils Credit is Low"), "*****@*****.**", "*****@*****.**", {"message": message}, {"plain": "elections/credits_low.txt"}, ) self.credit_warning = datetime.now() self.save() except: pass message = ( "%s has only %s credits left. Please contact us if you would like to purchase more credit. If you do not have enough pre-bought credit when a message is sent you will be charged at a higher rate for that text message." % (self.name, str(credits_left)) ) try: send_email( _("Your Credit is Low"), "*****@*****.**", "*****@*****.**", {"message": message}, {"plain": "elections/credits_low.txt"}, ) #'*****@*****.**', #'*****@*****.**', self.credit_warning = datetime.now() self.save() except: pass return credits_left
def CloseTicket(self, prediction): if prediction['eventid'] in self.openedTickets: subject = f"ALFRED: TICKET WOULD HAVE BEEN Closed ! : {prediction['host_short_name']} in {prediction['host_environment']}" body = f"{prediction['description']} \n" body = f"{body} {json.dumps(prediction,default=dateConverter)}" send_email(subject,body, notified_people)
def done(self, request, form_dict): num_weighted_questions = 0 num_questions = 0 real_score = 0 candidate_scores = {} candidate_question_answers = {} self.multiply_questions = [] candidate_ids = [] questions_skipped = [] # get party-list users_of_allowed_parties = [] for path, forms in form_dict.iteritems(): for question_id, form in forms.iteritems(): num_questions = num_questions + 1 question = Question.objects.get(id=question_id) answer_value = form.cleaned_data['value'] if QTYPE_MODEL_PARTY == question.question_type: for party in answer_value: current_eip = getattr(party, 'current_eip') if current_eip is None: return Http404() candidatesOnList = current_eip.candidate_dict() for id, candidateOnList in candidatesOnList.iteritems(): if candidateOnList: users_of_allowed_parties.append(candidateOnList.candidate_id) users = User.objects.filter(pk__in=users_of_allowed_parties) candidateSelection = PoliticianProfile.objects.filter(user__in=users).order_by('?') # get list of candidate ids and create a dictionay entry for each candidate to keep array of scores for candidate in candidateSelection: candidate_scores[candidate] = [] candidate_ids.append(candidate.id) # get a list of answers that each candidate has chosen and store them in a dictionary for candidate in self.elections_candidacies: candidate_question_answers[candidate.candidate.profile] = {} question_answers = candidate.answers.all() for question_answer in question_answers: if question_answer.question_id in candidate_question_answers[candidate.candidate.profile].keys(): candidate_question_answers[candidate.candidate.profile][question_answer.question_id].append(question_answer.id) else: answer_list = [] answer_list.append(question_answer.id) candidate_question_answers[candidate.candidate.profile][question_answer.question_id] = answer_list #Create a full list of candidate answers for storage all_candidate_answers = copy.deepcopy(candidate_question_answers) all_visitor_answers = {} all_questions = [] for path, forms in form_dict.iteritems(): for question_id, form in forms.iteritems(): question = Question.objects.get(id=question_id) if len(question.question_type) > 1 and question.question_type[1] == 'S': continue num_questions = num_questions + 1 all_questions.append(question) answer_value = form.cleaned_data['value'] empty_list = [] # checks if the answer is will be returned in a list, make into a list if not if question.question_type not in MULTIPLE_ANSWER_TYPES: empty_list.append(answer_value) answer_value = empty_list else: answer_value = list(answer_value) #all_visitor_answers[question_id] = answer_value #if no preference is selected question is ignored if 'no_pref' in answer_value: all_visitor_answers[question_id] = answer_value questions_skipped.append(question_id) continue # Get length of the list to help calculate score length = len(answer_value) if question.question_type in BACKOFFICE_QUESTION_TYPES: all_visitor_answers[question_id] = answer_value for candidate in candidateSelection: keys = candidate_question_answers[candidate].keys() question_id = int(question_id) score = 0 if question_id in keys: for value in answer_value: if question.question_type == QTYPE_NORM_POLONECHOICE_VISONECHOICE_RANGE: answer = Answer.objects.get(id=value) politicians_answer = Answer.objects.get(id=int(candidate_question_answers[candidate][int(question_id)][0]) ) if int(politicians_answer.meta) >= int(answer.meta): score = 1 else: if int(value) in candidate_question_answers[candidate][int(question_id)]: score = score + 1 if score > 0: new_score = float(float(score) / float(len(candidate_question_answers[candidate][int(question_id)]))) else: new_score = 0 candidate_scores[candidate].append({question.id: new_score}) elif QTYPE_MODEL_PARTY == question.question_type: party_names = [value.name for value in answer_value] for candidate in candidateSelection: all_candidate_answers[candidate][question_id] = candidate.party().id all_visitor_answers[question_id] = party_names elif QTYPE_MODEL_POLITICAL_EXPERIENCE_YEARS == question.question_type: all_visitor_answers[question_id] = answer_value answer = Answer.objects.get(id=answer_value[0]) parts = answer.meta.split(':') start = parts[0] if len(parts) > 1: end= parts[1] else: end = int(parts[0]) + 1 if end == 'G': for candidate in candidateSelection: if candidate.political_experience_days == None: candidate.political_experience_days = 0 if (int(candidate.political_experience_days)/365) >= int(start): candidate_scores[candidate].append({question.id: 1}) all_candidate_answers[candidate][question_id] = (int(candidate.political_experience_days)/365) else: for candidate in candidateSelection: # need to subtract one form the end figure as 'to' is up to but not equal if candidate.political_experience_days == None: candidate.political_experience_days = 0 if (int(candidate.political_experience_days)/365) in range(int(start),(int(end))): candidate_scores[candidate].append({question.id: 1}) all_candidate_answers[candidate][question_id] = (int(candidate.political_experience_days)/365) elif QTYPE_MODEL_EDUCATION_LEVEL == question.question_type: answer = Answer.objects.get(id=answer_value[0]) answer_value= answer.meta if answer_value == 'ALL_OTHERS': exclude_list = ['HBO', 'MBO', 'Universitair'] levels = EducationLevel.objects.exclude(level__in=exclude_list) else: levels = EducationLevel.objects.filter(level=answer_value) # Check all levels that the politican can be in to be a match level_names = [] for level in levels: level_names.append(level.level) #get all the education levels that have a level in the correct level list ed_instances =Education.objects.filter(level=level.id) for ed in ed_instances: #if the education is of a candidate of this match if ed.politician_id in candidate_ids: #get the politician candidate = PoliticianProfile.objects.get(id=ed.politician_id) #Add level to all_candidate_answers if question_id in all_candidate_answers[candidate].keys(): all_candidate_answers[candidate][question_id].append(ed.level.level) else: all_candidate_answers[candidate][question_id] = [] all_candidate_answers[candidate][question_id].append(ed.level.level) answered = False for question_answer in candidate_scores[candidate]: if question.id in question_answer.keys(): answered = True if answered == False: candidate_scores[candidate].append({question.id: 1}) all_visitor_answers[question_id] = level_names elif QTYPE_MODEL_PROFILE_RELIGION == question.question_type: all_visitor_answers[question_id] = answer_value for value in answer_value: for candidate in candidateSelection.all(): all_candidate_answers[candidate][question_id] = candidate.religion if candidate.religion == value: candidate_scores[candidate].append({question.id: 1}) elif QTYPE_MODEL_PROFILE_AGE == question.question_type: all_visitor_answers[question_id] = answer_value answer = Answer.objects.get(id=answer_value[0]) parts = answer.meta.split(':') start = parts[0] if len(parts) > 1: end=parts[1] if end == '': for candidate in candidateSelection: if candidate.age >= int(start): candidate_scores[candidate].append({question.id: 1}) all_candidate_answers[candidate][question_id] = candidate.age elif start == '': for candidate in candidateSelection: if candidate.age < int(end): candidate_scores[candidate].append({question.id: 1}) all_candidate_answers[candidate][question_id] = candidate.age else: for candidate in candidateSelection: if candidate.age in range(int(start),int(end)): candidate_scores[candidate].append({question.id: 1}) all_candidate_answers[candidate][question_id] = candidate.age elif QTYPE_MODEL_PROFILE_GENDER == question.question_type: all_visitor_answers[question_id] = answer_value for candidate in candidateSelection: if candidate.gender == answer_value[0]: candidate_scores[candidate].append({question.id: 1}) all_candidate_answers[candidate][question_id] = candidate.gender elif QTYPE_MODEL_PROFILE_QUESTION_WEIGHT == question.question_type: all_visitor_answers[question_id] = answer_value self.multiply_questions = answer_value[0] elif QTYPE_MODEL_WORK_EXPERIENCE_TYPE == question.question_type: all_visitor_answers[question_id] = [a.id for a in answer_value] queryset = candidateSelection.all().distinct().filter(work__sector__in=answer_value) for candidate in queryset: candidate_scores[candidate].append({question.id: 1}) all_candidate_answers[candidate][question_id] = list(set([s.sector_id for s in candidate.work.all()])) elif QTYPE_MODEL_POLITICAL_EXPERIENCE_TYPE == question.question_type: all_visitor_answers[question_id] = [a.id for a in answer_value] queryset = candidateSelection.all().distinct().filter(political__type__in=answer_value) for candidate in queryset: candidate_scores[candidate].append({question.id: 1}) all_candidate_answers[candidate][question_id] = list(set([s.type_id for s in candidate.political.all()])) # fill out list with default score of 0 for each candidate, if not already there for candidate in candidateSelection: answered = False for question_answer in candidate_scores[candidate]: if question.id in question_answer.keys(): answered = True if answered == False: candidate_scores[candidate].append({question.id: 0}) #Add Weighting num_weighted_questions = 0 for question in all_questions: if str(question.id) not in questions_skipped: if question.theme in self.multiply_questions: num_weighted_questions = num_weighted_questions + 1 number_of_questions = (((num_questions - 2) + num_weighted_questions ) - len(questions_skipped)) if number_of_questions < 1: number_of_questions = 1 for candidate in candidateSelection: for question in candidate_scores[candidate]: for question_id, score in question.iteritems(): qid = question_id for q in all_questions: if qid == q.id: if q.theme in self.multiply_questions: score = score * 2 score = float(float(score * 100)/number_of_questions) question[question_id] = score else: score = float(float(score * 100)/number_of_questions) question[question_id] = score candidates_total_scores = {} for candidate in candidateSelection: total = 0 for question in candidate_scores[candidate]: for question_id, score in question.iteritems(): total = float(total + score) #candidates_total_scores[candidate] = ceil(total) if total > 99 and settings.DEBUG == False: if int(total) > 100: real_score = total total = 100 if settings.DEBUG and total < 100 and total > 99: total = 100 candidates_total_scores[candidate] = total visitor = VisitorResult() new_visitor = visitor.create() new_visitor.ipaddress=getip(request) new_visitor.election_instance = self.election_instance # Only link visitors if request.user.is_authenticated() and request.user.profile and request.user.profile.type == 'visitor': new_visitor.user = request.user new_visitor.visitor_answers = json.dumps(all_visitor_answers) new_visitor.save() sorted_candidates = [(k, candidates_total_scores[k]) for k in candidates_total_scores.keys()] random.seed() random.shuffle(sorted_candidates) sorted_candidates = sorted(sorted_candidates, key=itemgetter(1), reverse=True) for candidate, score in sorted_candidates[:5]: candidate_ans = CandidateAnswers() candidate_ans.candidate = candidate.user candidate_ans.candidate_answers = json.dumps(all_candidate_answers[candidate]) candidate_ans.candidates_score = candidates_total_scores[candidate] candidate_ans.candidate_question_scores = json.dumps(candidate_scores[candidate]) candidate_ans.save() new_visitor.candidate_answers.add(candidate_ans) if real_score > 0: try: send_email( 'Error: score more than 100 in results', '*****@*****.**', '*****@*****.**', {'hash': new_visitor.hash, 'real_score': real_score}, {'plain': 'questions/score_error.txt'}, ) except: pass if self.iframe: return redirect('fo.match_results', hash=new_visitor, iframe=self.iframe) else: return redirect('fo.match_results', hash=new_visitor)