def test_two_full_ranges_overlap(self): self.assertTrue(NumericRange() & NumericRange()) self.assertTrue( NumericRange(None, None, "[]") & NumericRange(None, None, "[]"))
def test_not_gt(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__not_gt=NumericRange(5, 10)), [self.objs[0], self.objs[2]], )
def test_valid_integer(self): field = pg_forms.IntegerRangeField() value = field.clean(['1', '2']) self.assertEqual(value, NumericRange(1, 2))
def test_contains_range(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__contains=NumericRange(3, 8)), [self.objs[0]], )
def test_overlap(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__overlap=NumericRange(3, 8)), [self.objs[0], self.objs[1]], )
def test_unbounded(self): r = NumericRange(None, None, '()') instance = RangesModel(floats=r) instance.save() loaded = RangesModel.objects.get() self.assertEqual(r, loaded.floats)
def str2metric(field, val): _, ftype, fname = field.split('_') # Find out what type of metric it is ftype_choices = { 'other': 'Other Metric', 'beta': 'Effect Size', 'class': 'Classification Metric' } current_metric = {'type': ftype_choices[ftype]} # Find out if it's a common metric and stucture the information fname_common = { 'OR': ('Odds Ratio', 'OR'), 'HR': ('Hazard Ratio', 'HR'), 'AUROC': ('Area Under the Receiver-Operating Characteristic Curve', 'AUROC'), 'Cindex': ('Concordance Statistic', 'C-index'), 'R2': ('Proportion of the variance explained', 'R²'), } if fname in fname_common: current_metric['name'] = fname_common[fname][0] current_metric['name_short'] = fname_common[fname][1] elif (ftype == 'beta') and (fname == 'other'): current_metric['name'] = 'Beta' current_metric['name_short'] = 'β' else: fname, val = val.split('=') current_metric['name'] = fname.strip() # Parse out the confidence interval and estimate if type(val) == float: current_metric['estimate'] = val else: matches_square = insquarebrackets.findall(val) #Check if an alternative metric has been declared if '=' in val: mname, val = [x.strip() for x in val.split('=')] # Check if it has short + long name matches_parentheses = inparentheses.findall(mname) if len(matches_parentheses) == 1: current_metric['name'] = mname.split('(')[0] current_metric['name_short'] = matches_parentheses[0] #Check if SE is reported matches_parentheses = inparentheses.findall(val) if len(matches_parentheses) == 1: val = val.split('(')[0].strip() try: current_metric['estimate'] = float(val) except: val, unit = val.split(" ", 1) current_metric['estimate'] = float(val) current_metric['unit'] = unit current_metric['se'] = matches_parentheses[0] elif len(matches_square) == 1: current_metric['estimate'] = float(val.split('[')[0]) ci_match = tuple(map(float, matches_square[0].split(' - '))) current_metric['ci'] = NumericRange(lower=ci_match[0], upper=ci_match[1], bounds='[]') else: current_metric['estimate'] = float(val.split('[')[0]) return current_metric
def addscene_2_db(): # Gather the form variables try: prod_id = int(request.form['production']) script = int((request.form['script'].split(' - '))[0]) first_page = int(request.form['lower_page']) second_page = int(request.form['upper_page']) page_range = (NumericRange(lower=first_page,upper=second_page) if first_page<second_page else NumericRange(lower=second_page,upper=first_page)) description = request.form['description'] # Make sure the lists of arrays are not larger than the limit if (len(request.form.getlist('sfx[]')) > array_limit or len(request.form.getlist('props[]')) > array_limit or len(request.form.getlist('stunts[]')) > array_limit): raise Exception() else: sfx = filter(None, request.form.getlist('sfx[]')) # Remove any empty strings from the SFX array props = filter(None, request.form.getlist('props[]')) # Remove any empty strings from the SFX array stunts = filter(None, request.form.getlist('stunts[]')) # Remove any empty strings from the SFX array weather = request.form['weather'] time_of_day = request.form['tod'] location = request.form['location'] cost = float(request.form['cost']) budget = float(request.form['budget']) characters = request.form.getlist('characters') character_ids = map(lambda c: int((c.split(' - '))[0]), characters) except: return errorpage(message="There was a problem with your input", redo_link="/productionselect", action="add your scene again") # Determine the new scene id. cursor = g.conn.execute(text("SELECT MAX(scene_id) AS sid FROM Scenes")) try: new_sid = int(cursor.fetchone()['sid'])+1 except: new_sid = 0 cursor.close() try: # Add to the Scenes Table insert_scenes_cmd = ("INSERT INTO Scenes " "VALUES(:s, :d, :f, :p, :t, :w, :o, :c, :l)") g.conn.execute(text(insert_scenes_cmd),s=new_sid,d=description,f=sfx, p=props, t=stunts, w=weather, o=time_of_day, c=cost, l=location) # Add to the "Scripts and Productions are Made_Of Scenes" Table insert_made_of_cmd = "INSERT INTO Made_of VALUES(:c, :p, :s, :b, :r)" g.conn.execute(text(insert_made_of_cmd), c=script, p=prod_id, s=new_sid, b=budget, r=page_range) # Add to the "Scenes Feature Characters" Table for cid in character_ids: insert_feature_cmd = "INSERT INTO Feature VALUES(:c, :s, :r)" g.conn.execute(text(insert_feature_cmd), c=script, s=new_sid, r=cid) except: return errorpage(message="There was a problem with the database", redo_link="/addscene?production="+str(prod_id), action="add your scene again") return render_template("success.html", action="adding your scene")
def tuple_to_numericrange(t): """Helper method to convert a tuple to an inclusive NumericRange.""" if not t: return None return NumericRange(t[0], t[1], '[]')
def test_int_range(self): qs = PostgresModel.objects.all() with self.assertNumQueries(1): data1 = [o.int_range for o in qs.all()] with self.assertNumQueries(0): data2 = [o.int_range for o in qs.all()] self.assertListEqual(data2, data1) self.assertListEqual(data2, [NumericRange(1900, 2000), NumericRange(1989)]) qs = PostgresModel.objects.filter(int_range__contains=2015) with self.assertNumQueries(1): data3 = [o.int_range for o in qs.all()] with self.assertNumQueries(0): data4 = [o.int_range for o in qs.all()] self.assertListEqual(data4, data3) self.assertListEqual(data4, [NumericRange(1989)]) qs = PostgresModel.objects.filter( int_range__contains=NumericRange(1950, 1990)) with self.assertNumQueries(1): data5 = [o.int_range for o in qs.all()] with self.assertNumQueries(0): data6 = [o.int_range for o in qs.all()] self.assertListEqual(data6, data5) self.assertListEqual(data6, [NumericRange(1900, 2000)]) qs = PostgresModel.objects.filter( int_range__contained_by=NumericRange(0, 2050)) with self.assertNumQueries(1): data5 = [o.int_range for o in qs.all()] with self.assertNumQueries(0): data6 = [o.int_range for o in qs.all()] self.assertListEqual(data6, data5) self.assertListEqual(data6, [NumericRange(1900, 2000)]) qs = PostgresModel.objects.filter(int_range__fully_lt=(2015, None)) with self.assertNumQueries(1): data7 = [o.int_range for o in qs.all()] with self.assertNumQueries(0): data8 = [o.int_range for o in qs.all()] self.assertListEqual(data8, data7) self.assertListEqual(data8, [NumericRange(1900, 2000)]) qs = PostgresModel.objects.filter(int_range__fully_gt=(1970, 1980)) with self.assertNumQueries(1): data9 = [o.int_range for o in qs.all()] with self.assertNumQueries(0): data10 = [o.int_range for o in qs.all()] self.assertListEqual(data10, data9) self.assertListEqual(data10, [NumericRange(1989)]) qs = PostgresModel.objects.filter(int_range__not_lt=(1970, 1980)) with self.assertNumQueries(1): data11 = [o.int_range for o in qs.all()] with self.assertNumQueries(0): data12 = [o.int_range for o in qs.all()] self.assertListEqual(data12, data11) self.assertListEqual(data12, [NumericRange(1989)]) qs = PostgresModel.objects.filter(int_range__not_gt=(1970, 1980)) with self.assertNumQueries(1): data13 = [o.int_range for o in qs.all()] with self.assertNumQueries(0): data14 = [o.int_range for o in qs.all()] self.assertListEqual(data14, data13) self.assertListEqual(data14, []) qs = PostgresModel.objects.filter(int_range__adjacent_to=(1900, 1989)) with self.assertNumQueries(1): data15 = [o.int_range for o in qs.all()] with self.assertNumQueries(0): data16 = [o.int_range for o in qs.all()] self.assertListEqual(data16, data15) self.assertListEqual(data16, [NumericRange(1989)]) qs = PostgresModel.objects.filter(int_range__startswith=1900) with self.assertNumQueries(1): data17 = [o.int_range for o in qs.all()] with self.assertNumQueries(0): data18 = [o.int_range for o in qs.all()] self.assertListEqual(data18, data17) self.assertListEqual(data18, [NumericRange(1900, 2000)]) qs = PostgresModel.objects.filter(int_range__endswith=2000) with self.assertNumQueries(1): data19 = [o.int_range for o in qs.all()] with self.assertNumQueries(0): data20 = [o.int_range for o in qs.all()] self.assertListEqual(data20, data19) self.assertListEqual(data20, [NumericRange(1900, 2000)]) PostgresModel.objects.create(int_range=[1900, 1900]) qs = PostgresModel.objects.filter(int_range__isempty=True) with self.assertNumQueries(1): data21 = [o.int_range for o in qs.all()] with self.assertNumQueries(0): data22 = [o.int_range for o in qs.all()] self.assertListEqual(data22, data21) self.assertListEqual(data22, [NumericRange(empty=True)])
def adduser_2_db(): ''' cursor = g.conn.execute(text("SELECT enum_range(NULL::specialties)")) specialties = list(cursor.fetchall()) cursor.close() ''' # Define error links and actions redo_link = "/adduser" action = "add your user" try: # Gather the form variables name = request.form['name'] phone_num = (str(int(request.form['phone_num1'])) + '-' + str(int(request.form['phone_num2'])) + '-' + str(int(request.form['phone_num3']))) if len(phone_num) != 12: raise Exception() email_address = request.form['email_address'] try: past_cred = request.form['past_cred'] except: past_cred = None except: return errorpage(message="There was a problem with the values.", redo_link=redo_link, action=action) try: # Generate a new user id. cursor = g.conn.execute("SELECT MAX(uid) AS uid FROM Users") new_uid = int(cursor.fetchone()['uid'])+1 cursor.close() insert_cmd = "INSERT INTO Users VALUES (:u, :n, :p, :c, :e)" g.conn.execute(text(insert_cmd), u=new_uid, n=name, p=phone_num, c=past_cred, e=email_address) except: return errorpage(message="There was a problem inserting your values.", redo_link=redo_link, action=action) # Get values for the other user types. users_types = request.form.getlist('users_type') print users_types # Crew if 'crew' in users_types: try: # Generate a new crew id. cursor = g.conn.execute("SELECT MAX(cid) AS cid FROM Crew") new_cid = int(cursor.fetchone()['cid'])+1 cursor.close() try: specialties=request.form.getlist('specialties') except: specialties=None insert_crew_cmd = "INSERT INTO Crew VALUES (:c, :u, :s)" g.conn.execute(text(insert_crew_cmd), c=new_cid, u=new_uid, s=specialties) except: # Roll back command delete_user_cmd="DELETE FROM Users WHERE uid=:n" g.conn.execute(text(delete_user_cmd),n=new_uid) return errorpage(message="There was a problem adding your crew values-rolling back.") # Actor if 'actor' in users_types: try: # Generate a new crew id. cursor = g.conn.execute("SELECT MAX(aid) AS aid FROM Actors") new_aid = int(cursor.fetchone()['aid'])+1 cursor.close() try: haircolor=request.form['haircolor'] except: haircolor=None try: eyecolor=request.form['eyecolor'] except: eyecolor=None try: ethnicity=request.form['ethnicity'] except: ethnicity=None try: skills=filter(None, request.form.getlist('skills')) except: skills=None try: first_age = int(request.form['lower_age']) second_age = int(request.form['upper_age']) age_range = (NumericRange(lower=first_age,upper=second_age) if first_age<second_age else NumericRange(lower=second_age,upper=first_age)) except: age_range=None insert_actors_cmd = "INSERT INTO Actors VALUES (:a, :u, :h, :s, :e, :y, :g)" g.conn.execute(text(insert_actors_cmd), a=new_aid, u=new_uid, h=haircolor, s=skills, e=ethnicity, y=eyecolor, g=age_range) except: # Roll back command delete_user_cmd="DELETE FROM Users WHERE uid=:n" g.conn.execute(text(delete_user_cmd),n=new_uid) return errorpage(message="There was a problem adding your actor values-rolling back.") # Producer if 'producer' in users_types: try: # Generate a new producer id. cursor = g.conn.execute("SELECT MAX(producer_id) AS pid FROM Producers") new_pid = int(cursor.fetchone()['pid'])+1 cursor.close() insert_producers_cmd = "INSERT INTO Producers VALUES (:p, :u)" g.conn.execute(text(insert_producers_cmd), p=new_pid, u=new_uid) except: # Roll back command delete_user_cmd="DELETE FROM Users WHERE uid=:n" g.conn.execute(text(delete_user_cmd),n=new_uid) return errorpage(message="There was a problem adding your producer values-rolling back.") return render_template("success.html", action="adding your user")
def sample_vote(): vote = SwissVote() vote.bfs_number = Decimal('100.1') vote.date = date(1990, 6, 2) vote.legislation_number = 4 vote.legislation_decade = NumericRange(1990, 1994) vote.title_de = "Vote DE" vote.title_fr = "Vote FR" vote.short_title_de = "V D" vote.short_title_fr = "V F" vote.keyword = "Keyword" vote.votes_on_same_day = 2 vote._legal_form = 1 vote.initiator = "Initiator" vote.anneepolitique = "anneepolitique" vote.bfs_map_de = ( "https://www.atlas.bfs.admin.ch/maps/12/map/mapIdOnly/1815_de.html") vote.bfs_map_fr = "htt(ps://www.ap/mapIdOnly/1815[e.html}" vote.descriptor_1_level_1 = Decimal('4') vote.descriptor_1_level_2 = Decimal('4.2') vote.descriptor_1_level_3 = Decimal('4.21') vote.descriptor_2_level_1 = Decimal('10') vote.descriptor_2_level_2 = Decimal('10.3') vote.descriptor_2_level_3 = Decimal('10.35') vote.descriptor_3_level_1 = Decimal('10') vote.descriptor_3_level_2 = Decimal('10.3') vote.descriptor_3_level_3 = Decimal('10.33') vote._result = 1 vote.result_eligible_voters = 2 vote.result_votes_empty = 3 vote.result_votes_invalid = 4 vote.result_votes_valid = 5 vote.result_votes_total = 6 vote.result_turnout = Decimal('20.01') vote._result_people_accepted = 1 vote.result_people_yeas = 8 vote.result_people_nays = 9 vote.result_people_yeas_p = Decimal('40.01') vote._result_cantons_accepted = 1 vote.result_cantons_yeas = Decimal('1.5') vote.result_cantons_nays = Decimal('24.5') vote.result_cantons_yeas_p = Decimal('60.01') vote.result_ag_eligible_voters = 101 vote.result_ag_votes_valid = 102 vote.result_ag_votes_total = 103 vote.result_ag_turnout = Decimal('10.40') vote.result_ag_yeas = 105 vote.result_ag_nays = 107 vote.result_ag_yeas_p = Decimal('10.80') vote._result_ag_accepted = 0 vote.result_ai_eligible_voters = 101 vote.result_ai_votes_valid = 102 vote.result_ai_votes_total = 103 vote.result_ai_turnout = Decimal('10.40') vote.result_ai_yeas = 105 vote.result_ai_nays = 107 vote.result_ai_yeas_p = Decimal('10.80') vote._result_ai_accepted = 0 vote.result_ar_eligible_voters = 101 vote.result_ar_votes_valid = 102 vote.result_ar_votes_total = 103 vote.result_ar_turnout = Decimal('10.40') vote.result_ar_yeas = 105 vote.result_ar_nays = 107 vote.result_ar_yeas_p = Decimal('10.80') vote._result_ar_accepted = 0 vote.result_be_eligible_voters = 101 vote.result_be_votes_valid = 102 vote.result_be_votes_total = 103 vote.result_be_turnout = Decimal('10.40') vote.result_be_yeas = 105 vote.result_be_nays = 107 vote.result_be_yeas_p = Decimal('10.80') vote._result_be_accepted = 0 vote.result_bl_eligible_voters = 101 vote.result_bl_votes_valid = 102 vote.result_bl_votes_total = 103 vote.result_bl_turnout = Decimal('10.40') vote.result_bl_yeas = 105 vote.result_bl_nays = 107 vote.result_bl_yeas_p = Decimal('10.80') vote._result_bl_accepted = 0 vote.result_bs_eligible_voters = 101 vote.result_bs_votes_valid = 102 vote.result_bs_votes_total = 103 vote.result_bs_turnout = Decimal('10.40') vote.result_bs_yeas = 105 vote.result_bs_nays = 107 vote.result_bs_yeas_p = Decimal('10.80') vote._result_bs_accepted = 0 vote.result_fr_eligible_voters = 101 vote.result_fr_votes_valid = 102 vote.result_fr_votes_total = 103 vote.result_fr_turnout = Decimal('10.40') vote.result_fr_yeas = 105 vote.result_fr_nays = 107 vote.result_fr_yeas_p = Decimal('10.80') vote._result_fr_accepted = 0 vote.result_ge_eligible_voters = 101 vote.result_ge_votes_valid = 102 vote.result_ge_votes_total = 103 vote.result_ge_turnout = Decimal('10.40') vote.result_ge_yeas = 105 vote.result_ge_nays = 107 vote.result_ge_yeas_p = Decimal('10.80') vote._result_ge_accepted = 0 vote.result_gl_eligible_voters = 101 vote.result_gl_votes_valid = 102 vote.result_gl_votes_total = 103 vote.result_gl_turnout = Decimal('10.40') vote.result_gl_yeas = 105 vote.result_gl_nays = 107 vote.result_gl_yeas_p = Decimal('10.80') vote._result_gl_accepted = 0 vote.result_gr_eligible_voters = 101 vote.result_gr_votes_valid = 102 vote.result_gr_votes_total = 103 vote.result_gr_turnout = Decimal('10.40') vote.result_gr_yeas = 105 vote.result_gr_nays = 107 vote.result_gr_yeas_p = Decimal('10.80') vote._result_gr_accepted = 0 vote.result_ju_eligible_voters = 101 vote.result_ju_votes_valid = 102 vote.result_ju_votes_total = 103 vote.result_ju_turnout = Decimal('10.40') vote.result_ju_yeas = 105 vote.result_ju_nays = 107 vote.result_ju_yeas_p = Decimal('10.80') vote._result_ju_accepted = 0 vote.result_lu_eligible_voters = 101 vote.result_lu_votes_valid = 102 vote.result_lu_votes_total = 103 vote.result_lu_turnout = Decimal('10.40') vote.result_lu_yeas = 105 vote.result_lu_nays = 107 vote.result_lu_yeas_p = Decimal('10.80') vote._result_lu_accepted = 0 vote.result_ne_eligible_voters = 101 vote.result_ne_votes_valid = 102 vote.result_ne_votes_total = 103 vote.result_ne_turnout = Decimal('10.40') vote.result_ne_yeas = 105 vote.result_ne_nays = 107 vote.result_ne_yeas_p = Decimal('10.80') vote._result_ne_accepted = 0 vote.result_nw_eligible_voters = 101 vote.result_nw_votes_valid = 102 vote.result_nw_votes_total = 103 vote.result_nw_turnout = Decimal('10.40') vote.result_nw_yeas = 105 vote.result_nw_nays = 107 vote.result_nw_yeas_p = Decimal('10.80') vote._result_nw_accepted = 0 vote.result_ow_eligible_voters = 101 vote.result_ow_votes_valid = 102 vote.result_ow_votes_total = 103 vote.result_ow_turnout = Decimal('10.40') vote.result_ow_yeas = 105 vote.result_ow_nays = 107 vote.result_ow_yeas_p = Decimal('10.80') vote._result_ow_accepted = 0 vote.result_sg_eligible_voters = 101 vote.result_sg_votes_valid = 102 vote.result_sg_votes_total = 103 vote.result_sg_turnout = Decimal('10.40') vote.result_sg_yeas = 105 vote.result_sg_nays = 107 vote.result_sg_yeas_p = Decimal('10.80') vote._result_sg_accepted = 0 vote.result_sh_eligible_voters = 101 vote.result_sh_votes_valid = 102 vote.result_sh_votes_total = 103 vote.result_sh_turnout = Decimal('10.40') vote.result_sh_yeas = 105 vote.result_sh_nays = 107 vote.result_sh_yeas_p = Decimal('10.80') vote._result_sh_accepted = 0 vote.result_so_eligible_voters = 101 vote.result_so_votes_valid = 102 vote.result_so_votes_total = 103 vote.result_so_turnout = Decimal('10.40') vote.result_so_yeas = 105 vote.result_so_nays = 107 vote.result_so_yeas_p = Decimal('10.80') vote._result_so_accepted = 0 vote.result_sz_eligible_voters = 101 vote.result_sz_votes_valid = 102 vote.result_sz_votes_total = 103 vote.result_sz_turnout = Decimal('10.40') vote.result_sz_yeas = 105 vote.result_sz_nays = 107 vote.result_sz_yeas_p = Decimal('10.80') vote._result_sz_accepted = 0 vote.result_tg_eligible_voters = 101 vote.result_tg_votes_valid = 102 vote.result_tg_votes_total = 103 vote.result_tg_turnout = Decimal('10.40') vote.result_tg_yeas = 105 vote.result_tg_nays = 107 vote.result_tg_yeas_p = Decimal('10.80') vote._result_tg_accepted = 0 vote.result_ti_eligible_voters = 101 vote.result_ti_votes_valid = 102 vote.result_ti_votes_total = 103 vote.result_ti_turnout = Decimal('10.40') vote.result_ti_yeas = 105 vote.result_ti_nays = 107 vote.result_ti_yeas_p = Decimal('10.80') vote._result_ti_accepted = 0 vote.result_ur_eligible_voters = 101 vote.result_ur_votes_valid = 102 vote.result_ur_votes_total = 103 vote.result_ur_turnout = Decimal('10.40') vote.result_ur_yeas = 105 vote.result_ur_nays = 107 vote.result_ur_yeas_p = Decimal('10.80') vote._result_ur_accepted = 0 vote.result_vd_eligible_voters = 101 vote.result_vd_votes_valid = 102 vote.result_vd_votes_total = 103 vote.result_vd_turnout = Decimal('10.40') vote.result_vd_yeas = 105 vote.result_vd_nays = 107 vote.result_vd_yeas_p = Decimal('10.80') vote._result_vd_accepted = 1 vote.result_vs_eligible_voters = 101 vote.result_vs_votes_valid = 102 vote.result_vs_votes_total = 103 vote.result_vs_turnout = Decimal('10.40') vote.result_vs_yeas = 105 vote.result_vs_nays = 107 vote.result_vs_yeas_p = Decimal('10.80') vote._result_vs_accepted = 1 vote.result_zg_eligible_voters = 101 vote.result_zg_votes_valid = 102 vote.result_zg_votes_total = 103 vote.result_zg_turnout = Decimal('10.40') vote.result_zg_yeas = 105 vote.result_zg_nays = 107 vote.result_zg_yeas_p = Decimal('10.80') vote._result_zg_accepted = 0 vote.result_zh_eligible_voters = 101 vote.result_zh_votes_valid = 102 vote.result_zh_votes_total = 103 vote.result_zh_turnout = Decimal('10.40') vote.result_zh_yeas = 105 vote.result_zh_nays = 107 vote.result_zh_yeas_p = Decimal('10.80') vote._department_in_charge = 1 vote.procedure_number = Decimal('24.557') vote._position_federal_council = 1 vote._position_parliament = 1 vote._position_national_council = 1 vote.position_national_council_yeas = 10 vote.position_national_council_nays = 20 vote._position_council_of_states = 1 vote.position_council_of_states_yeas = 30 vote.position_council_of_states_nays = 40 vote.duration_federal_assembly = 30 vote.duration_post_federal_assembly = 31 vote.duration_initative_collection = 32 vote.duration_initative_federal_council = 33 vote.duration_initative_total = 34 vote.duration_referendum_collection = 35 vote.duration_referendum_total = 36 vote.signatures_valid = 40 vote.signatures_invalid = 41 vote.recommendations = { 'fdp': 1, 'cvp': 1, 'sps': 1, 'svp': 1, 'lps': 2, 'ldu': 2, 'evp': 2, 'csp': 3, 'pda': 3, 'poch': 3, 'gps': 4, 'sd': 4, 'rep': 4, 'edu': 5, 'fps': 5, 'lega': 5, 'kvp': 66, 'glp': 66, 'bdp': None, 'mcg': 9999, 'sav': 1, 'eco': 2, 'sgv': 3, 'sbv-usp': 3, 'sgb': 3, 'travs': 3, 'vsa': 9999, 'vpod': 1, 'ssv': 1, 'gem': 1, 'kdk': 1, 'vdk': 1, 'endk': 1, 'fdk': 1, 'edk': 1, 'gdk': 1, 'ldk': 1, 'sodk': 1, 'kkjpd': 1, 'bpuk': 1, 'sbk': 1, 'acs': 1, 'tcs': 1, 'vcs': 1, 'voev': 1 } vote.recommendations_other_yes = "Pro Velo" vote.recommendations_other_no = None vote.recommendations_other_free = "Pro Natura, Greenpeace" vote.recommendations_divergent = { 'edu_vso': 1, 'fdp_ti': 1, 'fdp-fr_ch': 2, 'jcvp_ch': 2, } vote.national_council_election_year = 1990 vote.national_council_share_fdp = Decimal('01.10') vote.national_council_share_cvp = Decimal('02.10') vote.national_council_share_sp = Decimal('03.10') vote.national_council_share_svp = Decimal('04.10') vote.national_council_share_lps = Decimal('05.10') vote.national_council_share_ldu = Decimal('06.10') vote.national_council_share_evp = Decimal('07.10') vote.national_council_share_csp = Decimal('08.10') vote.national_council_share_pda = Decimal('09.10') vote.national_council_share_poch = Decimal('10.10') vote.national_council_share_gps = Decimal('11.10') vote.national_council_share_sd = Decimal('12.10') vote.national_council_share_rep = Decimal('13.10') vote.national_council_share_edu = Decimal('14.10') vote.national_council_share_fps = Decimal('15.10') vote.national_council_share_lega = Decimal('16.10') vote.national_council_share_kvp = Decimal('17.10') vote.national_council_share_glp = Decimal('18.10') vote.national_council_share_bdp = Decimal('19.10') vote.national_council_share_mcg = Decimal('20.20') vote.national_council_share_ubrige = Decimal('21.20') vote.national_council_share_yeas = Decimal('22.20') vote.national_council_share_nays = Decimal('23.20') vote.national_council_share_neutral = Decimal('24.20') vote.national_council_share_none = Decimal('25.20') vote.national_council_share_empty = Decimal('26.20') vote.national_council_share_free_vote = Decimal('27.20') vote.national_council_share_unknown = Decimal('28.20') vote.national_council_share_vague = Decimal('28.20') return vote
def test_ends_touch(self): self.assertFalse(NumericRange(10, 20) & NumericRange(20, 30)) self.assertTrue(NumericRange(10, 20, "[]") & NumericRange(20, 30)) self.assertFalse(NumericRange(20, 30) & NumericRange(10, 20)) self.assertTrue(NumericRange(20, 30) & NumericRange(10, 20, "[]")) self.assertFalse(NumericRange(10, 20) & NumericRange(20, None)) self.assertTrue(NumericRange(10, 20, "[]") & NumericRange(20, None)) self.assertFalse(NumericRange(20, None) & NumericRange(10, 20)) self.assertTrue(NumericRange(20, None) & NumericRange(10, 20, "[]")) self.assertFalse(NumericRange(None, 20) & NumericRange(20, 30)) self.assertTrue(NumericRange(None, 20, "[]") & NumericRange(20, 30)) self.assertFalse(NumericRange(20, 30) & NumericRange(None, 20)) self.assertTrue(NumericRange(20, 30) & NumericRange(None, 20, "[]")) self.assertFalse(NumericRange(None, 20) & NumericRange(20, None)) self.assertTrue(NumericRange(None, 20, "[]") & NumericRange(20, None)) self.assertFalse(NumericRange(20, None) & NumericRange(None, 20)) self.assertTrue(NumericRange(20, None) & NumericRange(None, 20, "[]")) self.assertFalse(NumericRange(0, 2, "()") & NumericRange(0, 0, "[]"))
def test_full_range_overlaps_non_full_range(self): self.assertTrue(NumericRange() & NumericRange(-12, 55)) self.assertTrue(NumericRange(-12, 55) & NumericRange())
def test_range_object(self): r = NumericRange(0, 10) instance = RangesModel(ints=r) instance.save() loaded = RangesModel.objects.get() self.assertEqual(r, loaded.ints)
def create_numeric_range(self, data): return NumericRange(data.get('lower', 0), data.get('upper', None))
def test_tuple(self): instance = RangesModel(ints=(0, 10)) instance.save() loaded = RangesModel.objects.get() self.assertEqual(NumericRange(0, 10), loaded.ints)
def load(apps, schema_editor): School = apps.get_model("search", "School") HighSchoolClass = apps.get_model("search", "HighSchoolClass") ExtendedSubject = apps.get_model("search", "ExtendedSubject") Language = apps.get_model("search", "Language") with open("csvs/publiczne_oddzialy_2020.csv", newline="") as csv_file: csv_reader = csv.reader(csv_file, delimiter=";") for n, row in enumerate(csv_reader): if n > 0: regon = row[7].zfill(9) school = School.objects.filter( public_institution_data__regon=regon) if (not school.exists() or school.get().school_type != "liceum ogólnokształcące"): continue school = school.get() class_name = row[1] type = { "ogólnodostępny": "O", "mistrzostwa sportowego": "MS", "dwujęzyczny": "D", "międzynarodowy": "M", "wstępny": "DW", "sportowy": "S", "integracyjny cz. ogólnodostępna": "I-o", "integracyjny cz. dla kandydatów z orzeczeniem o potrzebie kształcenia specjalnego": "I-i", "przygotowania wojskowego": "PW", }.get(row[35], "") hsc = HighSchoolClass( type=type, name=class_name, school=school, year=NumericRange(2020, 2022, "[)"), ) hsc.save() subject_list = [v for v in row[3].split(",") if v] subject_names = { val: key for (key, val) in SubjectName.choices + LanguageName.choices } for subject in subject_list: subject = subject.strip() name = subject_names[subject] es = ExtendedSubject(name=name, high_school_class=hsc) es.save() languages = list( re.search( "\\((([A-z]+\\*?)(?:,([A-z]+\\*?))*)-([A-z]+\\*?)(?:,([A-z]+\\*?))*\\)", row[2], ).groups()) for i, lan in enumerate(languages[1:]): if not lan: continue is_multiple_levels = lan.endswith("*") is_bilingual = hsc.type == "D" and i == 0 lan = lan.replace("*", "") nr = 1 if lan in languages[0] else 2 lang = Language( high_school_class=hsc, name=lan, multiple_levels=is_multiple_levels, is_bilingual=is_bilingual, nr=nr, ) lang.save()
def test_empty(self): r = NumericRange(empty=True) instance = RangesModel(ints=r) instance.save() loaded = RangesModel.objects.get() self.assertEqual(r, loaded.ints)
def post(self, request, format=None): """ Get talents matching to search condition """ # Filter talents according to search condition search_conditions = request.data hasAnyConditions = len(search_conditions.values()) > 0 talent_name = self.pickout_data(search_conditions, 'talent_name') talent_tid = self.pickout_data(search_conditions, 'talent_tid') casting_request_id = self.pickout_data(search_conditions, 'casting_request_id') talent_name_or_tid = self.pickout_data(search_conditions, 'talent_name_or_tid') ages = self.pickout_data(search_conditions, 'ages') availability = self.pickout_data(search_conditions, 'availability') heights = self.pickout_data(search_conditions, 'heights') languages = self.pickout_data(search_conditions, 'languages') position_ids = self.pickout_data(search_conditions, 'position_ids') position_sub_type_ids = self.pickout_data(search_conditions, 'position_sub_type_ids') ratings = self.pickout_data(search_conditions, 'ratings') sexes = self.pickout_data(search_conditions, 'sexes') skill_ids = self.pickout_data(search_conditions, 'skill_ids') sub_skill_ids = self.pickout_data(search_conditions, 'sub_skill_ids') approved = self.pickout_data(search_conditions, 'approved') locked_dance_combination = self.pickout_data( search_conditions, 'locked_dance_combination') talents = Talent.objects.all() # Check talent_tid if talent_tid: try: talents = talents.filter(tid__icontains=talent_tid) except Talent.DoesNotExist: raise Http404 # Check talent_name if talent_name: talents = talents.filter( Q(user__first_name__icontains=talent_name) | Q(user__last_name__icontains=talent_name)) # Check casting_request_id if casting_request_id: casting_request = CastingRequest.objects.get(pk=casting_request_id) # casting_request_talent_ids talent_ids = CastingRequestTalent.objects\ .filter(casting_request_id=casting_request.id)\ .values_list('talent', flat=True)\ .order_by('talent')\ .distinct() talents = talents.filter(~Q(id__in=talent_ids)) # Check talent_name_or_tid if talent_name_or_tid: talents = talents.filter( Q(user__first_name__icontains=talent_name_or_tid) | Q(user__last_name__icontains=talent_name_or_tid) | Q(tid__icontains=talent_name_or_tid)) # Check sexes if sexes: talents = talents.filter(Q(sex__in=sexes)) # Check position_ids if position_ids: talent_position_talent_ids = TalentPositionType.objects.filter( Q(position_type_id__in=position_ids) )\ .values_list('talent', flat=True)\ .order_by('talent')\ .distinct() talents = talents.filter(Q(id__in=talent_position_talent_ids)) # Check position_sub_type_ids if position_sub_type_ids: talent_position_sub_type_talent_ids = TalentPositionSubType.objects.filter( Q(position_sub_type_id__in=position_sub_type_ids) )\ .values_list('talent', flat=True)\ .order_by('talent')\ .distinct() talents = talents.filter( Q(id__in=talent_position_sub_type_talent_ids)) # Check skill_ids if skill_ids: talent_skill_talent_ids = TalentSkill.objects.filter( reduce(or_, (Q(skill_id=skill_id) for skill_id in skill_ids)) )\ .values_list('talent', flat=True)\ .order_by('talent')\ .distinct() talents = talents.filter(Q(id__in=talent_skill_talent_ids)) # Check sub_skill_ids if sub_skill_ids: talent_sub_skill_talent_ids = TalentSubSkill.objects.filter(Q(sub_skill_id__in=sub_skill_ids))\ .values_list('talent', flat=True)\ .order_by('talent')\ .distinct() talents = talents.filter(Q(id__in=talent_sub_skill_talent_ids)) # Check availability if availability and (availability['start_date'] or availability['end_date']): queries = Q() if availability['end_date']: queries = Q(start_date__lte=parse(availability['end_date'])) if availability['start_date']: queries &= Q(end_date__gte=parse(availability['start_date'])) talent_availabilities_talent_ids = TalentAvailability.objects.filter(queries)\ .values_list('talent', flat=True)\ .order_by('talent')\ .distinct() talents = talents.filter( Q(id__in=talent_availabilities_talent_ids)) # Check ages if ages: talents = talents.filter(Q(age_range__in=ages)) # Check heights if heights: queries = Q() for height_range in heights: start_height = height_range['start_height'] end_height = height_range['end_height'] if end_height == 0: end_height = start_height + 1 queries |= Q(height__contained_by=NumericRange( start_height, end_height)) talents = talents.filter(queries) # Check languages if languages: talent_languages_talent_ids = TalentLanguage.objects.filter(language__in=languages)\ .values_list('talent', flat=True)\ .order_by('talent')\ .distinct() talents = talents.filter(Q(id__in=talent_languages_talent_ids)) # Check ratings if ratings: rated_talent_ids = [] for talent in talents: talent_average_rating = TalentRating.objects.filter(talent=talent)\ .aggregate(Avg('rating'))['rating__avg'] if talent_average_rating: for rating_range in ratings: if (talent_average_rating >= rating_range['start_rating']) and ( talent_average_rating <= rating_range['end_rating']): rated_talent_ids.append(talent.id) talents = talents.filter(Q(id__in=rated_talent_ids)) # Check approved if approved is not None: talents = talents.filter(approved=approved) if locked_dance_combination: talents = talents.filter( locked_dance_combination=locked_dance_combination) talents = self.check_sort_condition(talents, search_conditions) # Logging user = request.user if user and user.type != 'agency' and len( talents) > 0 and hasAnyConditions: for talent in talents: UserNoteManager.search_logger( None, user, talent.user, 'TALENT APPEARED INSEARCH BY {finder}'.format(finder=user), user) serializer = TalentSerializer(talents, many=True) return Response(serializer.data)
def test_exact(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__exact=NumericRange(0, 10)), [self.objs[0]], )
def test_float_open(self): field = pg_forms.FloatRangeField() value = field.clean(['', '3.1415926']) self.assertEqual(value, NumericRange(None, 3.1415926))
def test_contained_by(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__contained_by=NumericRange(0, 20)), [self.objs[0], self.objs[1], self.objs[3]], )
def apply_filters(self, q, facets=None, pagination=None, work_model=Work, edition_model=Edition): """Apply filters to a base query against Work or a materialized view. :param work_model: Either Work, MaterializedWork, or MaterializedWorkWithGenre :param edition_model: Either Edition, MaterializedWork, or MaterializedWorkWithGenre """ if self.languages: q = q.filter(edition_model.language.in_(self.languages)) if self.exclude_languages: q = q.filter( not_(edition_model.language.in_(self.exclude_languages))) if self.audiences: q = q.filter(work_model.audience.in_(self.audiences)) if (Classifier.AUDIENCE_CHILDREN in self.audiences or Classifier.AUDIENCE_YOUNG_ADULT in self.audiences): gutenberg = DataSource.lookup(self._db, DataSource.GUTENBERG) # TODO: A huge hack to exclude Project Gutenberg # books (which were deemed appropriate for # pre-1923 children but are not necessarily so for # 21st-century children.) # # This hack should be removed in favor of a # whitelist system and some way of allowing adults # to see books aimed at pre-1923 children. q = q.filter(edition_model.data_source_id != gutenberg.id) if self.appeals: q = q.filter(work_model.primary_appeal.in_(self.appeals)) # If a license source is specified, only show books from that # source. if self.license_source: q = q.filter(LicensePool.data_source == self.license_source) if self.age_range != None: if (Classifier.AUDIENCE_ADULT in self.audiences or Classifier.AUDIENCE_ADULTS_ONLY in self.audiences): # Books for adults don't have target ages. If we're including # books for adults, allow the target age to be empty. audience_has_no_target_age = work_model.target_age == None else: audience_has_no_target_age = False if len(self.age_range) == 1: # The target age must include this number. r = NumericRange(self.age_range[0], self.age_range[0], '[]') q = q.filter( or_(work_model.target_age.contains(r), audience_has_no_target_age)) else: # The target age range must overlap this age range r = NumericRange(self.age_range[0], self.age_range[-1], '[]') q = q.filter( or_(work_model.target_age.overlaps(r), audience_has_no_target_age)) if self.fiction == self.UNCLASSIFIED: q = q.filter(work_model.fiction == None) elif self.fiction != self.BOTH_FICTION_AND_NONFICTION: q = q.filter(work_model.fiction == self.fiction) if self.media: q = q.filter(edition_model.medium.in_(self.media)) # TODO: Also filter on formats. q = self.only_show_ready_deliverable_works(q, work_model) distinct = False if self.list_data_source_id or self.list_ids: # One book can show up on more than one list; we need to # add a DISTINCT clause. distinct = True q = q.join(LicensePool.custom_list_entries) if self.list_data_source_id: q = q.join(CustomListEntry.customlist).filter( CustomList.data_source_id == self.list_data_source_id) else: q = q.filter(CustomListEntry.list_id.in_(self.list_ids)) if self.list_seen_in_previous_days: cutoff = datetime.datetime.utcnow() - datetime.timedelta( self.list_seen_in_previous_days) q = q.filter(CustomListEntry.most_recent_appearance >= cutoff) if facets: q = facets.apply(self._db, q, work_model, edition_model, distinct=distinct) if pagination: q = pagination.apply(q) return q
def test_fully_gt(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__fully_gt=NumericRange(5, 10)), [], )
def test_loading(self): instance = list(serializers.deserialize('json', self.test_data))[0].object self.assertEqual(instance.ints, NumericRange(0, 10)) self.assertEqual(instance.floats, NumericRange(empty=True)) self.assertEqual(instance.dates, None)
def test_adjacent_to(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__adjacent_to=NumericRange(0, 5)), [self.objs[1], self.objs[2]], )
def test_open(self): field = pg_forms.IntegerRangeField() value = field.clean(['', '0']) self.assertEqual(value, NumericRange(None, 0))
def test_valid_floats(self): field = pg_forms.FloatRangeField() value = field.clean(['1.12345', '2.001']) self.assertEqual(value, NumericRange(1.12345, 2.001))
def test_empty_ranges_do_not_overlap(self): self.assertFalse(NumericRange(0, 0, "()") & NumericRange()) self.assertFalse( NumericRange(0, 1, "()") & NumericRange(None, None, "[]"))