rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
@unittest2.expectedFailure
def test_with_dsym(self): """Test 'image lookup -t days' and check for correct display.""" self.buildDsym() self.image_lookup_for_enum_type()
for import_name, import_mod in mod.mv.imports.items(): var = defaultvar(import_name, None) var.imported = True getgx().types[inode(var)] = set([(import_mod, 0)]) self.imports[import_name] = import_mod
def visitFrom(self, node, parent=None): if not node in getmv().importnodes: # XXX use (func, node) as parent.. error("please place all imports (no 'try:' etc) at the top of the file", node) if hasattr(node, 'level') and node.level: error("relative imports are not supported", node)
label = Label(root)
label = Label(root, width=70, height=40)
def __init__(self, root, viewports): self.root = root self.viewports = viewports self.topButtonFrame = Frame(root) self.topButtonFrame.pack(side=TOP) self.botButtonFrame = Frame(root) self.botButtonFrame.pack(side=BOTTOM) self.button = Button(self.topButtonFrame, text="Quit", command=self.shutdown) self.button.pack(side=LEFT)
opts, args = getopt.getopt(sys.argv[1:], 'vbchef:wad:m:rl', ['extmod', 'nobounds', 'nowrap', 'flags=', 'dir=', 'makefile=', 'random', 'long', 'msvc'])
opts, args = getopt.getopt(sys.argv[1:], 'vbchef:wad:m:rl', ['help', 'extmod', 'nobounds', 'nowrap', 'flags=', 'dir=', 'makefile=', 'random', 'long', 'msvc', 'ann'])
def main(): setgx(newgx()) print '*** SHED SKIN Python-to-C++ Compiler 0.6 ***' print 'Copyright 2005-2010 Mark Dufour; License GNU GPL version 3 (See LICENSE)' print # --- some checks major, minor = sys.version_info[:2] if (major, minor) not in [(2, 4), (2, 5), (2, 6)]: print '*ERROR* Shed Skin is not compatible with this version of Python' sys.exit(1) if sys.platform == 'win32' and os.path.isdir('c:/mingw'): print '*ERROR* please rename or remove c:/mingw, as it conflicts with Shed Skin' sys.exit() # --- command-line options try: opts, args = getopt.getopt(sys.argv[1:], 'vbchef:wad:m:rl', ['extmod', 'nobounds', 'nowrap', 'flags=', 'dir=', 'makefile=', 'random', 'long', 'msvc']) except getopt.GetoptError: usage() for o, a in opts: if o in ['-h', '--help']: usage() if o in ['-b', '--nobounds']: getgx().bounds_checking = False if o in ['-e', '--extmod']: getgx().extension_module = True if o in ['-a', '--ann']: getgx().annotation = True if o in ['-d', '--dir']: getgx().output_dir = a if o in ['-l', '--long']: getgx().longlong = True if o in ['-w', '--nowrap']: getgx().wrap_around_check = False if o in ['-r', '--random']: getgx().fast_random = True if o in ['-m', '--makefile']: getgx().makefile_name = a if o in ['-v', '--msvc']: getgx().msvc = True if o in ['-f', '--flags']: if not os.path.isfile(a): print "*ERROR* no such file: '%s'" % a sys.exit(1) getgx().flags = a # --- argument if len(args) != 1: usage() name = args[0] if not name.endswith('.py'): name += '.py' if not os.path.isfile(name): print "*ERROR* no such file: '%s'" % name sys.exit(1) getgx().main_mod = name[:-3] # --- analyze & annotate infer.analyze(name) annotate.annotate() cpp.generate_code()
self.timer = gobject.timeout_add(20, self.fire_timer)
self.timer = gobject.timeout_add(50, self.fire_timer)
def set_timer(self): self.timer = gobject.timeout_add(20, self.fire_timer)
if self.CPU_clock: gobject.source_remove(self.CPU_clock)
if self.timer: gobject.source_remove(self.timer)
def pause_CPU(self, widget, *args, **kwargs): # FIXME abstract that properly. if self.CPU_clock: gobject.source_remove(self.CPU_clock) widget.set_label("_Continue") self.CPU_clock = None else: self.CPU_clock = gobject.timeout_add(10, C64.iterate) widget.set_label("_Pause")
self.CPU_clock = None
self.timer = None
def pause_CPU(self, widget, *args, **kwargs): # FIXME abstract that properly. if self.CPU_clock: gobject.source_remove(self.CPU_clock) widget.set_label("_Continue") self.CPU_clock = None else: self.CPU_clock = gobject.timeout_add(10, C64.iterate) widget.set_label("_Pause")
self.CPU_clock = gobject.timeout_add(10, C64.iterate)
self.set_timer()
def pause_CPU(self, widget, *args, **kwargs): # FIXME abstract that properly. if self.CPU_clock: gobject.source_remove(self.CPU_clock) widget.set_label("_Continue") self.CPU_clock = None else: self.CPU_clock = gobject.timeout_add(10, C64.iterate) widget.set_label("_Pause")
return lookupclass(cl.node.bases[0], getmv())
return cl.node.bases[0]
def supercall(self, node, parent): while isinstance(parent, function): parent = parent.parent if (isinstance(node.expr, CallFunc) and \ node.attrname not in ('__getattr__', '__setattr__') and \ isinstance(node.expr.node, Name) and \ node.expr.node.name == 'super'): if (len(node.expr.args) >= 2 and \ isinstance(node.expr.args[1], Name) and node.expr.args[1].name=='self'): cl = lookupclass(node.expr.args[0], getmv()) if cl.node.bases: return lookupclass(cl.node.bases[0], getmv()) error("unsupported usage of 'super'", node)
supercall = self.supercall(node.node, func) if supercall: node.node = Getattr(Name(supercall.ident), node.node.attrname)
base = self.supercall(node.node, func) if base: node.node = Getattr(copy.deepcopy(base), node.node.attrname)
def visitCallFunc(self, node, func=None): # XXX clean up!! newnode = cnode(node, parent=func)
propagate(10)
propagate(0)
def lookahead(): # mods: [list(int)] global lit_mask lit_mask = [1]
def supercall(self, node, parent):
def supercall(self, orig, parent): node = orig.node
def supercall(self, node, parent): while isinstance(parent, function): parent = parent.parent if (isinstance(node.expr, CallFunc) and \ node.attrname not in ('__getattr__', '__setattr__') and \ isinstance(node.expr.node, Name) and \ node.expr.node.name == 'super'): if (len(node.expr.args) >= 2 and \ isinstance(node.expr.args[1], Name) and node.expr.args[1].name=='self'): cl = lookupclass(node.expr.args[0], getmv()) if cl.node.bases: return cl.node.bases[0] error("unsupported usage of 'super'", node)
error("unsupported usage of 'super'", node)
error("unsupported usage of 'super'", orig)
def supercall(self, node, parent): while isinstance(parent, function): parent = parent.parent if (isinstance(node.expr, CallFunc) and \ node.attrname not in ('__getattr__', '__setattr__') and \ isinstance(node.expr.node, Name) and \ node.expr.node.name == 'super'): if (len(node.expr.args) >= 2 and \ isinstance(node.expr.args[1], Name) and node.expr.args[1].name=='self'): cl = lookupclass(node.expr.args[0], getmv()) if cl.node.bases: return cl.node.bases[0] error("unsupported usage of 'super'", node)
base = self.supercall(node.node, func)
base = self.supercall(node, func)
def visitCallFunc(self, node, func=None): # XXX clean up!! newnode = cnode(node, parent=func)
food_type_file.write(str(float(univ.total_food)/float(univ.total_wrong_food))+ '\n')
univ.food_type_file.write(str(float(univ.total_food)/float(univ.total_wrong_food))+ '\n')
def record(univ): ctime = univ.ttime points_file=open(univ.folder_name+'/points'+(str(ctime/1000000)),'w') points_file.write('points: '+ str(univ.points) +' rewarded: ' + str(univ.reward)) connex_final_file=open(univ.folder_name+'/connex'+(str(ctime/1000000)),'w') food_file=open(univ.folder_name+'/burger_time','w') out_spike_file=open(univ.folder_name+'/out_spike','w') if univ.total_wrong_food > 0: food_type_file.write(str(float(univ.total_food)/float(univ.total_wrong_food))+ '\n') connex_final_file.write(str(univ.lmax)+'\n') for layer_size in univ.layer_sizes: connex_final_file.write(str(layer_size[0]) +' ' + str(layer_size[1]) + ' '+ str(layer_size[2]) + '\n') for syn_sum in univ.synsumco: connex_final_file.write(str(syn_sum) + ' ' ) connex_final_file.write('\n') for layer in univ.spirit_brain.cell_array: for row in layer: for item in row: for cell in item: for connection in cell.connections: other_cell = connection.post_cell connex_final_file.write( str(cell.cell_type) + ' ' + str(cell.layer) + ' ' + str(cell.x) + ' ' + str(cell.y) + ' ' + str(other_cell.cell_type) + ' ' +str(other_cell.layer) + ' ' + str(other_cell.x) + ' ' + str(other_cell.y) + ' ' + str(connection.s) + ' ' + str(int(connection.fast))+ ' ' + str(int(connection.plastic)) +'\n') univ.food_times.append(ctime) for food_time in univ.food_times: food_file.write(str(food_time) +'\n') univ.out_spikes.append(ctime) for out_spike in univ.out_spikes: out_spike_file.write(str(out_spike) +'\n') points_file.close() connex_final_file.close() food_file.close() out_spike_file.close()
blah = Blah(7, 'eight') woef(1)
class do: def __init__(self, public, do): self.public = public self.do = do if __name__ == '__main__': blah = Blah(7, 'eight') woef(1) d = do('public', 'do')
def woef(x): print x
d = (1, (1.1, 'u')) a, (b, c) = d e, f = d for x,(y,z) in [d]: x y z l = [((v,u),w) for u,(v,w) in [d]] print 'u', l
d = (1, (1.1, 'u')) a, (b, c) = d e, f = d for x,(y,z) in [d]: x y z l = [((v,u),w) for u,(v,w) in [d]] print 'uh', '%.2f %d' % l[0][0], l[0][1], len(l)
def _sum(l): # l: [pyiter(A)] first = True # [int] for e in l: # [pyiter(A)] if first: # [] result = e # [A] first = False # [int] else: result += e # [A] return result # [A]
if cl.module not in [getmv().module, getgx().modules['builtin']] and not (cl.ident in getmv().ext_funcs or cl.ident in getmv().ext_classes): if cplusplus: namespace = cl.module.full_path()+'::' else: namespace = '::'.join(cl.module.mod_path)+'::'
if cl.module not in [getmv().module, getgx().modules['builtin']]: if not (cl.ident in getmv().ext_funcs or cl.ident in getmv().ext_classes): if cplusplus: namespace = cl.module.full_path()+'::' else: namespace = '::'.join(cl.module.mod_path)+'::'
def map(ident): if cplusplus: return ident+' *' return conv.get(ident, ident)
print >>gv.out, ' __%s__::%s *__ss_object;' % (cl.module.ident, cl.ident)
print >>gv.out, ' __%s__::%s *__ss_object;' % (cl.module.ident, cpp.nokeywords(cl.ident))
print >>gv.out, 'typedef struct {'
print >>gv.out, ' self->__ss_object = new __%s__::%s();' % (cl.module.ident, cl.ident)
print >>gv.out, ' self->__ss_object = new __%s__::%s();' % (cl.module.ident, cpp.nokeywords(cl.ident))
print >>gv.out, 'typedef struct {'
print >>gv.out, 'PyObject *%s::__to_py__() {' % cl.cpp_name
print >>gv.out, 'PyObject *%s::__to_py__() {' % cpp.nokeywords(cl.ident)
def convert_methods(gv, cl, declare): if declare: print >>gv.out, ' PyObject *__to_py__();' else: print >>gv.out, 'namespace __%s__ { /* XXX */\n' % cl.module.ident print >>gv.out, 'PyObject *%s::__to_py__() {' % cl.cpp_name print >>gv.out, ' if(__ss_proxy->has_key(this))' print >>gv.out, ' return (PyObject *)(__ss_proxy->__getitem__(this));' print >>gv.out, ' %sObject *self = (%sObject *)(%sObjectType.tp_alloc(&%sObjectType, 0));' % (4*(cl.ident,)) print >>gv.out, ' self->__ss_object = this;' print >>gv.out, ' __ss_proxy->__setitem__(self->__ss_object, self);' print >>gv.out, ' return (PyObject *)self;' print >>gv.out, '}\n}\n' print >>gv.out, 'namespace __shedskin__ { /* XXX */\n' print >>gv.out, 'template<> __%s__::%s *__to_ss(PyObject *p) {' % (cl.module.ident, cl.cpp_name) print >>gv.out, ' if(p == Py_None) return NULL;' print >>gv.out, ' if(PyObject_IsInstance(p, (PyObject *)&__%s__::%sObjectType)!=1)' % (cl.module.ident, cl.ident) print >>gv.out, ' throw new TypeError(new str("error in conversion to Shed Skin (%s expected)"));' % cl.ident print >>gv.out, ' return ((__%s__::%sObject *)p)->__ss_object;' % (cl.module.ident, cl.ident) print >>gv.out, '}\n}'
print >>gv.out, 'template<> __%s__::%s *__to_ss(PyObject *p) {' % (cl.module.ident, cl.cpp_name)
print >>gv.out, 'template<> __%s__::%s *__to_ss(PyObject *p) {' % (cl.module.ident, cpp.nokeywords(cl.ident))
def convert_methods(gv, cl, declare): if declare: print >>gv.out, ' PyObject *__to_py__();' else: print >>gv.out, 'namespace __%s__ { /* XXX */\n' % cl.module.ident print >>gv.out, 'PyObject *%s::__to_py__() {' % cl.cpp_name print >>gv.out, ' if(__ss_proxy->has_key(this))' print >>gv.out, ' return (PyObject *)(__ss_proxy->__getitem__(this));' print >>gv.out, ' %sObject *self = (%sObject *)(%sObjectType.tp_alloc(&%sObjectType, 0));' % (4*(cl.ident,)) print >>gv.out, ' self->__ss_object = this;' print >>gv.out, ' __ss_proxy->__setitem__(self->__ss_object, self);' print >>gv.out, ' return (PyObject *)self;' print >>gv.out, '}\n}\n' print >>gv.out, 'namespace __shedskin__ { /* XXX */\n' print >>gv.out, 'template<> __%s__::%s *__to_ss(PyObject *p) {' % (cl.module.ident, cl.cpp_name) print >>gv.out, ' if(p == Py_None) return NULL;' print >>gv.out, ' if(PyObject_IsInstance(p, (PyObject *)&__%s__::%sObjectType)!=1)' % (cl.module.ident, cl.ident) print >>gv.out, ' throw new TypeError(new str("error in conversion to Shed Skin (%s expected)"));' % cl.ident print >>gv.out, ' return ((__%s__::%sObject *)p)->__ss_object;' % (cl.module.ident, cl.ident) print >>gv.out, '}\n}'
print >>gv.out, 'static PyTypeObject %sObjectType = {' % cl.ident
print >>gv.out, 'PyTypeObject %sObjectType = {' % cl.ident
print >>gv.out, 'typedef struct {'
version='alpha-0.171',
version='alpha-0.172',
def fullsplit(path, result=None): """ Split a pathname into components (the opposite of os.path.join) in a platform-neutral way. """ if result is None: result = [] head, tail = os.path.split(path) if head == '': return [tail] + result if head == path: return result return fullsplit(head, [tail] + result)
self.widget = AjaxForeignKeyWidget(attrs={'type': key_type, 'width': 35, 'ajax_func': ajax_func, 'shadow_field': shadow_field_name})
self.widget = AjaxForeignKeyWidget(attrs={'type': key_type, 'width': 35, 'ajax_func': ajax_func, 'shadow_field': shadow_field_name, 'field_name': field_name})
def __init__(self, field_name='', field=None, key_type=None, to_field=None, to_field_name=None, required=True, label='', localize=False, initial=None, widget=None, help_text='', ajax_func=None, queryset=None, error_messages=None, show_hidden_initial=False, shadow_field_name=None, *args, **kwargs):
context['program'] = self.program
context['program'] = prog
def get_student_schedules(request, students, prog, extra='', onsite=False): """ generate student schedules """
basedir = 'program/modules/programprintables/'
def get_student_schedules(request, students, prog, extra='', onsite=False): """ generate student schedules """
return render_to_response(self.baseDir()+'studentschedule.html', request, (prog, tl), context)
return render_to_response(basedir+'studentschedule.html', request, (prog, tl), context)
def get_student_schedules(request, students, prog, extra='', onsite=False): """ generate student schedules """
schedule_template = select_template([self.baseDir()+'program_custom_schedules/%s_studentschedule.tex' %(self.program.id), self.baseDir()+'studentschedule.tex'])
schedule_template = select_template([basedir+'program_custom_schedules/%s_studentschedule.tex' %(prog.id), basedir+'studentschedule.tex'])
def get_student_schedules(request, students, prog, extra='', onsite=False): """ generate student schedules """
@register.filter def makelist(lst): if len(lst) == 0: return 'No responses' result = '' for item in lst: result += '<li>' + str(item) + '</li>' + '\n' return result
def drop_empty_answers(lst): # Takes a list of answers and drops empty ones. Whitespace-only is empty. return [ ans for ans in lst if (not isinstance(ans.answer, basestring)) or ans.answer.strip() ]
def list_classes(ans): if not isinstance(ans, list): return ans newlist = [] for key in ans: try: intkey = int(key) except ValueError: return '<ul>\n' + makelist( ans ) + '</ul>\n' q = ClassSubject.objects.filter(id=intkey) if q.count() == 1: newlist.extend( [ c.emailcode() + ': ' + c.title() for c in q ] ) else: newlist.append( key ) return '<ul>\n' + makelist( newlist ) + '</ul>\n'
def answer_to_list(ans): if isinstance(ans.answer, list): value = ans.answer else: value = [ ans.answer ] if ans.question.question_type.name == 'Favorite Class': return [ c.emailcode() + ': ' + c.title() for c in ClassSubject.objects.filter(id__in=value) ] return value
def list_classes(ans): # If the answer is a list of classes, render a shiny list of their titles. # If the answer is an ordinary list, prettify the list. # Otherwise just spit the answer back out. # Kind of inelegant, but I didn't want to make yet another set of templates. if not isinstance(ans, list): return ans newlist = [] for key in ans: try: intkey = int(key) except ValueError: return '<ul>\n' + makelist( ans ) + '</ul>\n' # If we get a non-integer answer, quit early. q = ClassSubject.objects.filter(id=intkey) if q.count() == 1: newlist.extend( [ c.emailcode() + ': ' + c.title() for c in q ] ) else: newlist.append( key ) # If no class matches, spit out the raw answer. return '<ul>\n' + makelist( newlist ) + '</ul>\n'
if Tag.getTag('ask_about_duplicate_accounts', default='False') == 'True':
if Tag.getTag('require_email_validation', default='False') == 'True':
def user_registration(request): """ Registration view -- takes care of users who want to create a new account. """ if request.user.is_authenticated(): return render_to_response('registration/already_logged_in.html', request, request.get_node('Q/Web/myesp'), {}) if request.method == 'POST': form = UserRegForm(request.POST) if form.is_valid(): ## First, check to see if we have any users with the same e-mail if not 'do_reg_no_really' in request.POST and Tag.getTag('ask_about_duplicate_accounts', default='False') == 'True': existing_accounts = User.objects.filter(email=form.cleaned_data['email'], is_active=True).exclude(password='emailuser') if len(existing_accounts) != 0: return render_to_response('registration/newuser.html', request, request.get_node('Q/Web/myesp'), { 'accounts': existing_accounts, 'form': form, 'site': Site.objects.get_current() }) try: user = User.objects.get(email=form.cleaned_data['email'], password = 'emailuser') except User.DoesNotExist: try: user = User.objects.filter(username = form.cleaned_data['username'], is_active = False).latest('date_joined') except User.DoesNotExist: user = User(email = form.cleaned_data['email']) user.username = form.cleaned_data['username'] user.last_name = form.cleaned_data['last_name'] user.first_name = form.cleaned_data['first_name'] user.set_password(form.cleaned_data['password']) # Append key to password and disable until activation if desired if Tag.getTag('ask_about_duplicate_accounts', default='False') == 'True': userkey = random.randint(0,2**31 - 1) user.password += "_%d" % userkey user.is_active = False user.save() ESPUser_Profile.objects.get_or_create(user = user) role_verb = GetNode('V/Flags/UserRole/%s' % form.cleaned_data['initial_role']) role_bit = UserBit.objects.create(user = user, verb = role_verb, qsc = request.get_node('Q'), recursive = False) if Tag.getTag('require_email_validation', default='False') == 'False': user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']) login(request, user) return HttpResponseRedirect('/myesp/profile/') else: from django.template import Context as RawContext t = loader.get_template('registration/activation_email.txt') c = RawContext({'user': user, 'activation_key': userkey, 'site': Site.objects.get_current()}) send_mail("Account Activation", t.render(c), settings.SERVER_EMAIL, [user.email], fail_silently = False) return render_to_response('registration/account_created_activation_required.html', request, request.get_node('Q/Web/myesp'), {'user': user, 'site': Site.objects.get_current()}) else: form = UserRegForm() return render_to_response('registration/newuser.html', request, request.get_node('Q/Web/myesp'),{'form':form})
prog = module.program
prog = module.get_program()
def hide_choice_if_useless(field): """ Hide a choice field if there's only one choice """ if len(field.choices) == 1: hide_field(field, default=field.choices[0][0])
unavailable_teachers = User.objects.filter(id__in=list(teacher_dict['class_approved'])+list(teacher_dict['class_proposed'])).exclude(id__in=teacher_dict['availability']).distinct()
unavailable_teachers = User.objects.filter(id__in=list(teacher_dict['class_approved'].values_list('id', flat=True))+list(teacher_dict['class_proposed'].values_list('id', flat=True))).exclude(id__in=teacher_dict['availability']).distinct()
def force_availability(self, request, tl, one, two, module, extra, prog): teacher_dict = prog.teachers() if request.method == 'POST': if request.POST.has_key('sure') and request.POST['sure'] == 'True': # Find all teachers who have not indicated their availability and do it for them. unavailable_teachers = User.objects.filter(id__in=list(teacher_dict['class_approved'])+list(teacher_dict['class_proposed'])).exclude(id__in=teacher_dict['availability']).distinct() for t in unavailable_teachers: teacher = ESPUser(t) for ts in prog.getTimeSlots(): teacher.addAvailableTime(self.program, ts) return self.scheduling(request, tl, one, two, module, 'refresh', prog) else: return self.scheduling(request, tl, one, two, module, '', prog) # Normally, though, return a page explaining the issue. context = {'prog': self.program} context['good_teacher_num'] = User.objects.filter(id__in=teacher_dict['class_approved']).filter(id__in=teacher_dict['availability']).distinct().count() context['total_teacher_num'] = User.objects.filter(id__in=teacher_dict['class_approved']).distinct().count()
break if not module: raise Http404
return ProgramModuleObj.getFromProgModule(prog, module)
def findModuleObject(tl, call_txt, prog): modules = ProgramModule.objects.filter(main_call = call_txt, module_type = tl).select_related()[:1]
if not module: raise Http404 return ProgramModuleObj.getFromProgModule(prog, module)
return ProgramModuleObj.getFromProgModule(prog, module) raise Http404
def findModuleObject(tl, call_txt, prog): modules = ProgramModule.objects.filter(main_call = call_txt, module_type = tl).select_related()[:1]
if tl != "manage" and request.user.is_authenticated() and isinstance(moduleobj, CoreModule): other_modules = moduleobj.findCategoryModules(False) for m in other_modules: m.request = request m.user = user if not m.isCompleted() and hasattr(m, m.module.main_call): return getattr(m, m.module.main_call)(request, tl, one, two, call_txt, extra, prog)
def findModule(request, tl, one, two, call_txt, extra, prog): moduleobj = ProgramModuleObj.findModuleObject(tl, call_txt, prog) user = ESPUser(request.user) # If a "core" module has been found: # Put the user through a sequence of all required modules in the same category. if tl != "manage" and request.user.is_authenticated() and isinstance(moduleobj, CoreModule): other_modules = moduleobj.findCategoryModules(False) for m in other_modules: m.request = request m.user = user if not m.isCompleted() and hasattr(m, m.module.main_call): return getattr(m, m.module.main_call)(request, tl, one, two, call_txt, extra, prog)
sqlcontent = str(sqlcontent)
sqlcontent = unicodedata.normalize('NFKD', unicode(sqlcontent)).encode('ascii', 'ignore')
def process_response(self, request, response):
qs = self.registrations.filter(id=user.id, studentregistration__start_date__lte=now, studentregistration__end_date__gte=now)
rt = RegistrationType.get_cached(name=prereg_verb, category='student') qs = self.registrations.filter(id=user.id, studentregistration__start_date__lte=now, studentregistration__end_date__gte=now, studentregistration__relationship=rt)
def preregister_student(self, user, overridefull=False, priority=1, prereg_verb = None, fast_force_create=False): StudentRegistration, RegistrationType = self.StudentRegistration, self.RegistrationType
rt = RegistrationType.get_cached(name=prereg_verb, category='student')
def preregister_student(self, user, overridefull=False, priority=1, prereg_verb = None, fast_force_create=False): StudentRegistration, RegistrationType = self.StudentRegistration, self.RegistrationType
if include_optional:
if not include_optional:
def findCategoryModules(self, include_optional): prog = self.program module_type = self.module.module_type
if tl != "manage" and request.user.is_authenticated() and isinstance(moduleobj, CoreModule): other_modules = moduleobj.findCategoryModules(False) for m in other_modules: m.request = request m.user = user if not isinstance(m, CoreModule) and not m.isCompleted() and hasattr(m, m.module.main_call): return getattr(m, m.module.main_call)(request, tl, one, two, call_txt, extra, prog)
def findModule(request, tl, one, two, call_txt, extra, prog): moduleobj = ProgramModuleObj.findModuleObject(tl, call_txt, prog) user = ESPUser(request.user) # If a "core" module has been found: # Put the user through a sequence of all required modules in the same category. #if tl != "manage" and request.user.is_authenticated() and isinstance(moduleobj, CoreModule): # other_modules = moduleobj.findCategoryModules(False) # for m in other_modules: # m.request = request # m.user = user # if not m.isCompleted() and hasattr(m, m.module.main_call): # return getattr(m, m.module.main_call)(request, tl, one, two, call_txt, extra, prog)
return tmpModule.deadline_met('/Classes/Create')
return tmpModule.deadline_met('/Classes/Create') or tmpModule.deadline_met('/Classes/Edit')
def deadline_met(self, extension=''): if self.user.isAdmin(self.program): return True if len(extension) > 0: return super(TeacherClassRegModule, self).deadline_met(extension)
sections = self.getEnrolledSectionsFromProgram(program).order_by('meeting_times')
sections = self.getSections(program, verbs=['Enrolled']).order_by('meeting_times')
def getFirstClassTime(self, program): sections = self.getEnrolledSectionsFromProgram(program).order_by('meeting_times') if sections.count() == 0: return None else: if sections[0].meeting_times.count() == 0: return None else: return sections[0].meeting_times.order_by('start')[0]
output.append(normal_row % {'errors': bf_errors, 'label': label, 'field': unicode(bf), 'help_text': help_text})
output.append(normal_row % {'html_class_attr': html_class_attr, 'errors': bf_errors, 'label': label, 'field': unicode(bf), 'help_text': help_text})
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row): "Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()." top_errors = self.non_field_errors() # Errors that should be displayed above all fields. output, hidden_fields = [], [] first = True for name, field in self.fields.items(): if not first: output.append(error_row % '<span class="or">- or -</span>') else: first = False bf = forms.forms.BoundField(self, field, name) bf_errors = forms.util.ErrorList([conditional_escape(error) for error in bf.errors]) # Escape and cache in local variable. if bf.is_hidden: if bf_errors: top_errors.extend(['(Hidden field %s) %s' % (name, e) for e in bf_errors]) hidden_fields.append(unicode(bf)) else: if errors_on_separate_row and bf_errors: output.append(error_row % bf_errors) if bf.label: label = conditional_escape(bf.label) # Only add a colon if the label does not end in punctuation. if label[-1] not in ':?.!': label += ':' label = bf.label_tag(label) or '' else: label = '' if field.help_text: help_text = help_text_html % field.help_text else: help_text = u'' output.append(normal_row % {'errors': bf_errors, 'label': label, 'field': unicode(bf), 'help_text': help_text}) if top_errors: output.insert(0, error_row % top_errors) if hidden_fields: # Insert any hidden fields in the last row. str_hidden = u''.join(hidden_fields) if output: last_row = output[-1] # Chop off the trailing row_ender (e.g. '</td></tr>') and insert the hidden fields. output[-1] = last_row[:-len(row_ender)] + str_hidden + row_ender else: # If there aren't any rows in the output, just append the hidden fields. output.append(str_hidden) return u'\n'.join(output)
open_class_category = ClassCategories.objects.get_or_create(category='Walk-in Seminar', symbol='O', seq=0)[0]
open_class_category = ClassCategories.objects.get_or_create(category='Walk-in Seminar', symbol='W', seq=0)[0]
def hide_field(field, default=None): field.widget = forms.HiddenInput() if default is not None: field.initial = default
all_classes = ClassSubject.objects.filter(anchor__userbit_qsc__verb__id=tr_node.id, anchor__userbit_qsc__user=self).distinct()
when = datetime.now() all_classes = ClassSubject.objects.filter( anchor__userbit_qsc__verb__id=tr_node.id, anchor__userbit_qsc__user=self, anchor__userbit_qsc__startdate__lte=when, anchor__userbit_qsc__enddate__gte=when, ).distinct()
def getTaughtClassesFromProgram(self, program): from esp.program.models import ClassSubject, Program # Need the Class object. # Why is it that we had a find_by_anchor_perms function again? tr_node = GetNode('V/Flags/Registration/Teacher') all_classes = ClassSubject.objects.filter(anchor__userbit_qsc__verb__id=tr_node.id, anchor__userbit_qsc__user=self).distinct()
return ClassSubject.objects.filter(anchor__userbit_qsc__verb__id=tr_node.id, anchor__userbit_qsc__user=self).distinct()
when = datetime.now() return ClassSubject.objects.filter( anchor__userbit_qsc__verb__id=tr_node.id, anchor__userbit_qsc__user=self, anchor__userbit_qsc__startdate__lte=when, anchor__userbit_qsc__enddate__gte=when, ).distinct()
def getTaughtClassesAll(self): from esp.program.models import ClassSubject # Need the Class object. # Why is it that we had a find_by_anchor_perms function again? tr_node = GetNode('V/Flags/Registration/Teacher') return ClassSubject.objects.filter(anchor__userbit_qsc__verb__id=tr_node.id, anchor__userbit_qsc__user=self).distinct()
if reg_form.cleaned_data['optimal_class_size_range']:
if 'optimal_class_size_range' in reg_form.cleaned_data and reg_form.cleaned_data['optimal_class_size_range']:
def set_class_data(self, cls, reg_form): for k, v in reg_form.cleaned_data.items(): if k not in ('category', 'resources', 'viable_times', 'optimal_class_size_range', 'allowable_class_size_ranges') and k[:8] is not 'section_': cls.__dict__[k] = v
if reg_form.cleaned_data['allowable_class_size_ranges']:
if 'allowable_class_size_ranges' in reg_form.cleaned_data and reg_form.cleaned_data['allowable_class_size_ranges']:
def set_class_data(self, cls, reg_form): for k, v in reg_form.cleaned_data.items(): if k not in ('category', 'resources', 'viable_times', 'optimal_class_size_range', 'allowable_class_size_ranges') and k[:8] is not 'section_': cls.__dict__[k] = v
schedule += '%s|%s|%s\n' % ((' '+",".join(cls.friendly_times())).ljust(24), (' ' + cls.title).ljust(40), rooms)
schedule += '%s|%s|%s\n' % ((' '+",".join(cls.friendly_times())).ljust(24), (' ' + cls.title()).ljust(40), rooms)
def getSchedule(program, student): schedule = """
VerbParent = Q(userbit__verb__parent=GetNode("V/Flags/UserRole")) VerbName = Q(userbit__verb__name=stutype)
def students(self, QObject = False): from django.db.models import Q verb_base = DataTree.get_by_uri('V/Flags/Registration')
class MultihostCacheClassTest(MemcachedTestCase): """ Test cases for the memcached_multihost CacheClass class """ CACHES = [ "127.0.0.1:11213", "127.0.0.1:11214", "127.0.0.1:11215", "127.0.0.1:11216", "127.0.0.1:11217", "127.0.0.1:11218", "127.0.0.1:11219" ] CACHE_BACKENDS = CACHES[:5] + [ ";".join(CACHES[5:7]) ] def setUp(self):
if MultihostCacheClass: class MultihostCacheClassTest(MemcachedTestCase):
def runTest(self): response = self.client.get('/l' + 'o'*256 + 'ngurl.html') self.failUnless(response.status_code != 500, 'Ridiculous URL not handled gracefully.')
Create and configure a MultihostCacheClass instance to test. Also, our last two servers are actually joined; update accordingly.
Test cases for the memcached_multihost CacheClass class
def setUp(self): """ Create and configure a MultihostCacheClass instance to test. Also, our last two servers are actually joined; update accordingly. """ super(MultihostCacheClassTest, self).setUp()
super(MultihostCacheClassTest, self).setUp() for client in self.clients[5:7]: client.disconnect_all() self.clients = self.clients[:5] self._old_REMOTE_CACHE_SERVERS = getattr(settings, 'REMOTE_CACHE_SERVERS', None) settings.REMOTE_CACHE_SERVERS = self.CACHE_BACKENDS[1:3] + self.CACHE_BACKENDS[5:6] self._old_REMOTE_CACHES_TO_FLUSH = getattr(settings, 'REMOTE_CACHES_TO_FLUSH', None) settings.REMOTE_CACHES_TO_FLUSH = self.CACHE_BACKENDS[3:5] self._old_CACHE_PREFIX = settings.CACHE_PREFIX settings.CACHE_PREFIX = "TEST_" self.cacheclass = MultihostCacheClass(self.CACHE_BACKENDS[0], {}) def tearDown(self): """ Clean up our MultihostCacheClass instance """ self.cacheclass.close() super(MultihostCacheClassTest, self).tearDown() settings.REMOTE_CACHE_SERVERS = self._old_REMOTE_CACHE_SERVERS settings.REMOTE_CACHES_TO_FLUSH = self._old_REMOTE_CACHES_TO_FLUSH settings.CACHE_PREFIX = self._old_CACHE_PREFIX def make_key(self, key): """ Make a proper cache key from the given string, by prepending our cache prefix. Recall that the cache clients that we're given are raw memcached clients; they know nothing about Django at all, and they certainly don't know about the custom cache key setup that the Multihost class that we're testing, uses. """ return settings.CACHE_PREFIX + key def validate_inAllClients(self, key, value): """ Validate that the given key is set in all clients to the given value """ for client in self.clients: client_value = client.get( self.make_key(key) ) self.assertEqual(client_value, value) def validate_inUpdatingClients(self, key, value): """ Validate that the given key is set in clients that we're updating, to the given value """ for client in self.clients[0:3] + self.clients[5:6]: client_value = client.get( self.make_key(key) ) self.assertEqual(client_value, value) def validate_inDeleteOnlyClients(self, key, value): """ Validate that the given key is set in clients that we're only flushing, to the given value """ for client in self.clients[3:5]: client_value = client.get( self.make_key(key) ) self.assertEqual(client_value, value) def testGet(self): self.cacheclass.set('testGet', 'key') self.assertEqual('key', self.cacheclass.get('testGet')) def testAdd(self): self.cacheclass.delete("testAdd") self.cacheclass.add('testAdd', 'key') self.validate_inUpdatingClients('testAdd', 'key') self.validate_inDeleteOnlyClients('testAdd', None) self.cacheclass.add('testAdd', 'new_key') self.validate_inUpdatingClients('testAdd', 'key') self.validate_inDeleteOnlyClients('testAdd', None) self.cacheclass.delete("testAddClobber") for client in self.clients[1:]: client.set( self.make_key("testAddClobber"), "some key" ) self.cacheclass.add("testAddClobber", "another key!") self.validate_inDeleteOnlyClients('testAddClobber', None) for client in self.clients[0:3] + self.clients[5:7]: client.set( self.make_key("testAddClobber"), "some key" ) for client in self.clients[3:5]: client.set( self.make_key("testAddClobber"), "a third key!!" ) self.cacheclass.add("testAddClobber", "key that's doomed to get ignored...") self.validate_inUpdatingClients('testAddClobber', 'some key') self.validate_inDeleteOnlyClients('testAddClobber', 'a third key!!') def testSet(self): self.cacheclass.delete('testSet') self.cacheclass.set('testSet', 'key') self.validate_inUpdatingClients('testSet', 'key') self.validate_inDeleteOnlyClients('testSet', None) self.cacheclass.set('testSet', 'new_key') self.validate_inUpdatingClients('testSet', 'new_key') self.validate_inDeleteOnlyClients('testSet', None) for client in self.clients: client.set( self.make_key("testSetClobber"), "some key" ) self.cacheclass.set("testSetClobber", "another key!") self.validate_inUpdatingClients('testSetClobber', 'another key!') self.validate_inDeleteOnlyClients('testSetClobber', None) def testDelete(self): self.cacheclass.delete('testDelete') self.validate_inAllClients('testDelete', None) self.cacheclass.set('testDelete', 'key') self.validate_inUpdatingClients('testDelete', 'key') self.validate_inDeleteOnlyClients('testDelete', None) self.cacheclass.delete('testDelete') self.validate_inAllClients('testDelete', None) def testGetMany(self): keys = ['one', 'two', 'three'] values = ['1', '2', '3'] for key, value in zip(keys, values): self.cacheclass.set(key, value) self.assertEqual(dict(zip(keys, values)), self.cacheclass.get_many(keys)) def testHasKey(self): self.cacheclass.set('test_HasKey', 'Purple Water Buffalo') self.assert_(self.cacheclass.has_key('test_HasKey')) self.assert_(self.cacheclass.__contains__('test_HasKey')) self.assert_('test_HasKey' in self.cacheclass) def testIncrDecr(self): self.cacheclass.set('test_math', 1) self.cacheclass.decr('test_math') self.assertEqual(0, self.cacheclass.get('test_math')) self.cacheclass.incr('test_math') self.cacheclass.incr('test_math') self.cacheclass.incr('test_math') self.assertEqual(3, self.cacheclass.get('test_math'))
CACHES = [ "127.0.0.1:11213", "127.0.0.1:11214", "127.0.0.1:11215", "127.0.0.1:11216", "127.0.0.1:11217", "127.0.0.1:11218", "127.0.0.1:11219" ] CACHE_BACKENDS = CACHES[:5] + [ ";".join(CACHES[5:7]) ] def setUp(self): """ Create and configure a MultihostCacheClass instance to test. Also, our last two servers are actually joined; update accordingly. """ super(MultihostCacheClassTest, self).setUp() for client in self.clients[5:7]: client.disconnect_all() self.clients = self.clients[:5] self._old_REMOTE_CACHE_SERVERS = getattr(settings, 'REMOTE_CACHE_SERVERS', None) settings.REMOTE_CACHE_SERVERS = self.CACHE_BACKENDS[1:3] + self.CACHE_BACKENDS[5:6] self._old_REMOTE_CACHES_TO_FLUSH = getattr(settings, 'REMOTE_CACHES_TO_FLUSH', None) settings.REMOTE_CACHES_TO_FLUSH = self.CACHE_BACKENDS[3:5] self._old_CACHE_PREFIX = settings.CACHE_PREFIX settings.CACHE_PREFIX = "TEST_" self.cacheclass = MultihostCacheClass(self.CACHE_BACKENDS[0], {}) def tearDown(self): """ Clean up our MultihostCacheClass instance """ self.cacheclass.close() super(MultihostCacheClassTest, self).tearDown() settings.REMOTE_CACHE_SERVERS = self._old_REMOTE_CACHE_SERVERS settings.REMOTE_CACHES_TO_FLUSH = self._old_REMOTE_CACHES_TO_FLUSH settings.CACHE_PREFIX = self._old_CACHE_PREFIX def make_key(self, key): """ Make a proper cache key from the given string, by prepending our cache prefix. Recall that the cache clients that we're given are raw memcached clients; they know nothing about Django at all, and they certainly don't know about the custom cache key setup that the Multihost class that we're testing, uses. """ return settings.CACHE_PREFIX + key def validate_inAllClients(self, key, value): """ Validate that the given key is set in all clients to the given value """ for client in self.clients: client_value = client.get( self.make_key(key) ) self.assertEqual(client_value, value) def validate_inUpdatingClients(self, key, value): """ Validate that the given key is set in clients that we're updating, to the given value """ for client in self.clients[0:3] + self.clients[5:6]: client_value = client.get( self.make_key(key) ) self.assertEqual(client_value, value) def validate_inDeleteOnlyClients(self, key, value): """ Validate that the given key is set in clients that we're only flushing, to the given value """ for client in self.clients[3:5]: client_value = client.get( self.make_key(key) ) self.assertEqual(client_value, value) def testGet(self): self.cacheclass.set('testGet', 'key') self.assertEqual('key', self.cacheclass.get('testGet')) def testAdd(self): self.cacheclass.delete("testAdd") self.cacheclass.add('testAdd', 'key') self.validate_inUpdatingClients('testAdd', 'key') self.validate_inDeleteOnlyClients('testAdd', None) self.cacheclass.add('testAdd', 'new_key') self.validate_inUpdatingClients('testAdd', 'key') self.validate_inDeleteOnlyClients('testAdd', None) self.cacheclass.delete("testAddClobber") for client in self.clients[1:]: client.set( self.make_key("testAddClobber"), "some key" ) self.cacheclass.add("testAddClobber", "another key!") self.validate_inDeleteOnlyClients('testAddClobber', None) for client in self.clients[0:3] + self.clients[5:7]: client.set( self.make_key("testAddClobber"), "some key" ) for client in self.clients[3:5]: client.set( self.make_key("testAddClobber"), "a third key!!" ) self.cacheclass.add("testAddClobber", "key that's doomed to get ignored...") self.validate_inUpdatingClients('testAddClobber', 'some key') self.validate_inDeleteOnlyClients('testAddClobber', 'a third key!!') def testSet(self): self.cacheclass.delete('testSet') self.cacheclass.set('testSet', 'key') self.validate_inUpdatingClients('testSet', 'key') self.validate_inDeleteOnlyClients('testSet', None) self.cacheclass.set('testSet', 'new_key') self.validate_inUpdatingClients('testSet', 'new_key') self.validate_inDeleteOnlyClients('testSet', None) for client in self.clients: client.set( self.make_key("testSetClobber"), "some key" ) self.cacheclass.set("testSetClobber", "another key!") self.validate_inUpdatingClients('testSetClobber', 'another key!') self.validate_inDeleteOnlyClients('testSetClobber', None) def testDelete(self): self.cacheclass.delete('testDelete') self.validate_inAllClients('testDelete', None) self.cacheclass.set('testDelete', 'key') self.validate_inUpdatingClients('testDelete', 'key') self.validate_inDeleteOnlyClients('testDelete', None) self.cacheclass.delete('testDelete') self.validate_inAllClients('testDelete', None) def testGetMany(self): keys = ['one', 'two', 'three'] values = ['1', '2', '3'] for key, value in zip(keys, values): self.cacheclass.set(key, value) self.assertEqual(dict(zip(keys, values)), self.cacheclass.get_many(keys)) def testHasKey(self): self.cacheclass.set('test_HasKey', 'Purple Water Buffalo') self.assert_(self.cacheclass.has_key('test_HasKey')) self.assert_(self.cacheclass.__contains__('test_HasKey')) self.assert_('test_HasKey' in self.cacheclass) def testIncrDecr(self): self.cacheclass.set('test_math', 1) self.cacheclass.decr('test_math') self.assertEqual(0, self.cacheclass.get('test_math')) self.cacheclass.incr('test_math') self.cacheclass.incr('test_math') self.cacheclass.incr('test_math') self.assertEqual(3, self.cacheclass.get('test_math'))
def setUp(self): """ Create and configure a MultihostCacheClass instance to test. Also, our last two servers are actually joined; update accordingly. """ super(MultihostCacheClassTest, self).setUp()
print initial_data
def __init__(self, user=None, *args, **kwargs): super(StudentInfoForm, self).__init__(user, *args, **kwargs)
print "There exists student info!"
def clean(self): cleaned_data = self.cleaned_data user = self._user
cleaned_data['graduation_year'] = orig_prof.student_info.graduation_year
def clean(self): cleaned_data = self.cleaned_data user = self._user
cleaned_data['dob'] = orig_prof.student_info.dob
def clean(self): cleaned_data = self.cleaned_data user = self._user
for field_name in self._field_names: if not initial_dict.has_key(form_prefix + '-' + field_name): initial_dict[form_prefix + '-' + field_name] = getattr(self, field_name)
if not populating_from_form: for field_name in self._field_names: initial_dict[form_prefix + '-' + field_name] = getattr(self, field_name)
def get_field_by_name(name): for f in self._meta.fields: if f.name == name: return f return None
'text': s.title,
'text': s.title(),
def ajax_sections_cached(self, prog): sections = prog.sections().select_related('category', 'parent_class')
resources_for_user[resource['user_id']].append(resource['event__id'])
resources_for_user[resource['user_id']].append(resource['event_id'])
def ajax_teachers_cached(self, prog): teachers = ESPUser.objects.filter(userbit__verb=GetNode('V/Flags/Registration/Teacher')).filter(userbit__qsc__classsubject__isnull=False, userbit__qsc__parent__parent__program=prog).distinct()
priority_default = models.IntegerField(blank=True, default=-1)
priority_default = models.IntegerField(default=-1)
def increment_global_resource_rev(): import random val = random.randint(1,2**30) cache.set(GLOBAL_RESOURCE_CACHE_KEY, val, timeout=86400) return val
to_field_name=None, required=True, label='', initial=None,
to_field_name=None, required=True, label='', localize=False, initial=None,
def __init__(self, field_name='', field=None, key_type=None, to_field=None, to_field_name=None, required=True, label='', initial=None, widget=None, help_text='', ajax_func=None, queryset=None, error_messages=None, show_hidden_initial=False, *args, **kwargs):
self.makeaclass_logic(request, tl, one, two, module, extra, prog, newclass = None)
return self.makeaclass_logic(request, tl, one, two, module, extra, prog, newclass = None)
def makeaclass(self, request, tl, one, two, module, extra, prog, newclass = None): self.makeaclass_logic(request, tl, one, two, module, extra, prog, newclass = None)
resp = HttpResponse()
resp = HttpResponse(mimetype='application/json')
def catalog_json(self, request, tl, one, two, module, extra, prog, timeslot=None): """ Return the program class catalog """ # using .extra() to select all the category text simultaneously classes = ClassSubject.objects.catalog(self.program)
del sec._count_students
if hasattr(sec, '_count_students'): del sec._count_students
def catalog(self, program, ts=None, force_all=False, initial_queryset=None, use_cache=True, cache_only=False): # Try getting the catalog straight from cache catalog = self.catalog_cached(program, ts, force_all, initial_queryset, cache_only=True) if catalog is None: # Get it from the DB, then try prefetching class sizes catalog = self.catalog_cached(program, ts, force_all, initial_queryset, use_cache=use_cache, cache_only=cache_only) else: for cls in catalog: for sec in cls.get_sections(): del sec._count_students
self.initial = {prefix+'status': cls.status,
if type(cls.class_size_max) == int: csm = cls.class_size_max else: csm = 0 self.initial = { prefix+'status': cls.status,
def load_data(self, cls, prefix=''): self.initial = {prefix+'status': cls.status, prefix+'reg_status': None, prefix+'min_grade': cls.grade_min, prefix+'max_grade': cls.grade_max, prefix+'notes': cls.directors_notes, prefix+'class_size': cls.class_size_max, prefix+'clsid': cls.id, prefix+'progress': [cm.id for cm in cls.checklist_progress.all()]} return self.initial
prefix+'class_size': cls.class_size_max,
prefix+'class_size': csm ,
def load_data(self, cls, prefix=''): self.initial = {prefix+'status': cls.status, prefix+'reg_status': None, prefix+'min_grade': cls.grade_min, prefix+'max_grade': cls.grade_max, prefix+'notes': cls.directors_notes, prefix+'class_size': cls.class_size_max, prefix+'clsid': cls.id, prefix+'progress': [cm.id for cm in cls.checklist_progress.all()]} return self.initial
if type(ans) == None:
if ans == None:
def _get_capacity(self, ignore_changes=False): ans = None if self.max_class_capacity is not None: ans = self.max_class_capacity else: rooms = self.initial_rooms() if len(rooms) == 0: if not ans: ans = self.parent_class.class_size_max else: ans = min(self.parent_class.class_size_max, self._get_room_capacity(rooms))
return needs_teacher(self.profile)(self, request)
return needs_teacher(self.profile)(self, request, tl, one, two, module, extra, prog)
def profile(self, request, tl, one, two, module, extra, prog): """ Display the registration profile page, the page that contains the contact information for a student, as attached to a particular program """
return needs_student(self.profile)(self, request)
return needs_student(self.profile)(self, request, tl, one, two, module, extra, prog)
def profile(self, request, tl, one, two, module, extra, prog): """ Display the registration profile page, the page that contains the contact information for a student, as attached to a particular program """
map(response.delete_cookie, [x for x in ('cur_username','cur_email',
cookies_to_delete = [x for x in ('cur_username','cur_email',
def process_response(self, request, response): from esp.users.models import ESPUser modified_cookies = False
'cur_admin') if request.COOKIES.get(x, False)]) modified_cookies = True
'cur_admin') if request.COOKIES.get(x, False)] map(response.delete_cookie, cookies_to_delete) modified_cookies = (len(cookies_to_delete) > 0)
def process_response(self, request, response): from esp.users.models import ESPUser modified_cookies = False
anchor_choices = DataTree.objects.filter(Q(child_set__program__isnull=False) | Q(parent=GetNode("Q/Programs"))).exclude(parent__name="Subprograms").distinct()
def make_id_tuple(object_list): return tuple([(o.id, str(o)) for o in object_list])
anchor = forms.ModelChoiceField(anchor_choices, label = "Program Type")
anchor = forms.ModelChoiceField([], label = "Program Type")
def make_id_tuple(object_list): return tuple([(o.id, str(o)) for o in object_list])
unavailable_teachers = User.objects.filter(teacher_dict['class_approved'] | teacher_dict['class_proposed']).exclude(teacher_dict['availability']).distinct()
unavailable_teachers = User.objects.filter((teacher_dict['class_approved'] | teacher_dict['class_proposed']) & ~teacher_dict['availability']).distinct()
def force_availability(self, request, tl, one, two, module, extra, prog): teacher_dict = prog.teachers(QObjects=True) if request.method == 'POST': if request.POST.has_key('sure') and request.POST['sure'] == 'True': # Find all teachers who have not indicated their availability and do it for them. unavailable_teachers = User.objects.filter(teacher_dict['class_approved'] | teacher_dict['class_proposed']).exclude(teacher_dict['availability']).distinct() for t in unavailable_teachers: teacher = ESPUser(t) for ts in prog.getTimeSlots(): teacher.addAvailableTime(self.program, ts) return self.scheduling(request, tl, one, two, module, 'refresh', prog) else: return self.scheduling(request, tl, one, two, module, '', prog) # Normally, though, return a page explaining the issue. context = {'prog': self.program} context['good_teacher_num'] = User.objects.filter(teacher_dict['class_approved']).filter(teacher_dict['availability']).distinct().count() context['total_teacher_num'] = User.objects.filter(teacher_dict['class_approved']).distinct().count()
programs_to_archive = programs_to_archive.exclude(classsubject__id__in=ArchiveClass.objects.all().values_list('id', flat=True))
programs_to_archive = programs_to_archive.exclude(classsubject__id__in=ArchiveClass.objects.all().values_list('original_id', flat=True))
def execute(self): programs_to_archive = Program.objects.all()
return render_to_response(self.baseDir()+'reg_info.html', request, (prog, tl), {'form':form})
return render_to_response(self.baseDir()+'reg_info.html', request, (prog, tl), {'form':form, 'current_year':ESPUser.current_schoolyear()})
def onsite_create(self, request, tl, one, two, module, extra, prog):
self._execute(cmd, args)
return self._execute(cmd, args) if not cmd.startswith('SELECT'): connection_cache_lock.release() return self._execute(cmd, args)
def executeps(self, cmd, args=None): ''' execute a command using a prepared statement. ''' # If we can't get a lock, give up and just execute the query. # No point deadlocking over this. if not connection_cache_lock.acquire(0): self._execute(cmd, args) prepStmt = self.prepCache.get(cmd) if prepStmt is None: cmdId = "ps_%d" % (len(self.prepCache) + 1) # unique name for new prepared statement prepStmt = self.prepCache[cmd] = \ self.prepareStatement(cmd, cmdId) if DEBUG_PRINT: print '%d Prepared statement %s for %s...' % (self.conn_id, cmdId, cmd[:30]) connection_cache_lock.release() if DEBUG_PRINT: print '%d Using prepared statement %s...' % (self.conn_id, prepStmt[:30]) self._execute(prepStmt, args)
self._execute(prepStmt, args)
return self._execute(prepStmt, args)
def executeps(self, cmd, args=None): ''' execute a command using a prepared statement. ''' # If we can't get a lock, give up and just execute the query. # No point deadlocking over this. if not connection_cache_lock.acquire(0): self._execute(cmd, args) prepStmt = self.prepCache.get(cmd) if prepStmt is None: cmdId = "ps_%d" % (len(self.prepCache) + 1) # unique name for new prepared statement prepStmt = self.prepCache[cmd] = \ self.prepareStatement(cmd, cmdId) if DEBUG_PRINT: print '%d Prepared statement %s for %s...' % (self.conn_id, cmdId, cmd[:30]) connection_cache_lock.release() if DEBUG_PRINT: print '%d Using prepared statement %s...' % (self.conn_id, prepStmt[:30]) self._execute(prepStmt, args)
self.fields['times_available'].initial = [mt.short_description for mt in room.matching_times()] self.fields['furnishings'].initial = [f.res_type.name for f in room.associated_resources()]
self.fields['times_available'].initial = [mt.id for mt in room.matching_times()] self.fields['furnishings'].initial = [f.res_type.id for f in room.associated_resources()]
def load_classroom(self, program, room): self.fields['id'].initial = room.id self.fields['room_number'].initial = room.name self.fields['num_students'].initial = room.num_students self.fields['times_available'].initial = [mt.short_description for mt in room.matching_times()] self.fields['furnishings'].initial = [f.res_type.name for f in room.associated_resources()]
initial_rooms = Resource.objects.filter(name=self.cleaned_data['room_number'], event__anchor=program.anchor) initial_furnishings = [r.associated_resources() for r in initial_rooms] new_timeslots = [Event.objects.get(id=int(id_str)) for id_str in self.cleaned_data['times_available']] new_furnishings = [ResourceType.objects.get(id=int(id_str)) for id_str in self.cleaned_data['furnishings']] initial_rooms = list(initial_rooms) for fl in initial_furnishings: fl = list(fl)
orig_room_number = self.cleaned_data['orig_room_number'] if orig_room_number == "": orig_room_number = self.cleaned_data['room_number'] initial_rooms = program.getClassrooms().filter(name=orig_room_number).distinct() initial_furnishings = {} for r in initial_rooms: initial_furnishings[r] = list(r.associated_resources()) timeslots = Event.objects.filter(id__in=[int(id_str) for id_str in self.cleaned_data['times_available']]) furnishings = ResourceType.objects.filter(id__in=[int(id_str) for id_str in self.cleaned_data['furnishings']]) rooms_to_keep = list(initial_rooms.filter(event__in=timeslots)) rooms_to_delete = list(initial_rooms.exclude(event__in=timeslots)) new_timeslots = timeslots.exclude(id__in=[x.event_id for x in rooms_to_keep])
def save_classroom(self, program): """ Steps for saving a classroom: - Find the previous list of resources - Create a new list of resources - Move over resource assignments - Delete old resources """
for f in new_furnishings:
for f in furnishings:
def save_classroom(self, program): """ Steps for saving a classroom: - Find the previous list of resources - Create a new list of resources - Move over resource assignments - Delete old resources """
for i in range(0, len(initial_rooms)):
for rm in rooms_to_delete:
def save_classroom(self, program): """ Steps for saving a classroom: - Find the previous list of resources - Create a new list of resources - Move over resource assignments - Delete old resources """
ra_room = initial_rooms[i].assignments()
ra_room = rm.assignments()
def save_classroom(self, program): """ Steps for saving a classroom: - Find the previous list of resources - Create a new list of resources - Move over resource assignments - Delete old resources """
ra.resource = new_timeslots[new_timeslots.index(ra.resource.event)].new_room
ra.resource = timeslots[new_timeslots.index(ra.resource.event)].new_room
def save_classroom(self, program): """ Steps for saving a classroom: - Find the previous list of resources - Create a new list of resources - Move over resource assignments - Delete old resources """
for f in initial_furnishings[i]:
for f in initial_furnishings[rm]:
def save_classroom(self, program): """ Steps for saving a classroom: - Find the previous list of resources - Create a new list of resources - Move over resource assignments - Delete old resources """
initial_rooms[i].delete()
rm.delete() for room in rooms_to_keep: room.num_students = self.cleaned_data['num_students'] room.name = self.cleaned_data['room_number'] room.save() for f in furnishings.exclude(resource__group_id=room.group_id): new_resource = Resource() new_resource.event = room.event new_resource.res_type = f new_resource.name = f.name + ' for ' + self.cleaned_data['room_number'] new_resource.group_id = room.group_id new_resource.save() f.new_resource = new_resource for f in Resource.objects.filter(group_id=room.group_id).exclude(id=room.id).exclude(res_type__in=furnishings): f.delete()
def save_classroom(self, program): """ Steps for saving a classroom: - Find the previous list of resources - Create a new list of resources - Move over resource assignments - Delete old resources """
msg = u'Please enter your affiliation if you are not from MIT.'
msg = u'Please enter your affiliation if you are not from %s.' % INSTITUTION_NAME
def clean(self): super(TeacherInfoForm, self).clean() cleaned_data = self.cleaned_data
result[key] = self.registrations.filter(studentregistration__relationship=rmap[key], studentregistration__start_date__lte=now, studentregistration__end_date__gte=now).distinct()
result[key] = list(self.registrations.filter(studentregistration__relationship=rmap[key], studentregistration__start_date__lte=now, studentregistration__end_date__gte=now).distinct()) if len(result[key]) == 0: del result[key]
def students_dict(self): from esp.program.models import RegistrationType now = datetime.datetime.now() rmap = RegistrationType.get_map() result = {} for key in rmap: result[key] = self.registrations.filter(studentregistration__relationship=rmap[key], studentregistration__start_date__lte=now, studentregistration__end_date__gte=now).distinct() return result
students_dict.depend_on_row(lambda: StudentRegistration, lambda reg: {'self': reg.section})
def students_dict(self): from esp.program.models import RegistrationType now = datetime.datetime.now() rmap = RegistrationType.get_map() result = {} for key in rmap: result[key] = self.registrations.filter(studentregistration__relationship=rmap[key], studentregistration__start_date__lte=now, studentregistration__end_date__gte=now).distinct() return result
num_students_prereg.depend_on_row(lambda: StudentRegistration, lambda reg: {'self': reg.section}) @cache_function
def num_students_prereg(self): return self.students_prereg().count()
StudentRegistration.objects.filter(section=self, end_date__gte=now).update(end_date=now)
qs = StudentRegistration.objects.filter(section=self, end_date__gte=now) qs.update(end_date=now) for reg in qs: signals.post_save.send(sender=StudentRegistration, instance=reg)
def clearStudents(self): from esp.program.models import StudentRegistration now = datetime.datetime.now() StudentRegistration.objects.filter(section=self, end_date__gte=now).update(end_date=now)
ans = self.max_class_capacity
return self.max_class_capacity
def _get_capacity(self, ignore_changes=False): if self.max_class_capacity is not None: ans = self.max_class_capacity
"main_call": "classList"
"main_call": "classList",
def module_properties(cls): return [ { "admin_title": "Show All Classes at Onsite Registration", "link_title": "List of All Classes", "module_type": "onsite", "seq": 31 }, { "admin_title": "Show Open Classes at Onsite Registration", "link_title": "List of Open Classes", "module_type": "onsite", "seq": 32, "main_call": "classList" "aux_calls": "status", } ]
shours += math.ceil(section.duration)*section.parent_class.class_size_max
if section.parent_class.class_size_max !=0: shours += math.ceil(section.duration)*section.parent_class.class_size_max else: shours = 0
def __init__(self, newclslist): self.clslist = newclslist
ClassSection._get_capacity.delete([sec])
sec.parent_program._moduleExtension = {}
def runTest(self): # Parameters initial_capacity = 37 mult_test = 0.6 offset_test = 4 # Get class capacity self.program.getModules() options = self.program.getModuleExtension('StudentClassRegModuleInfo') sec = random.choice(list(self.program.sections())) sec.parent_class.class_size_max = initial_capacity sec.parent_class.save() sec.max_class_capacity = initial_capacity sec.save() # Check that initially the capacity is correct self.assertEqual(sec.capacity, initial_capacity) # Check that multiplier works options.class_cap_multiplier = str(mult_test) options.save() ClassSection._get_capacity.delete([sec]) self.assertEqual(sec.capacity, int(initial_capacity * mult_test)) # Check that multiplier and offset work options.class_cap_offset = offset_test options.save() ClassSection._get_capacity.delete([sec]) self.assertEqual(sec.capacity, int(initial_capacity * mult_test + offset_test)) # Check that offset only works options.class_cap_multiplier = '1.0' options.save() ClassSection._get_capacity.delete([sec]) self.assertEqual(sec.capacity, int(initial_capacity + offset_test)) # Check that we can go back to normal options.class_cap_offset = 0 options.save() ClassSection._get_capacity.delete([sec]) self.assertEqual(sec.capacity, initial_capacity)
ClassSection._get_capacity.delete([sec]) self.assertEqual(sec.capacity, int(initial_capacity * mult_test + offset_test))
sec.parent_program._moduleExtension = {} self.assertEqual(sec._get_capacity(), int(initial_capacity * mult_test + offset_test))
def runTest(self): # Parameters initial_capacity = 37 mult_test = 0.6 offset_test = 4 # Get class capacity self.program.getModules() options = self.program.getModuleExtension('StudentClassRegModuleInfo') sec = random.choice(list(self.program.sections())) sec.parent_class.class_size_max = initial_capacity sec.parent_class.save() sec.max_class_capacity = initial_capacity sec.save() # Check that initially the capacity is correct self.assertEqual(sec.capacity, initial_capacity) # Check that multiplier works options.class_cap_multiplier = str(mult_test) options.save() ClassSection._get_capacity.delete([sec]) self.assertEqual(sec.capacity, int(initial_capacity * mult_test)) # Check that multiplier and offset work options.class_cap_offset = offset_test options.save() ClassSection._get_capacity.delete([sec]) self.assertEqual(sec.capacity, int(initial_capacity * mult_test + offset_test)) # Check that offset only works options.class_cap_multiplier = '1.0' options.save() ClassSection._get_capacity.delete([sec]) self.assertEqual(sec.capacity, int(initial_capacity + offset_test)) # Check that we can go back to normal options.class_cap_offset = 0 options.save() ClassSection._get_capacity.delete([sec]) self.assertEqual(sec.capacity, initial_capacity)
if ( len(Document.get_completed(self.user, self.program_anchor_cached)) > 0 ):
if ( len(Document.get_completed(self.user, self.program_anchor_cached())) > 0 ):
def isCompleted(self): """ Whether the user has paid for this program or its parent program. """ if ( len(Document.get_completed(self.user, self.program_anchor_cached)) > 0 ): return True else: parent_program = self.program.getParentProgram() if parent_program is not None: return ( len(Document.get_completed(self.user, parent_program.anchor)) > 0 )