def test_filtered_list(session): c = Candidate() c.id = 1 session.add(c) session.commit() query = Algorithm.filtered_list_of_table_objects(Candidate, [1]) assert type(c) == type(query[0])
def new_candidate(id): if request.method == "POST": if not "image" in request.files: return "no image found", 400 file = request.files["image"] if not file: return "no image found", 400 image = face_recognition.load_image_file(file) encodings = face_recognition.face_encodings(image) if (len(encodings) != 1): return str( len(encodings)) + " faces found. But required only 1 face", 400 user = User.query.get(id) if not user: return "invalid user", 400 candidate = Candidate() candidate.name = request.form.get("name", type=str) candidate.encoding = encodings[0] candidate.user = user db.session.add(candidate) db.session.commit() return "created", 201 return render_template("new_candidate.html", id=id)
def test_candidate_repr(self): """ Test candidate representation """ cand = Candidate() self.assertEqual( cand.__repr__(), '{"Candidate" : {"name": None, "dob": None, "job": None, "poll": None, ' '"contact": None, "states": None, "party": None, "election": None}}' )
def test_deferred_candidates_are_not_counted(self, test_session, candidates_promoter): """ Two candidates apply to the 2019 intake and are successful. One defers to 2019. Both are promoted in the following year. How many "successes" should be counted for the programme? The answer should be one, because only one is actually on the programme at the time """ test_session.add(Ethnicity(id=4, value="Prefer not to say")) test_session.commit() candidates = [Candidate(ethnicity_id=4) for i in range(2)] # all candidates apply for the 2019 intake and are successful for candidate in candidates: candidate.applications.append( Application( scheme_id=1, application_date=date(2018, 6, 1), scheme_start_date=date(2019, 3, 1), successful=True, )) # all candidates are substantively promoted candidates_promoter(candidates, 1, temporary=False) # one candidate defers to the 2020 intake candidates[0].applications[0].defer(date_to_defer_to=date(2020, 3, 1)) # save to the database test_session.add_all(candidates) test_session.commit() data = CharacteristicPromotionReport("FLS", "2019", "ethnicity").get_data() expected_output = ["Prefer not to say", 1, 1.0, 0, 0.0, 1] assert data[0] == expected_output
def row_writer(self, candidate: Candidate) -> List: application = candidate.most_recent_application() current_role: Role = candidate.roles[0] return [ f"{candidate.first_name} {candidate.last_name}", candidate.email_address, application.cohort, application.offer_status(), current_role.role_name, current_role.grade.value, current_role.location.value, current_role.organisation.name, candidate.joining_date, candidate.joining_grade.value, candidate.completed_fast_stream, candidate.ethnicity.value, candidate.ethnicity.bame, candidate.long_term_health_condition, candidate.main_job_type.lower_socio_economic_background, candidate.gender.value, candidate.sexuality.value, candidate.caring_responsibility, candidate.age_range.value, candidate.belief.value, candidate.working_pattern.value, f"localhost:5000/candidates/candidate/{candidate.id}", ]
def create_app(): app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///hire.db' api.init_app(app) db.init_app(app) with app.app_context(): db.create_all() cand = Candidate(firstname='Harry', middlename='Ian', lastname='Laurenceau', city='Chicago', state='MD') db.session.add(cand) db.session.commit() ma.init_app(app) @app.route('/health') def healthcheck(): return {'status': 'UP'} @app.route('/history/<int:id>', methods=['POST']) def add_history(id): ceh = CandidateEmploymentHistorySchema() employment_history = request.json #employment_history['startdate'] = datetime.strptime(employment_history['startdate'], '%d-%m-%Y') #employment_history['enddate'] = datetime.strptime(employment_history['enddate'], '%d-%m-%Y') c = ceh.load(employment_history) print(c, type(c.startdate)) return 'success' return app
def test_deleting_candidate(client, mockery): data = {'first_name': mockery.first_name, 'last_name': mockery.last_name} result = client.json('main.candidate_endpoint', data=data, method='DELETE') assert result['success'] assert result.get('id') == mockery.id assert not Candidate.exists(**data)
def test_delete_user_from_db(session): u = Candidate(email='*****@*****.**') session.add(u) session.commit() c = User.query.first() session.delete(c) session.commit() assert 0 == Candidate.query.count()
def register_as_candidate(): if current_user.is_authenticated: return redirect(url_for('main.index')) form = RegistrationForm() if form.validate_on_submit(): candidate = Candidate() form.populate_obj(candidate) candidate.set_password(form.password.data) db.session.add(candidate) db.session.commit() send_email_confirmation(candidate) flash( "Congratulations, you've registered successfully. Now check your email to confirm your account" ) return redirect(url_for('auth.login')) return render_template('auth/register-as-candidate.html', title='Register as a candidate', form=form)
def resume_results(): candidates = [] candidates_skills_list = [] target = os.path.join(Config.APP_ROOT, 'temp') if not os.path.isdir(target): os.mkdir(target) for file in request.files.getlist("file"): filename = file.filename destination = "\\".join([target, filename]) file.save(destination) candidate = process_candidate(path=destination) candidates.append(candidate) if candidate.skills.__len__() != 0: candidates_skills_list.extend(candidate.skills) #TODO : Write code to delete the file from the temp folder os.chmod(destination, 0o0777) os.remove(destination) _firstname = request.form['firstname'] or "Unknown" _middlename = request.form['middlename'] or "Unknown" _lastname = request.form['lastname'] or "Unknown" _email_id = request.form['email_id'] or "Unknown" _contact_number = request.form['contact_number'] or "Unknown" _skills = ','.join(candidates_skills_list) or "No skills found" ocandidate = Candidate(firstname=_firstname, middlename=_middlename, lastname=_lastname, email_id=_email_id, contact_number=_contact_number, date_added=datetime.datetime.now(), last_modified=datetime.datetime.now(), skills=_skills) print(ocandidate) #TODO : Write Code here to insert the candidate into database return render_template('results.html', candidates=candidates) # @app.route('/resume_results',methods=['GET','POST']) # def resume_results(): # # skills = ['xml', 'python', 'java'] # skills = [] # _firstname = request.form['firstname'] or "Unknown" # _middlename = request.form['middlename'] or "Unknown" # _lastname = request.form['lastname'] or "Unknown" # _email_id = request.form['email_id'] or "Unknown" # _contact_number = request.form['contact_number'] or "Unknown" # _skills = ','.join(skills) or "No skills found" # print (_firstname, _middlename, _lastname, _email_id, _contact_number, _skills) # return "Working"
def mockery(): employee = Candidate(first_name='John', last_name='Doe', email='*****@*****.**', skype='john_doe') db.session.add(employee) db.session.commit() yield employee db.session.delete(employee) db.session.commit()
def draw_lottery(): json_data = request.get_json() num_winners = json_data['num_winners'] announcement_delay = json_data['announcement_delay'] cand_names = json_data['candidates'] created_at = datetime.now(timezone(timedelta(hours=9))) created_at = created_at.replace(tzinfo=None) published_at = created_at + timedelta(minutes=announcement_delay) seed = int(created_at.timestamp() * 1000) result = Result(created_at=created_at, published_at=published_at, seed=seed, drawer_ip=request.remote_addr) candidates = [Candidate(name=name, result=result) for name in cand_names] random.seed(seed) cand_indices = list(range(len(cand_names))) for _ in range(10): random.shuffle(cand_indices) winner_indices = random.sample(cand_indices, num_winners) winners = [candidates[i] for i in winner_indices] for winner in winners: winner.is_winner = True db.session.add(result) db.session.commit() winner_dicts = [] for winner in winners: winner_dict = {} winner_dict['name'] = winner.name unfair_stats_week = calculate_unfair_score(name=winner.name, days=7) unfair_stats_month = calculate_unfair_score(name=winner.name, days=30) winner_dict['unfair'] = { 'week': { 'num_tries': unfair_stats_week[0], 'num_wins': unfair_stats_week[1], 'unfair_score': unfair_stats_week[2] }, 'month': { 'num_tries': unfair_stats_month[0], 'num_wins': unfair_stats_month[1], 'unfair_score': unfair_stats_month[2] } } winner_dicts.append(winner_dict) result_url = url_for('views.show_result', result_id=result.id) return jsonify({ 'winners': winner_dicts, 'result_id': result.id, 'result_url': result_url })
def registration(): upload_file = request.files['file'] file_name = secure_filename(upload_file.filename) if file_name == '': return "No File Provided", 204 if not is_valid_file(file_name): return "Invalid File", 400 save_file(upload_file, file_name) candidate = Candidate(request.form['full_name'], request.form['birth_date'], request.form['experience_years'], request.form['department_id'], file_name) db.session.add(candidate) db.session.commit() return "Saved"
def test_eligible_candidates(self, test_session, candidates_promoter): test_session.add(Ethnicity(id=4, value="Prefer not to say")) test_session.commit() candidates = [Candidate(ethnicity_id=1) for i in range(2)] for candidate in candidates: candidate.applications.append( Application( scheme_id=1, application_date=date(2018, 6, 1), scheme_start_date=date(2019, 3, 1), )) test_session.add_all(candidates) candidates[0].applications[0].defer(date_to_defer_to=date(2020, 3, 1)) test_session.commit() data = PromotionReport("FLS", "2019").eligible_candidates() assert len(data) == 1
def mockery(): timeslots = [ Timeslot(day='Monday', hour='10', minute='0'), # 0 Timeslot(day='Monday', hour='10', minute='15'), # 1 Timeslot(day='Monday', hour='10', minute='30'), # 2 Timeslot(day='Monday', hour='10', minute='45'), # 3 Timeslot(day='Monday', hour='11', minute='0'), # 4 Timeslot(day='Monday', hour='11', minute='15'), # 5 Timeslot(day='Monday', hour='11', minute='30'), # 6 Timeslot(day='Tuesday', hour='12', minute='0'), # 7 Timeslot(day='Tuesday', hour='12', minute='15'), # 8 Timeslot(day='Tuesday', hour='12', minute='30'), # 9 Timeslot(day='Tuesday', hour='12', minute='45'), # 10 Timeslot(day='Friday', hour='14', minute='0'), # 11 Timeslot(day='Friday', hour='14', minute='15') # 12 ] employee1 = Employee( first_name='John', last_name='Doe', availability=timeslots[:7], ) employee2 = Employee(first_name='Bob', last_name='Smith', availability=timeslots[5:]) candidate = Candidate( first_name='Alice', last_name='Appleseed', email='*****@*****.**', availability=[timeslots[7], timeslots[8], timeslots[11]]) for obj in (employee1, employee2, candidate): db.session.add(obj) db.session.commit() yield employee1, employee2, candidate for obj in (employee1, employee2, candidate): db.session.delete(obj) db.session.commit()
def synchronize_chunk(csv_chunk): fec_ids = [row["fec_id"] for row in csv_chunk] existing_candidates = load_candidates(fec_ids) for row in csv_chunk: new_data = candidate_schema.load(row, unknown=EXCLUDE) if new_data["fec_id"] not in existing_candidates: print("New candidate:", new_data) db.session.add(Candidate(**new_data)) else: existing_candidate = existing_candidates[row["fec_id"]] for column in new_data: existing_val = getattr(existing_candidate, column) new_val = new_data[column] if existing_val != new_val: print( f"Updating {column} on candidate {row['fec_id']}. Old: {existing_val} New: {new_val}" ) setattr(existing_candidate, column, new_val) db.session.commit()
def create_election(): # if user is authenticated, make the owner of the election the current logged in user # if the user is not authenticated, redirect the user to the login page # form = ElectionForm() form = ElectionForm(request.form) if form.validate_on_submit(): pending_status = Status.query.get(1) random_link = uuid.uuid4() # return 'hi' election = Election(owner=current_user, name=form.name.data, date_of_election=datetime.combine( form.date_of_election.data, time()), description=form.description.data, time_of_election=form.time_of_election.data, status=pending_status, number_of_voters=form.number_of_voters.data, link=str(random_link), password=form.password.data) print(election) db.session.add(election) # create candidates for c in form.candidates.data: candidate = Candidate(election=election, name=c['name'], bio=c['description']) print(candidate) db.session.add(candidate) db.session.commit() return redirect(url_for('election', link=random_link)) return render_template("election_form.html", title="Create Election", form=form)
if __name__ == '__main__': with open(header_file, 'r') as header_file: data = header_file.read() # data = csv.reader(header_file) header = data.strip().replace('\n', '') with open(data_file, mode="r") as infile: reader = csv.reader(infile, delimiter='|') # print(list(reader)) Data = namedtuple("Data", header) # get names from column headers for data in map(Data._make, reader): cand = Candidate() cand.CAND_ID = data.CAND_ID cand.CAND_NAME = data.CAND_NAME cand.CAND_ICI = data.CAND_ICI cand.CAND_PCC = data.CAND_PCC cand.CAND_ST1 = data.CAND_ST1 cand.CAND_ST2 = data.CAND_ST2 zipcode = Zipcode.select(graph, data.CAND_ZIP).first() if not zipcode: zipcode = Zipcode() zipcode.ZIPCODE = data.CAND_ZIP graph.push(zipcode) cand.CAND_ZIP.add(zipcode)
def test_commit_session(session): u = Candidate(email='*****@*****.**') session.add(u) session.commit() assert 0 < u.id
def test_commit_to_db(session): u = Candidate(email='*****@*****.**') session.add(u) session.commit() assert 1 == Candidate.query.count()
def add_candidate_ajax(): ticker = request.form['ticker'] candidate = Candidate.query.filter_by(ticker=ticker).first() user_candidate = Candidate() user_candidate.email = current_user.email user_candidate.ticker = ticker user_candidate.reason = '' user_candidate.enabled = 1 user_candidate.company_name = candidate.company_name user_candidate.exchange = candidate.exchange user_candidate.industry = candidate.industry user_candidate.full_description = candidate.full_description user_candidate.logo = candidate.logo user_candidate.sector = candidate.sector user_candidate.exchange_short = candidate.exchange_short user_candidate.website = candidate.website user_candidate.isActivelyTrading_fmp = candidate.isActivelyTrading_fmp url = 'https://colak.eu.pythonanywhere.com/data_hub/current_stock_price_short/' + ticker context = ssl.create_default_context(cafile=certifi.where()) response = urlopen(url, context=context) data = response.read().decode("utf-8") price = json.loads(data)[0]['price'] user_candidate.price_added = price user_candidate.update_candidate() candidates = get_user_candidates() return json.dumps(candidates, cls=general.JsonEncoder)
def make_candidate(self, data, **kwargs): return Candidate(**data)
for data in map(Data._make, reader): comm = Committee() comm.CMTE_ID = data.CMTE_ID comm.CMTE_NM = data.CMTE_NM comm.TRES_NM = data.TRES_NM # Treasures name comm.CMTE_ST1 = data.CMTE_ST1 comm.CMTE_ST2 = data.CMTE_ST2 comm.CMTE_DSGN = data.CMTE_DSGN comm.CMTE_TP = data.CMTE_TP comm.CMTE_FILING_FREQ = data.CMTE_FILING_FREQ comm.ORG_TP = data.ORG_TP comm.CONNECTED_ORG_NM = data.CONNECTED_ORG_NM cand = Candidate.select(graph, data.CAND_ID).first() if not cand: cand = Candidate() cand.CAND_ID = data.CAND_ID graph.push(cand) # add edge comm.CAND_ID.add(cand) zipcode = Zipcode.select(graph, data.CMTE_ZIP).first() if not zipcode: zipcode = Zipcode() zipcode.ZIPCODE = data.CMTE_ZIP graph.push(zipcode) # add edge
def register(): schema = { "type": "object", "properties": { "username": { "type": "string" }, "email": { "type": "string" }, "password": { "type": "string" }, "first_name": { "type": "string" }, "middle_name": { "type": "string" }, "last_name": { "type": "string" } }, "required": ["username", "email", "password", "first_name", "last_name"] } data = request.get_json() try: validate(data, schema=schema) except ValidationError as e: print(e) return jsonify({ 'status': 'Failure', 'msg': 'Missing/incorrect fields: {}'.format(e) }) if (not 'username' in data or not 'email' in data or not 'password' in data): return jsonify({ 'status': 'Failure', 'msg': 'Must provide username, email, and password' }), 400 #Check if email is already in use check_candidate = Candidate.query.filter_by(email=data['email']).first() if (check_candidate is not None): return jsonify({ 'status': 'Failure', 'msg': 'Email is already in use. Please use another' }) check_candidate = Candidate.query.filter_by( username=data['username']).first() if (check_candidate is not None): return jsonify({ 'status': 'Failure', 'msg': 'Username is already in use. Please use another' }) candidate = Candidate( candidate_id=uuid.uuid4().hex, username=data['username'], email=data['email'], first_name=data['first_name'], middle_name=data['middle_name'] if 'middle_name' in data else None, last_name=data['last_name']) candidate.set_password(data['password']) try: db.session.add(candidate) db.session.commit() return jsonify({'status': 'Success'}) except: print('Unexpected error:', sys.exc_info()[0]) return jsonify({ 'status': 'Failure', 'msg': 'Unknown error - please try again later' })