def voter_update(): if 'voter' in session: name = request.form['name'] DOB = request.form['DOB'] address = request.form['address'] state = request.form['state'] mobile = request.form['mobile'] email = request.form['email'] aadhaar = request.form['aadhaar'] status = False new = { 'name' : name, 'DOB' : DOB, 'address' : address, 'state' : state, 'mobile' : mobile, 'email' : email, 'aadhaar' : aadhaar, 'status' : status } Voter.updateVoter({'username':session['voter']}, {'$set': new}) flash('Profile updated successfully', 'info') return redirect(url_for('profile')) else: flash('You need to Login first!', 'warning') return redirect(url_for('login'))
def __init__(self, user, postingKey): self.steem = Steem(keys=[postingKey], nodes=steemd_nodes) self.user = user self.voter = Voter(self.steem, user) self.last_update_duration = 0 super().__init__(None) self.daemon = True
def approvedVoter(voterID): if 'admin' in session: Voter.updateVoter({'_id':ObjectId(voterID)}, {'$set':{'status':True}}) flash('Voter approved', 'success') return redirect(url_for('approveVoter')) else: flash('You need to Login first!', 'warning') return redirect(url_for('admin'))
def setUp(self) -> None: num_routes = 7 routes = ['r{}'.format(i) for i in range(1, num_routes + 1)] self.test_election = ElectionResult( routes, [ Voter('Ike', ['r1', 'r6', 'r2', 'r3', 'r5', 'r4', 'r7']), Voter('Jochem', ['r3', 'r4', 'r6', 'r1', 'r2', 'r7', 'r5']), Voter('Jesse', ['r2', 'r1', 'r5', 'r3', 'r4', 'r7', 'r6']), Voter('Piotr', ['r3', 'r5', 'r2', 'r4', 'r7', 'r1', 'r6']), Voter('Melina', ['r4', 'r1', 'r5', 'r6', 'r3', 'r2', 'r7']), ] )
def submit_vote(): message = 'Success!' try: t = ClientTallier(random.choice(tallier_endpoints)) voter = Voter(session['username'], r, t, e) success = voter.vote(request.form['evote'], json.loads(request.form['proof'])) if not success: message = "Something went wrong, please try again" except Exception: message = 'Something went wrong, please try again' return message
def voter_register(): username = request.form['username'] password = request.form['password'] voter = Voter.getVoter({'username': username}) if voter is None: voter = Voter(username=username, password=password) voter.addVoter() session['voter'] = username return redirect(url_for('home')) else: return redirect(url_for('login'))
def voter_register(): username = request.form['username'] password = request.form['password'] voter = Voter.getVoter({'username':username}) if voter is None: voter = Voter(username = username, password = password) voter.addVoter() session['voter'] = username flash('Registration successful. Update profile', 'info') return redirect(url_for('home')) else: flash('You need to Login first!', 'warning') return redirect(url_for('login'))
def election_result_from_file(filename: str): with open(filename, newline='') as csvFile: data_list = list(csv.DictReader(csvFile)) # simplify the route names old_keys = list(data_list[0].keys()) new_keys = old_keys.copy() for i, key in enumerate(new_keys): new_keys[i] = key.replace('Which route would you prefer? Pick an order in which you prefer routes. ' 'MAKE SURE THAT YOU RANK ALL ROUTES AT DIFFERENT PRIORITIES. ', '') routes = new_keys[2:] # update all keys (=questions) for the enquete answers for row in data_list: for i in range(len(new_keys)): row[new_keys[i]] = row.pop(old_keys[i]) voters = [] for row in data_list: name = row['What is your name?'] ranking = ['']*12 for route in row: if route == 'Tijdstempel' or route == 'What is your name?' : continue route_index = int(row[route][:-7]) - 1 ranking[route_index] = route if has_empty_element(ranking): raise Exception("Input is wrong or interpretation is wrong. Ranking of voter {} has empty element." .format(name)) voter = Voter(name, ranking) voters.append(voter) return ElectionResult(routes, voters)
def approveVoter(): if 'admin' in session: voters = Voter.getVoters({'status':False}) return render_template('approveVoter.html', Voters=voters) else: flash('You need to Login first!', 'warning') return redirect(url_for('admin'))
def vote(electionID, candidateID): if 'voter' in session: voter = Voter.getVoter({'username': session['voter']}) election = Election.getElection({'_id': ObjectId(electionID)}) if election['date'].date() > datetime.datetime.now().date(): flash(f"Election not yet started. Come back on {election['date'].date()}", 'danger') elif election['date'].date() < datetime.datetime.now().date(): flash(f"Election ended on {election['date'].date()}", 'danger') elif election['date'].date() == datetime.datetime.now().date(): if str(datetime.datetime.now().time())[:5] > election['starttime'] and str(datetime.datetime.now().time())[:5] < election['endtime']: flash('Vote recorded successfully', 'success') vote = { 'timestamp': str(datetime.datetime.now()), 'electionID': electionID, 'candidateID': candidateID, 'voter': str(voter['_id']) } response = Blockchain.add_transaction(vote) flash(response, 'info') else: flash(f"You can vote between {election['starttime']} to {election['endtime']}", 'info') return redirect(url_for('home')) else: flash('You need to Login first!', 'warning') return redirect(url_for('login'))
def generate_voter_instances(self, submissions): all_voters = [] for submission in submissions: voter_data = self.client.get_submission_details(submission) voter = Voter(voter_data['first_name'], voter_data['last_name'], voter_data['views'], voter_data['submission_id']) all_voters.append(voter) return all_voters
def profile(): if 'voter' in session: username = session['voter'] voter = Voter.getVoter({'username': username}) return render_template('profile.html', Voter=voter) else: return redirect(url_for('login'))
def register(min_age = 18,city= 'New Brunswick',state= 'NJ') -> None: print('---------Voter Registration---------\n') first_name = input("Enter First Name: ").upper() last_name = input("Enter Last Name: ").upper() dob = get_dob() age = (datetime.date.today() - dob).days/365 print(age) if age < min_age: print("Too Young to Register") return address = get_address() #FOR now voter id will just be a numbering system with open('voterid.txt','r') as file: voter_id = int(file.readline()) voter_id += 1 with open('voterid.txt','w') as file: file.write(str(voter_id)) registered_voter = Voter(voter_id,first_name,last_name,dob,address) with open('voters.csv','a') as file: writer = csv.writer(file, delimiter = ',') writer.writerow([str(voter_id),repr(registered_voter)])
def populate_from_spreadsheet(self, input_file_name): """ Grab voter data from the given spreadsheet (prepared by create_spreadsheet_from_voter_dictionary in create-voter-spreadsheet.py) and populate the Contest with the relevant Voters and Entries. """ if self.verbose: print(f"Populating contest with voter data from {input_file_name}...", end="", flush=True) with open(input_file_name, "r", newline="") as spreadsheet: reader = csv.reader(spreadsheet, delimiter=",") header = next(reader) entry_names = header[1:] # If there n Entries, each voter can assign at most n distinct rankings. # (Really the number of Entries may be more than the number of distinct rankings. # For example, a poll could ask users to vote for the top 3 Entries out of 10. # It's fine to overestimate the number of distinct rankings though. It'll just lead to # some wasted space in each Voter, which doesn't really matter.) num_distinct_rankings = len(entry_names) # construct Entries for entry_name in entry_names: # self.entries[i] contains the entry from column i+1 # (not column i because the leftmost column contains user info, not entry info) self.entries.append(Entry(entry_name)) # construct Voters and record their votes for row in reader: voter_name = row[0] # voter_rankings[i] contains the voter's ranking for entry self.entries[i] voter_rankings = row[1:] voter = Voter(voter_name, num_distinct_rankings) for i, ranking in enumerate(voter_rankings): if ranking: # the ranks are stored in user_rankings as a list of strings, so cast them # to ints for use as indexes voter.rank(self.entries[i], int(ranking)) self.voters.append(voter) if self.verbose: print(" done.")
def profile(): if 'voter' in session: username = session['voter'] voter = Voter.getVoter({'username':username}) return render_template('profile.html',Voter = voter) else: flash('You need to Login first!', 'warning') return redirect(url_for('login'))
def home(): if 'voter' in session: username = session['voter'] voter = Voter.getVoter({'username':username}) elections = Election.getElections() return render_template('home.html', Voter = voter, Elections = elections) else: flash('You need to Login first!', 'warning') return redirect(url_for('login'))
def create_voters_from_input_data(): rows = load_csv(URL_INPUT_CSV) if rows is None: return for row in rows: input_voter_list.append( Voter(row['row'], row['name'], row['birth_year'], row['address'], row['city'], row['state'], row['zip'])) return input_voter_list
class Curangel(Thread): def __init__(self, user, postingKey): self.steem = Steem(keys=[postingKey], nodes=steemd_nodes) self.user = user self.voter = Voter(self.steem, user) self.last_update_duration = 0 super().__init__(None) self.daemon = True def wait_for_recharge(self): while True: current_vp = self.voter.get_current_vp() if current_vp >= 9990: return else: t = "voting power at {:0.2f}%; " t += "estimated 100% in {}.\n" t += "waking up in {:0.3f}s." recharge_time = self.voter.get_recharge_time() sleep_s = recharge_time.total_seconds() if sleep_s > 0: print( t.format(current_vp / 100, str(recharge_time), sleep_s)) sleep(min([sleep_s, MONITOR_INTERVAL_SEC])) else: return def run(self): while True: try: self.wait_for_recharge() uri, id = self.voter.next_in_queue(self.steem) if uri is False: print("\nqueue is empty. Sleeping for a minute.") sleep(60) else: self.voter.vote(uri, id) except Exception: # log exception, sleep 10 seconds and retry print(format_exc()) sleep(10) print("\nretrying after exception...") pass
def fake_voter(self): fake = Faker('es_MX') select = ( "SELECT electoral_key FROM user ORDER BY electoral_key DESC LIMIT 70" ) self.cursor.execute(select) result = self.cursor.fetchall() for row in result: create_voter = Voter(self.connection, self.cursor) electoral_key = row[0] name = fake.first_name() middle_name = fake.first_name() flastname = fake.last_name() mlastname = fake.last_name() address = fake.simple_profile(sex=None)['address'] birth_date = fake.simple_profile(sex=None)['birthdate'] create_voter.create(electoral_key, name, middle_name, flastname, mlastname, address, birth_date) return ("OK")
def voter_authenticate(): username = request.form['username'] password = request.form['password'] voter = Voter.getVoter({'username': username, 'password': password}) if voter is None: session.pop('voter', None) return redirect(url_for('login')) else: session['voter'] = username return redirect(url_for('home'))
def _convert_dataset_into_id2voter(cls, dataset, possible_indecision_levels): """ Convert a Dataset object into a id2voter """ voter_id_count = 0 id2voter = dict() for strict, count in zip(dataset.preferences, dataset.counts): for _ in range(count): partial = PartialOrder.generate_from_strict( strict, np.random.choice(possible_indecision_levels)) voter = Voter(partial, strict) id2voter[voter_id_count] = voter voter_id_count += 1 return id2voter
def voter_authenticate(): username = request.form['username'] password = request.form['password'] voter = Voter.getVoter({'username':username,'password':password}) if voter is None: session.pop('voter', None) flash('Username or Password is wrong! Try Again', 'danger') return redirect(url_for('login')) else: session['voter'] = username flash('Login successful', 'success') return redirect(url_for('home'))
def voter_update(): name = request.form['name'] DOB = request.form['DOB'] address = request.form['address'] state = request.form['state'] constituency = request.form['constituency'] mobile = request.form['mobile'] email = request.form['email'] aadhaar = request.form['aadhaar'] status = False new = { 'name': name, 'DOB': DOB, 'address': address, 'state': state, 'constituency': constituency, 'mobile': mobile, 'email': email, 'aadhaar': aadhaar, 'status': status } Voter.updateVoter({'username': session['voter']}, {'$set': new}) return redirect(url_for('profile'))
class add_voter(): def __init__(self, Voter_id): self.key = hashlib.sha256(Voter_id.encode('utf-8')).hexdigest() self.voter = Voter(self.key) def disp(self): return self.voter.disp() def get_key(self): return self.voter.public_key def verify(self): if self.voter.amount == 0: return True else: return False
def create_voter(self): print 'Alright, let\'s create a voter' first_name = raw_input('What is the voter\'s first name?').lower().capitalize() last_name = raw_input('Ok, what is the voter\'s last name?').lower().capitalize() print 'For this survey, please select one of the following views:' for view in self.VALID_VIEWS: print view views = raw_input().lower().capitalize() voter = Voter(first_name, last_name, views) response = self.submit_vote(first_name, last_name, views) if response == 200: print 'Submitting your survey. Please wait...' self.submissions_list = self.client.get_submissions_list() self.voters = self.generate_voter_instances(self.submissions_list) print 'Survey was submitted successfully' else: print 'There was an error submitting your survey, please try again later.' return
def add_voter(): try: if (request.args.get('fetch_user') == "true"): data = request.get_json() voter_list = voters.get_all_voters() voter_list = [ x for x in voter_list if (x.firstName == data.get("firstName") and x.lastName == data.get("lastName") and x.ssn == data.get("ssn") and x.birthdate == datetime.date( *[int(num) for num in data['birthdate'].split("-")])) ] if len(voter_list) > 1: abort(500, "There was an internal issue: csp500") elif len(voter_list) < 1: abort(400, "Voter has not yet registered.") else: voter = voter_list[0] return jsonify({ "status": "registered", "voter_id": voter.id, "firstName": voter.firstName, "lastName": voter.lastName, "birthdate": voter.birthdate }) else: data = Voter.make_voter(request.get_json()) data = voters.add_voter(data) response = jsonify({ "status": "registered", "voter_id": data.id, "firstName": data.firstName, "lastName": data.lastName, "birthdate": data.birthdate }) print("Added new Voter: ", response) return response except ValueError as ex: abort(400, ex) except RuleErrors.RuleException as ex: abort(403, ex) except SecurityErrors.SecurityException as ex: abort(401, ex)
def login(): form = LoginForm() #if they submitted all the necessary features of the login form if form.validate_on_submit(): cleanSSN = re.sub(r"\D", "", form.ssn.data) cleanDOB = re.sub(r"\D", "", form.dob.data) #check if the user is in the database cleanFLN = re.sub(r"[A-Za-z']", "", form.fullName.data) user = Voter.getVoter(dbManager, connection, cleanFLN) #confirm users password if user is None or not user.check_password(cleanSSN, cleanDOB): #notify user authentication did not work return not_found('Either you have already voted or the information you entered did not match any on record. If you have not yet voted, please try again.') #login_user(user) return vote_page(user) return render_template('login.html', title='Sign In', form=form)
def landing_page(): startTime = ElectionTimespan.getStartTime(dbManager, connection) endTime = ElectionTimespan.getEndTime(dbManager, connection) if not startTime or not endTime: return not_found('GENERIC ERROR') form = LoginForm() #if they submitted all the necessary features of the login form if form.validate_on_submit(): #check if the user is in the database user = Voter.getVoter(dbManager, connection, form.fullName.data) #confirm users password if user is None or not user.check_password(form.ssn.data, form.dob.data): #notify user authentication did not work return not_found('Either you have already voted or the information you entered did not match any on record. If you have not yet voted, please try again.') #login_user(user) return vote_page(user) return render_template("login.html", title='Sign In', form=form, startTime=startTime, endTime=endTime)
def registerCandidate(): if 'voter' in session: voter = Voter.getVoter({'username':session['voter']}) electionID = request.form.get('electionID') election = Election.getElection({'_id':ObjectId(electionID)}) if datetime.datetime.now() + datetime.timedelta(days=2) >= election['date']: flash("Candiate Registration is closed", 'danger') else : candidate = { 'id' : str(uuid4()).replace('-', ''), 'voterID' : voter['_id'], 'name' : voter['name'], 'slogan' : request.form['slogan'], 'representing' : request.form['representing'], 'qualification' : request.form['qualification'], 'status' : False } Election.updateElection({'_id':ObjectId(electionID)}, {'$push': {'candidates': candidate}}) flash('Your registration details as candidate are successfully recorderd', 'info') return redirect(url_for('home')) else: flash('You need to Login first!', 'warning') return redirect(url_for('login'))
def test_decide_vote_should_return_republican(self): voter = Voter('first_name', 'last_name', 'Liberal', '12345') voter.decide_vote(mocked_republican, 0.20) self.failUnless(voter.vote == 'Republican')
def test_decide_vote_should_return_democrat(self): voter = Voter('first_name', 'last_name', 'Liberal', '12345') voter.decide_vote(mocked_democrat, 0.70) self.failUnless(voter.vote == 'Democrat')
def test_decide_vote_should_return_null(self): voter = Voter('first_name', 'last_name', 'Liberal', '12345') voter.decide_vote(mocked_democrat_for_null, 0.99) self.failUnless(voter.vote == 'null')