def test_increment(self): self.assertEqual(Day(2000, 1, 1) + 1, Day(2000, 1, 2)) self.assertEqual(Day(2000, 2, 28) + 2, Day(2000, 3, 1)) self.assertEqual(Day(2000, 2, 28) + timedelta(2), Day(2000, 3, 1)) self.assertEqual(Day(2000, 2, 28) - 2, Day(2000, 2, 26)) self.assertEqual(Day(2000, 2, 28) - 0, Day(2000, 2, 28))
def test_deep_itm_american_put_worth_intrinsic(self): F = 100.0 K = 150.0 sigma = 0.05 market_day = Day(2018, 1, 1) r = 0.2 option = OptionInstrument(K, OptionRight.PUT, Day(2018, 6, 1), ExerciseStyle.AMERICAN) european_value = option.european_value(market_day, F, sigma, r) intrinsic = option.intrinsic(F) cn_value = option.cn_value(market_day, F, sigma, r) self.assertAlmostEqual(cn_value, intrinsic, delta=0.01) self.assertLess(european_value, intrinsic)
def __init__(self, start_day, end_day): if start_day is None or end_day is None: raise TypeError("Cannot create Days Object from value None") logger.debug("creating days from " + str(start_day) + " and " + str(end_day)) if isinstance(start_day, DaysEnum): self.start_day = Day(start_day) if isinstance(end_day, DaysEnum): self.end_day = Day(end_day) self.start_day = start_day self.end_day = end_day
def test_european_close_to_black_scholes(self): rng = PimpedRandom() for _ in range(10): seed = np.random.randint(0, 100 * 1000) rng.seed(seed) market_day = Day(2018, 1, 1) option = random_option(rng, ex_style=ExerciseStyle.EUROPEAN) sigma = rng.random() * 0.5 fwd_price = rng.uniform(option.strike - 1.0, option.strike + 1.0) r = 0.1 * rng.random() numeric_value = option.cn_value(market_day, fwd_price, sigma, r) def bs_value(s): return option.european_value(market_day, fwd_price, s, r) analytic_value = bs_value(sigma) tol = max( bs_value(sigma + 0.01) - analytic_value, 0.01, analytic_value * 0.01) self.assertAlmostEqual(numeric_value, analytic_value, delta=tol, msg=f"Seed was {seed}")
def __init__(self, a_CasesPerDay): # We need to create a day object for every # entry in our a_CasesPerDay self.d_CaseHistory = {} # We also need to closely monitor the active cases, individually self.d_ActiveCases = {} # We will store these cases in the dictionary above # This way we can access a day's historys by Province.d_CaseHistory[day-1] print(f"Day # \t\tNew Cases\t\tActive Cases\t\tOperation Zone") print("--------------------- Confirmed Govt Data -------------------") for self.i_Cursor in range(0, len(a_CasesPerDay)): # The day will inherit a lot from the province o_Day = Day(i_DayNumber=self.i_Cursor, i_NewCases=a_CasesPerDay[self.i_Cursor], d_ActiveCases=self.d_ActiveCases, d_PreviousData=self.d_CaseHistory) self.d_ActiveCases = o_Day.d_ActiveCases self.d_CaseHistory[f"day-{self.i_Cursor}"] = o_Day print(self.d_CaseHistory[f"day-{self.i_Cursor}"]) # End of interpolation ---------------------------------------------------------- # Mark when our confirmed data ends --------------------------------------------- self.i_InputSignalEndIdx = self.i_Cursor+1 print("--------------------- Extrapolated Data -------------------") for self.i_Cursor in range(self.i_InputSignalEndIdx, self.i_InputSignalEndIdx + 10): # Here we are predicting 10 days ahead o_Day = self.ProjectNextDay() self.d_CaseHistory[f"day-{self.i_Cursor}"] = o_Day print(self.d_CaseHistory[f"day-{self.i_Cursor}"])
def random_option(rng: PimpedRandom, strike: float = None, right: OptionRight = None, expiry: Day = None, ex_style: ExerciseStyle = None): return OptionInstrument(strike or 80.0 + rng.random() * 20, right or rng.enum_choice(OptionRight), expiry or Day(2018, 1, 2) + rng.randint(1, 100), ex_style or rng.enum_choice(ExerciseStyle))
def from_parse_results(cls, result): days = [] if "startday" in result: logger.info("range date detected") # this is a date range that includes the intervening days start_day = Day.from_string(result.get("startday")[0]) end_day = result.get("endday")[0] end_day = Day.from_string(end_day) if end_day is not None else end_day days = cls(start_day, end_day) elif "day" in result: logger.info("list date detected") #TODO: have Days class support lists of individual days, as well as just ranges. as of now this is fine because both are iterable and give the same outputs when iterated over days = [ Day.from_string(day) for day in result.get("day") ] elif "day_shortcuts" in result: logger.info("shortcut date detected") days = cls.from_shortcut_string(result.get( "day_shortcuts")[0]) else: logger.info("unspecified date detected") # nothing specified, assumeit means every day return cls(DaysEnum.MONDAY, DaysEnum.SUNDAY) return days
def test_intrinsic(self): rng = PimpedRandom() for _ in range(100): seed = np.random.randint(0, 100 * 1000) rng.seed(seed) option = random_option(rng, ex_style=ExerciseStyle.EUROPEAN) market_day = Day(2018, 1, 1) fwd_price = option.strike + rng.uniform(-2.0, 2.0) self.assertAlmostEqual(option.european_value(market_day, fwd_price, sigma=1e-5, r=0.0), option.intrinsic(fwd_price), delta=1e-3, msg=f"Seed was {seed}")
def __iter__(self): # if end_day is None: # return [start_day] week = list(DaysEnum) start_index = week.index(self.start_day) end_index = week.index(self.end_day) if end_index < start_index: # if the end day is sooner in the week than the start end_index += start_index days = [] for x in range(start_index, end_index+1): #ensure the indices wrap around to the beginning of the week day_index = x % 7 days.append(Day(week[day_index])) return iter(days)
def test_american_worth_at_least_intrinsic(self): rng = PimpedRandom() for _ in range(5): seed = np.random.randint(0, 100 * 1000) rng.seed(seed) market_day = Day(2018, 1, 1) option = random_option(rng, ex_style=ExerciseStyle.AMERICAN) fwd_price = rng.uniform(option.strike - 1.0, option.strike + 1.0) sigma = rng.random() * 0.5 r = 0.1 * rng.random() numeric_value = option.cn_value(market_day, fwd_price, sigma, r) intrinsic_value = option.intrinsic(fwd_price) self.assertGreaterEqual(numeric_value, intrinsic_value, msg=f"Seesd was {seed}")
def get(self, eventId, guardianId): '''The visitor is not an authenticated guardian''' if not SubscriptionLoginHandler.isAuthenticatedGuardian(): self.redirect('/inschrijven/') return '''The guardian is not authorized to see the page with the given eventId/guardianId''' if not self.isAuthorized(eventId, guardianId): SubscriptionLoginHandler.redirectToSubscriptionPage(self) return '''The guardian is an authorized guardian, so show the form''' event = Event.get_by_id(int(eventId)) days = Day.gql("WHERE event = :1", event).fetch(999) guardian = Guardian.get_by_key_name(guardianId) notifications = [] templVal = { 'notifications': notifications } subscriptionDetailsList = SubscriptionDetails.gql("WHERE event = :1 AND guardian = :2", event, guardian).fetch(1, 0) if not subscriptionDetailsList: notifications.append('Pagina niet gevonden.') self.showError(templVal) return subscriptionDetails = subscriptionDetailsList[0] if subscriptionDetails and subscriptionDetails.requested: notifications.append('U kunt geen verzoeken meer indienen.') self.showError(templVal) return students = Student.gql("WHERE guardian = :1", guardian).fetch(999, 0) students_subjects = self.getStudentsSubjects(students) if event and guardian and students and days: templVal = { 'event': event, 'days': days, 'guardian': guardian, 'students': students_subjects } path = os.path.join(os.path.dirname(__file__), '../templates/subscription/subscription.html') self.response.out.write(template.render(path, templVal))
def get(self, arg): #first call for edit modus if arg.isdigit(): #get event info and parse it in template event = Event.get_by_id(int(arg)) day = Day.gql("WHERE event = :1", event)[0] monthText = self.getMonthText(day.date.month) tV = { 'event': event, 'day': day, 'monthText': monthText, 'logoutlink': users.create_logout_url("/") } path = os.path.join(os.path.dirname(__file__), '../templates/administration/event-edit.html') self.response.out.write(template.render(path, tV)) #first call of new event elif arg == 'nieuw': path = os.path.join(os.path.dirname(__file__), '../templates/administration/event-edit.html') self.response.out.write(template.render(path, {'logoutlink': users.create_logout_url("/")}))
def test_mc_value_close_to_bs(self): rng = PimpedRandom() for _ in range(5): seed = np.random.randint(0, 100 * 1000) rng.seed(seed) market_day = Day(2018, 1, 1) option = random_option(rng, ex_style=ExerciseStyle.EUROPEAN) fwd_price = rng.uniform(option.strike - 1.0, option.strike + 1.0) sigma = rng.random() * 0.5 r = 0.1 * rng.random() mc_value = option.mc_european_value(market_day, fwd_price, sigma, r) bs_value = option.european_value(market_day, fwd_price, sigma, r) self.assertAlmostEqual(mc_value, bs_value, delta=0.1, msg=f"Seesd was {seed}")
def post(self, arg): if self.request.POST['i-save-event']: n = self.request.POST['i-name'] d = self.request.POST['i-startdate'] v = Validator() errors = []; #is it an existing event or not? if arg.isdigit(): nE = Event.get_by_id(int(arg)) nDs = Day.gql("WHERE event = :1", nE).fetch(3) elif arg == 'nieuw': nE = Event(tables=40, talk_time=15) nDs = [Day(talks=12), Day(talks=12), Day(talks=12)] #validate data if not v.vString(n): errors.append('onjuiste titel ouderavondreeks') else: nE.event_name = n if not v.vDate(d): errors.append('onjuiste startdatum') else: d = map(int, (d.split('-'))) sD = datetime.datetime(year=d[0], month=d[1], day=d[2], hour=20, minute=00) nDs[0].date = sD #show errors if they exist if errors: path = os.path.join(os.path.dirname(__file__), '../templates/administration/event-edit.html') monthText = '' if nDs[0].date: monthText = self.getMonthText(nDs[0].date.month) tv = { 'errors': errors, 'event': nE, 'day': nDs[0], 'monthText': monthText, 'logoutlink': users.create_logout_url("/") } self.response.out.write(template.render(path, tv)) #update event in datastore if no error exists else: nE.put() #add two other dates and store them delta = datetime.timedelta(days=1) if nDs[0].date.weekday() < 3: nDs[1].date = deepcopy(nDs[0].date) + delta nDs[2].date = deepcopy(nDs[0].date) + delta*2 elif nDs[0].date.weekday() == 3: nDs[1].date = deepcopy(nDs[0].date) + delta nDs[2].date = deepcopy(nDs[0].date) + delta*3 elif nDs[0].date.weekday() == 4: nDs[1].date = deepcopy(nDs[0].date) + delta*3 nDs[2].date = deepcopy(nDs[0].date) + delta*4 for d in nDs: d.event = nE d.updateEndTime() d.put() self.redirect('/administratie')
except Exception, e: pass # Set random seed random.seed(1138) # Add an event event = Event(event_name="paasrapport", tables=40, talk_time=15) event.put() # Add some days to the aforementioned event day = Day(date=datetime.datetime(year=2011, month=11, day=11, hour=20, minute=00), talks=12, event=event) day.put() guardians = Guardian.all().fetch(99999999) samplesize = int(len(guardians)/3) guardians = random.sample(guardians, samplesize) for guardian in guardians: time = TimePreference() time.event = event time.guardian = guardian time.preference = random.randint(0, 2) time.save() days = event.days.fetch(999) random.shuffle(days) for i, day in enumerate(days):
def get(self): # Add some guardians new_guardian = Guardian(guardian_id=6781, firstname="A.J.", preposition="van", lastname="Brandsma") new_guardian.put() new_guardian = Guardian(guardian_id=6900, firstname="M.", lastname="Tervuure") new_guardian.put() # Add an event new_event = Event(tables=40, talk_time=15) new_event.put() # Add some days to the aforementioned event new_day = Day(date=datetime.datetime(year=2011, month=11, day=11, hour=20, minute=00), talks=12, event=new_event) new_day.put() new_day = Day(date=datetime.datetime(year=2011, month=11, day=12, hour=20, minute=00), talks=12, event=new_event) new_day.put() new_day = Day(date=datetime.datetime(year=2011, month=11, day=13, hour=20, minute=00), talks=12, event=new_event) new_day.put() # Add an event new_event = Event(tables=40, talk_time=15) new_event.put() # Add some days to the aforementioned event new_day = Day(date=datetime.datetime(year=2011, month=11, day=20, hour=19, minute=30), talks=12, event=new_event) new_day.put() new_day = Day(date=datetime.datetime(year=2011, month=11, day=21, hour=20, minute=00), talks=12, event=new_event) new_day.put() new_day = Day(date=datetime.datetime(year=2011, month=11, day=22, hour=19, minute=45), talks=12, event=new_event) new_day.put()
def get(self): print "" print "<html><body style='font-family: Helvetica; font-size: 0.9em;'>" print time.strftime("%H:%M:%S", time.localtime()) + ": Start<br>" logging.info("Fetching all info") # if arg != None: # event = Event.get_by_id(int(arg)) # else: event = Event.all().filter("event_name", "paasrapport").get() days = Day.all().filter("event", event).fetch(999) days.sort(key=lambda day: day.date) max_requests = 0 max_timepref = 0 max_rank = 0 allguardians = Guardian.all().fetch(9999) guardians = [] requests = [] for guardian in allguardians: requests = Request.all().filter("guardian", guardian).filter("event", event).fetch(999) if len(requests) > 0: max_requests = max([max_requests, len(requests)]) guardian.requests = requests guardian.day_prefs = [] for day in days: guardian.day_prefs.append(DayPreference.all().filter("guardian", guardian).filter("day", day).get()) guardian.day_prefs.sort(key=lambda day: day.rank) max_rank = max([max_rank, max([day.rank for day in guardian.day_prefs])]) guardian.time_pref = TimePreference.all().filter("guardian", guardian).filter("event", event).get() max_timepref = max([max_timepref, guardian.time_pref.preference]) if len(requests) > 5: guardianCopy = copy.deepcopy(guardian) guardian.requests = guardian.requests[: int(len(requests) / 2)] guardianCopy.requests = guardianCopy.requests[int(len(requests) / 2) :] guardianCopy.day_prefs[0].rank = 999 guardians.append(guardianCopy) guardians.append(guardian) timepref_options = range(max_timepref + 1) timepref_options = [1, 2, 0] planning = Planning(event, days) logging.info("All guardians/requests collected") for length in range(max_requests, 0, -1): for timepref in timepref_options: for rank in range(0, max_rank + 1): for day_num, day in enumerate(days): for guardian in filter( lambda guardian: (len(guardian.requests) == length) and (guardian.time_pref.preference == timepref) and ( filter(lambda day_pref: day_pref.day.date == day.date, guardian.day_prefs)[0].rank == rank ), guardians, ): # try to place these requests placed = planning.place(guardian, day_num) # on succes, remove guardian from guardian # on fail, the guardian will return on a less preferable round if placed: guardians.remove(guardian) logging.info("Placed") for dayIndex, day in enumerate(planning.days): start = time.clock() lowestValue = 0 for i, slot in enumerate(day[0]): lowestValue += len(planning.conflictedTeachers(day, i)) logging.info("conflicts: " + str(lowestValue)) # <--- Build a list of all regions logging.info("Building regions") regions = [] for tableIndex, table in enumerate(day): region = [tableIndex, 0, -1] previousGuardian = "" for slotIndex, slot in enumerate(table): guardianId = planning.getGuardianIdFromRequest(slot) block = table[region[1] : region[2] + 1] if guardianId == "": if len(block) == 0: region = [tableIndex, slotIndex, slotIndex] elif block.count(None) == 0: if previousGuardian != "": region[2] = slotIndex regions.append(region) region = [tableIndex, 0, -1] elif block.count(None) > 0: if len(block) > block.count(None): regions.append(region) region = [tableIndex, slotIndex, slotIndex] previousGuardian = "" else: if guardianId != previousGuardian and previousGuardian != "": regions.append(region) region = [tableIndex, slotIndex, slotIndex] region[2] = slotIndex previousGuardian = guardianId block = table[region[1] : region[2] + 1] if len(block) > block.count(None) > 0: regions.append(region) logging.info("Regions built") permutationSets = {} preconflicts = 0 pre_max_conflicts = 0 for i, slot in enumerate(day[0]): slotConflicts = len(planning.conflictedTeachers(day, i)) pre_max_conflicts = max([pre_max_conflicts, slotConflicts]) preconflicts += slotConflicts logging.info("Starting conflicts: " + str(preconflicts)) logging.info("Starting max slotconflicts: " + str(pre_max_conflicts)) for set in regions: block = day[set[0]][set[1] : set[2] + 1] block.sort(key=lambda x: planning.getTeacherStringFromRequest(x)) day[set[0]][set[1] : (set[2] + 1)] = block sortedconflicts = 0 sorted_max_conflicts = 0 for i, slot in enumerate(day[0]): slotConflicts = len(planning.conflictedTeachers(day, i)) sorted_max_conflicts = max([sorted_max_conflicts, slotConflicts]) sortedconflicts += slotConflicts logging.info("Conflicts after sorting: " + str(sortedconflicts)) logging.info("Max slotconflicts after sorting: " + str(sorted_max_conflicts)) conflicts = 9999 max_conflicts = 9999 while ( conflicts >= preconflicts and conflicts >= sortedconflicts and max_conflicts >= pre_max_conflicts and max_conflicts >= sorted_max_conflicts ): for set in regions: block = day[set[0]][set[1] : set[2] + 1] random.shuffle(block) day[set[0]][set[1] : (set[2] + 1)] = block conflicts = 0 max_conflicts = 0 for i, slot in enumerate(day[0]): slotConflicts = len(planning.conflictedTeachers(day, i)) max_conflicts = max([max_conflicts, slotConflicts]) conflicts += slotConflicts logging.info("Conflicts after shuffling: " + str(conflicts)) logging.info("Max slotconflicts after shuffling: " + str(max_conflicts)) # <--- Cycle through conflicted regions loop = 0 while lowestValue > 0: logging.info("Dropping non-conflicted regions") conflictedRegions = [ region for region in regions if planning.numberOfConflictsPerRegion(day, region) > 0 and (region[2] - region[1]) < 7 ] logging.info("Sorting regions to start with smallest region with highest number of conflicts") conflictedRegions.sort( key=lambda set: (set[2] - set[1], -planning.numberOfConflictsPerRegion(day, set)) ) logging.info(str(conflictedRegions)) loop += 2 if loop > len(conflictedRegions): loop = len(conflictedRegions) for set in conflictedRegions[:loop]: logging.info("Working on set: " + str(set)) logging.info("Set size: " + str(set[2] - set[1] + 1)) # logging.info("Number of conflicts in region: "+str(planning.numberOfConflictsPerRegion(day, set))) if planning.numberOfConflictsPerRegion(day, set) <= 0: logging.info("Already fixed; moving on...") continue if not tuple(set) in permutationSets: # logging.info("This set is new to the dictionary") block = day[set[0]][set[1] : set[2] + 1] permutations = itertools.permutations(block) permutations = list(permutations) permutationSets[tuple(set)] = permutations else: # logging.info("This set was already in the dictionary") permutations = permutationSets[tuple(set)] conflictCounter = [] for permIndex, perm in enumerate(permutations): block = day[set[0]][set[1] : (set[2] + 1)] day[set[0]][set[1] : (set[2] + 1)] = perm conflicts = 0 for i, slot in enumerate(day[0]): conflicts += len(planning.conflictedTeachers(day, i)) conflictCounter.append(conflicts) lowestValue = min(conflictCounter) bestOptions = [enum for enum, x in enumerate(conflictCounter) if x == lowestValue] bestOption = random.choice(bestOptions) newList = permutations[bestOption] day[set[0]][set[1] : set[2] + 1] = newList logging.info("Total conflicts: " + str(lowestValue)) if lowestValue == 0: break if lowestValue == 0: break if time.clock() - start > 600: break planning.outputHTML() for dayIndex, day in enumerate(planning.days): for tableIndex, table in enumerate(day): for slotIndex, slot in enumerate(table): if slot != None: new_appointment = Appointment( request=slot, day=days[dayIndex], table=tableIndex, slot=slotIndex ) new_appointment.put()
def test_time_since(self): d1 = Day(2001, 1, 1) d2 = d1 + 10 self.assertAlmostEqual(d2.time_since(d1), 10.0 / 365.25, 1e03)
def get(self, arg): event = Event.get_by_id(int(arg)) notifications = [] if not event: notifications.append("De bewerking kon niet worden voltooid omdat het event niet bestaat.") events = Event.all() path = os.path.join(os.path.dirname(__file__), '../templates/administration/event-list.html') template_values = {'events': events, 'logoutlink': users.create_logout_url("/") , 'notifications': notifications } self.response.out.write(template.render(path, template_values)) return requests = event.requests.fetch(9999) guardians_keys = [] for request in requests: if request.guardian.key().name() not in guardians_keys: guardians_keys.append(request.guardian.key().name()) if not guardians_keys: notifications.append("Er zijn geen voogden met verzoeken") events = Event.all() path = os.path.join(os.path.dirname(__file__), '../templates/administration/event-list.html') template_values = {'events': events, 'logoutlink': users.create_logout_url("/") , 'notifications': notifications } self.response.out.write(template.render(path, template_values)) return for guardian_num, guardian_key in enumerate(guardians_keys): guardian = Guardian.get_by_key_name(guardian_key) guardian_requests = Request.gql("WHERE guardian = :1 AND event = :2", guardian, event).fetch(999) guardian_appointments = [guardian_request.appointment.get() for guardian_request in guardian_requests if guardian_request.appointment.get()] day_ids = [appointment.day.key().id() for appointment in guardian_appointments if appointment] day_ids = list(set(day_ids)) if not guardian_appointments: continue mail = Email() message = 'Beste ' + guardian.title if not guardian.preposition == '': message += ' ' + guardian.preposition message += ' ' + guardian.lastname + ',\n\n' message += 'Er zijn afspraken ingepland voor de ouderavond(en) van het ' + event.event_name + ". " message += 'Hieronder vind u de afspraken die voor u zijn gemaakt:\n\n' for day_id in day_ids: day = Day.get_by_id(day_id) message += 'Op ' + str(day.date.day) + ' ' + AdministrationInviteGuardiansHandler.getMonthText(self, day.date.month) + ' ' + str(day.date.year) + ':\n' for appointment in guardian_appointments: if appointment.day.key().id() == day_id: student = appointment.request.student m = event.talk_time * appointment.slot d = timedelta(minutes=m) time = day.date + d message += 'Tijd: ' + str(time.hour) + ':' + str(time.minute) + '\n' message += 'Tafel: ' + str(appointment.table) + '\n' message += 'Leerling: ' + student.firstname + ' ' + student.preposition + ' ' + student.lastname + '\n' message += 'Vak: ' + appointment.request.combination.subject.name + '\n' message += 'Docent: ' + appointment.request.combination.teacher.name + '\n' message += 'Docentcode: ' + appointment.request.combination.teacher.key().name() + '\n\n' # mail.sendMail(guardian.email, 'Afspraken ouderavond(en) ' + event.event_name, message) if guardian_num == 0: print message return
def ProjectNextDay(self): i_ProjectedNewCases = self.ProjectNewCases() o_Day = Day(i_DayNumber=self.i_Cursor, i_NewCases=i_ProjectedNewCases, d_ActiveCases=self.d_ActiveCases, d_PreviousData=self.d_CaseHistory) return o_Day
def post(self, eventId, guardianId): '''The visitor is not an authenticated guardian''' if not SubscriptionLoginHandler.isAuthenticatedGuardian(): self.redirect('/inschrijven/') return '''The guardian is not authorized to the given''' if not self.isAuthorized(eventId, guardianId): SubscriptionLoginHandler.redirectToSubscriptionPage(self) return event = Event.get_by_id(int(eventId)) days = Day.gql("WHERE event = :1", event).fetch(999) guardian = Guardian.get_by_key_name(guardianId) students = Student.gql("WHERE guardian = :1", guardian).fetch(999, 0) students_subjects = self.getStudentsSubjects(students) notifications = [] templVal = { 'event': event, 'days': days, 'guardian': guardian, 'students': students_subjects, 'notifications': notifications } if not (event and days and guardian and students): notifications.append('U probeert een onmogelijke bewerking uit te voeren.') self.showError(templVal) return subscriptionDetailsList = SubscriptionDetails.gql("WHERE event = :1 AND guardian = :2", event, guardian).fetch(1, 0) if not subscriptionDetailsList: notifications.append('Pagina niet gevonden.') self.showError(templVal) return subscriptionDetails = subscriptionDetailsList[0] if subscriptionDetails and subscriptionDetails.requested: notifications.append('U kunt geen verzoeken meer indienen.') self.showError(templVal) return studentKeys = [str(k.replace('subject_', '')) for k in self.request.arguments() if re.match("subject_.+", k)] requests = [] dayPrefs = [] for s in students[:]: if str(s.key().name()) not in studentKeys: students.remove(s) if not students: notifications.append('U kunt geen verzoek indienen als u geen enkel vak geselecteerd heeft. ') for student in students[:]: subjectCodes = [c for c in self.request.get_all("subject_" + str(student.key().name()))] subjects = Subject.get_by_key_name(subjectCodes) if len(subjectCodes) > 3: notifications.append('U kunt maximaal 3 vakken per leerling bespreken.') if len(subjectCodes) != len(subjects): notifications.append('U probeert een onmogelijke bewerking uit te voeren.') for subject in subjects: combination = Combination.gql("WHERE class_id = :1 AND subject = :2", student.class_id, subject).fetch(1,0)[0] if not combination: notifications.append('U probeert een onmogelijke bewerking uit te voeren.') self.showError(templVal) return request = Request() request.event = event request.guardian = guardian request.student = student request.combination = combination requests.append(request) '''Process timepreference''' timePref = TimePreference() timePref.event = event timePref.guardian = guardian timePref.preference = 0 if not (self.request.get('time_pref') and (int(self.request.get('time_pref')) in [0,1,2])): notifications.append('U moet een voorkeur voor tijd aangeven.') else: timePref.preference = int(self.request.get('time_pref')) '''Check if dates from the form match the dates from the event ''' dayKeys = [long(k.replace('date_', '')) for k in self.request.arguments() if re.match("date_.+", k)] dayKeysFromStore= [day.key().id() for day in days] daysOk = True for dayKey in dayKeys: if dayKey not in dayKeysFromStore: daysOk = False notifications.append('U probeert een onmogelijke bewerking uit te voeren.') self.showError(templVal) return '''Check if the daypreference are correct filled in''' dayPrefsList = [int(self.request.get(k)) for k in self.request.arguments() if re.match("date_.+", k)] dayPrefsList.sort() dayPrefsOk = True if dayPrefsList != [1,2,3]: dayPrefsOk = False notifications.append('U moet een eerste, een tweede en een derde voorkeur aangeven') '''Process daypreferences''' if daysOk and dayPrefsOk: for day in days: dayPref = DayPreference() dayPref.day = day dayPref.guardian = guardian dayPref.rank = int(self.request.get("date_" + str(day.key().id()))) dayPrefs.append(dayPref) if notifications: path = os.path.join(os.path.dirname(__file__), '../templates/subscription/subscription.html') self.response.out.write(template.render(path, templVal)) return '''Store the requests''' for request in requests: request.put() for dayPref in dayPrefs: dayPref.put() timePref.put() subscriptionDetails.requested = True subscriptionDetails.put() SubscriptionLogoutHandler.logoutGuardian() path = os.path.join(os.path.dirname(__file__), '../templates/subscription/subscription-success.html') self.response.out.write(template.render(path, templVal)) return