index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
41,676
lemonad/molnet-polls
refs/heads/master
/forms.py
# -*- coding: utf-8 -*- from django.forms import (BooleanField, CharField, ChoiceField, Form, ModelForm, MultiValueField, MultiWidget, RadioSelect, Textarea, TextInput, ValidationError) from django.utils.encoding import force_unicode from django.utils.translation import ugettext_lazy as _ from models import Choice, Poll, Vote class ModelFormRequestUser(ModelForm): def __init__(self, request, *args, **varargs): self.user = request.user super(ModelFormRequestUser, self).__init__(*args, **varargs) def save(self, commit=True): obj = super(ModelFormRequestUser, self).save(commit=False) obj.user = self.user if commit: obj.save() self.save_m2m() # Be careful with ModelForms + commit=False return obj class ChoiceWithOtherRenderer(RadioSelect.renderer): """ RadioFieldRenderer that renders its last choice with a placeholder. See http://djangosnippets.org/snippets/863/ (and perhaps also http://djangosnippets.org/snippets/1377/) """ def __init__(self, *args, **kwargs): super(ChoiceWithOtherRenderer, self).__init__(*args, **kwargs) self.choices, self.other = self.choices[:-1], self.choices[-1] def __iter__(self): for input in super(ChoiceWithOtherRenderer, self).__iter__(): yield input id = '%s_%s' % (self.attrs['id'], self.other[0]) if 'id' in self.attrs else '' label_for = ' for="%s"' % id if id else '' checked = '' if not force_unicode(self.other[0]) == self.value else 'checked="true" ' yield '<label%s><input type="radio" id="%s" value="%s" name="%s" %s/> %s</label> %%s' % ( label_for, id, self.other[0], self.name, checked, self.other[1]) class ChoiceWithOtherWidget(MultiWidget): """ MultiWidget for use with ChoiceWithOtherField. See http://djangosnippets.org/snippets/863/ (and perhaps also http://djangosnippets.org/snippets/1377/) """ def __init__(self, choices, other_widget): widgets = [RadioSelect(choices=choices, renderer=ChoiceWithOtherRenderer), other_widget] super(ChoiceWithOtherWidget, self).__init__(widgets) def decompress(self, value): if not value: return [None, None] return value def format_output(self, rendered_widgets): """ Format the output by substituting the "other" choice into the first widget. """ return rendered_widgets[0] % rendered_widgets[1] class ChoiceWithOtherField(MultiValueField): """ ChoiceField with an option for a user-submitted "other" value. The last item in the choices array passed to __init__ is expected to be a choice for "other". This field's cleaned data is a tuple consisting of the choice the user made, and the "other" field typed in if the choice made was the last one. >>> class AgeForm(forms.Form): ... age = ChoiceWithOtherField(choices=[ ... (0, '15-29'), ... (1, '30-44'), ... (2, '45-60'), ... (3, 'Other, please specify:') ... ]) ... >>> # rendered as a RadioSelect choice field whose last choice has a text input ... print AgeForm()['age'] <ul> <li><label for="id_age_0_0"><input type="radio" id="id_age_0_0" value="0" name="age_0" /> 15-29</label></li> <li><label for="id_age_0_1"><input type="radio" id="id_age_0_1" value="1" name="age_0" /> 30-44</label></li> <li><label for="id_age_0_2"><input type="radio" id="id_age_0_2" value="2" name="age_0" /> 45-60</label></li> <li><label for="id_age_0_3"><input type="radio" id="id_age_0_3" value="3" name="age_0" /> Other, please \ specify:</label> <input type="text" name="age_1" id="id_age_1" /></li> </ul> >>> form = AgeForm({'age_0': 2}) >>> form.is_valid() True >>> form.cleaned_data {'age': (u'2', u'')} >>> form = AgeForm({'age_0': 3, 'age_1': 'I am 10 years old'}) >>> form.is_valid() True >>> form.cleaned_data {'age': (u'3', u'I am 10 years old')} >>> form = AgeForm({'age_0': 1, 'age_1': 'This is bogus text which is ignored since I didn\\'t pick "other"'}) >>> form.is_valid() True >>> form.cleaned_data {'age': (u'1', u'')} See http://djangosnippets.org/snippets/863/ (and perhaps also http://djangosnippets.org/snippets/1377/) """ def __init__(self, *args, **kwargs): other_field = kwargs.pop('other_field', None) if other_field is None: other_field = CharField(required=False) fields = [ChoiceField(widget=RadioSelect(renderer= ChoiceWithOtherRenderer), *args, **kwargs), other_field] widget = ChoiceWithOtherWidget(choices=kwargs['choices'], other_widget=other_field.widget) kwargs.pop('choices') self._was_required = kwargs.pop('required', True) kwargs['required'] = False super(ChoiceWithOtherField, self).__init__(widget=widget, fields=fields, *args, **kwargs) def clean(self, value): # MultiValueField turns off the "required" field for all the fields. # It prevents us from requiring the manual entry. This implements # that. if self._was_required: #if value and value[1] and value[0] != self.fields[0].choices[-1][0]: # value[0] = self.fields[0].choices[-1][0] if value and value[0] == self.fields[0].choices[-1][0]: manual_choice = value[1] if not manual_choice: raise ValidationError(self.error_messages['required']) return super(ChoiceWithOtherField, self).clean(value) def compress(self, value): if self._was_required and not value or value[0] in (None, ''): raise ValidationError(self.error_messages['required']) if not value: return [None, u''] return (value[0], value[1] if force_unicode(value[0]) == \ force_unicode(self.fields[0].choices[-1][0]) else u'') class PollVotingForm(Form): """ Form for voting on polls. """ def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') allow_new_choices = kwargs.pop('allow_new_choices') super(PollVotingForm, self).__init__(*args, **kwargs) if allow_new_choices: choices.append(('OTHER', 'Other')) self.fields['choices'] = \ ChoiceWithOtherField(choices=choices, required=True) else: self.fields['choices'] = \ ChoiceField(choices=choices, widget=RadioSelect, required=True) class PollForm(ModelFormRequestUser): """ Form for adding and editing polls. """ class Meta: model = Poll fields = ['title', 'description', 'allow_new_choices'] # Django 1.2 only # widgets = {'title': TextInput(attrs={'class': 'span-12 last input'}), # 'description': Textarea(attrs={'class': 'span-12 last input'}),} def __init__(self, *args, **kwargs): super(PollForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs['class'] = 'span-12 last input' self.fields['description'].widget.attrs['class'] = 'span-12 last input' self.fields['description'].widget.attrs['id'] = 'wmd-input' class ChoiceForm(ModelFormRequestUser): """ Form for adding and editing poll choices. """ def __init__(self, request, poll, *args, **varargs): self.poll = poll super(ChoiceForm, self).__init__(request, *args, **varargs) self.fields['choice'].widget.attrs['class'] = 'span-12 last input' def save(self, commit=True): obj = super(ChoiceForm, self).save(commit=False) obj.poll = self.poll if commit: obj.save() self.save_m2m() # Be careful with ModelForms + commit=False return obj class Meta: model = Choice fields = ['choice'] # Django 1.2 only # widgets = {'choice': TextInput(attrs={'class': 'span-12 input', # 'size': '255'}),}
{"/tests.py": ["/models.py"], "/urls.py": ["/feeds.py"], "/forms.py": ["/models.py"], "/admin.py": ["/models.py"], "/feeds.py": ["/models.py"], "/views.py": ["/forms.py", "/models.py"]}
41,677
lemonad/molnet-polls
refs/heads/master
/migrations/0001_initial.py
# -*- coding: utf-8 -*- from south.db import db from django.db import models from molnet.polls.models import * class Migration: def forwards(self, orm): # Adding model 'Poll' db.create_table('polls_poll', ( ('id', orm['polls.Poll:id']), ('slug', orm['polls.Poll:slug']), ('user', orm['polls.Poll:user']), ('title', orm['polls.Poll:title']), ('description', orm['polls.Poll:description']), ('allow_new_choices', orm['polls.Poll:allow_new_choices']), ('status', orm['polls.Poll:status']), ('published_at', orm['polls.Poll:published_at']), ('date_created', orm['polls.Poll:date_created']), ('date_modified', orm['polls.Poll:date_modified']), )) db.send_create_signal('polls', ['Poll']) # Adding model 'Vote' db.create_table('polls_vote', ( ('id', orm['polls.Vote:id']), ('user', orm['polls.Vote:user']), ('choice', orm['polls.Vote:choice']), ('date_created', orm['polls.Vote:date_created']), ('date_modified', orm['polls.Vote:date_modified']), )) db.send_create_signal('polls', ['Vote']) # Adding model 'Choice' db.create_table('polls_choice', ( ('id', orm['polls.Choice:id']), ('poll', orm['polls.Choice:poll']), ('choice', orm['polls.Choice:choice']), ('user', orm['polls.Choice:user']), ('date_created', orm['polls.Choice:date_created']), )) db.send_create_signal('polls', ['Choice']) # Creating unique_together for [poll, choice] on Choice. db.create_unique('polls_choice', ['poll_id', 'choice']) def backwards(self, orm): # Deleting unique_together for [poll, choice] on Choice. db.delete_unique('polls_choice', ['poll_id', 'choice']) # Deleting model 'Poll' db.delete_table('polls_poll') # Deleting model 'Vote' db.delete_table('polls_vote') # Deleting model 'Choice' db.delete_table('polls_choice') models = { 'auth.group': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '80', 'unique': 'True'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)"}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'max_length': '30', 'unique': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'polls.choice': { 'Meta': {'unique_together': "(('poll', 'choice'),)"}, 'choice': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'poll': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['polls.Poll']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'polls.poll': { 'allow_new_choices': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}), 'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'published_at': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), 'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '80', 'blank': 'True', 'unique': 'True', 'populate_from': 'None', 'db_index': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'DRAFT'", 'max_length': '32', 'db_index': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '140', 'unique': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'polls.vote': { 'choice': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['polls.Choice']"}), 'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}), 'date_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) } } complete_apps = ['polls']
{"/tests.py": ["/models.py"], "/urls.py": ["/feeds.py"], "/forms.py": ["/models.py"], "/admin.py": ["/models.py"], "/feeds.py": ["/models.py"], "/views.py": ["/forms.py", "/models.py"]}
41,678
lemonad/molnet-polls
refs/heads/master
/models.py
# -*- coding: utf-8 -*- import re from autoslug import AutoSlugField from django.contrib.auth.models import User from django.db import connection from django.db.models import (BooleanField, CharField, Count, DateField, DateTimeField, ForeignKey, Manager, Model, permalink, Q, TextField, TimeField) from django.utils.translation import ugettext_lazy as _ class PollManager(Manager): def recent(self): return self.exclude(status='DRAFT') \ .order_by('-published_at') def created_by_user(self, userid): return self.filter(user=userid) \ .order_by('-published_at') def answered_by_user(self, userid): return self.filter(choice__vote__user=userid) \ .exclude(status='DRAFT') \ .order_by('-choice__vote__date_modified') class Poll(Model): """ A poll is basically a question with multiple pre-defined choices that users can pick amongst. Users vote by selecting one choice, or optionally, create a new choice _and_ vote on it). By answering a poll, a user increases the poll's popularity. Polls are created by a specific user, which becomes the poll's administrator. Polls are either in draft mode or published. Polls have a title and an optional description (markdown). """ STATUS_CHOICES = (('DRAFT', _("Draft")), ('PUBLISHED', _("Published")), ('CLOSED', _("Closed"))) slug = AutoSlugField(_("Slug"), populate_from='title', editable=False, unique=True, blank=True, max_length=80) user = ForeignKey(User, verbose_name=_('created by'), db_index=True) title = CharField(_('title'), max_length=140, unique=True) description = TextField(_('description'), blank=True) allow_new_choices = BooleanField(_('allow users to add choices?'), default=False) status = CharField(_("Status"), db_index=True, max_length=32, choices=STATUS_CHOICES, default='DRAFT') published_at = DateTimeField(_('date and time published'), null=True, blank=True, db_index=True) date_created = DateTimeField(_('created (date)'), db_index=True, auto_now_add=True) date_modified = DateTimeField(_('modified (date)'), db_index=True, auto_now=True) objects = PollManager() def __unicode__(self): return self.title def number_of_votes(self): q = self.choice_set.aggregate(num_votes=Count('vote')) return q['num_votes'] def is_draft(self): return (self.status == 'DRAFT') def is_published(self): return (self.status != 'DRAFT') def is_closed(self): return (self.status == 'CLOSED') class Meta: ordering = ['-published_at'] verbose_name = _('poll') verbose_name_plural = _('polls') class ChoiceManager(Manager): def get_choices_and_votes_for_poll(self, pollid): return self.filter(poll=pollid) \ .annotate(num_votes=Count('vote')) class Choice(Model): """ A poll consists of multiple choices which users can "vote" on. """ poll = ForeignKey(Poll, verbose_name=_('poll'), db_index=True) choice = CharField(_('choice'), max_length=255) user = ForeignKey(User, verbose_name=_('added by'), db_index=True) date_created = DateTimeField(_('created (date)'), db_index=True, auto_now_add=True) objects = ChoiceManager() def __unicode__(self): return self.choice class Meta: unique_together = (('poll', 'choice'),) ordering = ['date_created'] verbose_name = _('choice') verbose_name_plural = _('choices') class VoteManager(Manager): def votes_for_poll(self, pollid): return self.filter(choice__poll=pollid) class Vote(Model): """ A vote on a poll choice by a user. """ user = ForeignKey(User, verbose_name=_('user'), db_index=True) choice = ForeignKey(Choice, verbose_name=_('choice'), db_index=True) date_created = DateTimeField(_('created (date)'), db_index=True, auto_now_add=True) date_modified = DateTimeField(_('modified (date)'), db_index=True, auto_now=True) objects = VoteManager() class Meta: ordering = ['-date_created'] verbose_name = _('vote') verbose_name_plural = _('votes')
{"/tests.py": ["/models.py"], "/urls.py": ["/feeds.py"], "/forms.py": ["/models.py"], "/admin.py": ["/models.py"], "/feeds.py": ["/models.py"], "/views.py": ["/forms.py", "/models.py"]}
41,679
lemonad/molnet-polls
refs/heads/master
/admin.py
# -*- coding: utf-8 -*- from django import forms from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from models import (Choice, Poll, Vote) class ChoiceAdmin(admin.ModelAdmin): fields = ['poll', 'choice', 'user'] list_display = ['poll', 'choice', 'user', 'date_created'] search_fields = ['choice'] admin.site.register(Choice, ChoiceAdmin) class PollAdmin(admin.ModelAdmin): fields = ['title', 'description', 'user', 'allow_new_choices', 'status', 'published_at'] list_display = ['title', 'user', 'allow_new_choices', 'status', 'published_at', 'date_created', 'date_modified'] list_filter = ['status', 'allow_new_choices'] search_fields = ['title', 'description'] admin.site.register(Poll, PollAdmin) class VoteAdmin(admin.ModelAdmin): fields = ['user', 'choice'] list_display = ['user', 'choice', 'date_created'] admin.site.register(Vote, VoteAdmin)
{"/tests.py": ["/models.py"], "/urls.py": ["/feeds.py"], "/forms.py": ["/models.py"], "/admin.py": ["/models.py"], "/feeds.py": ["/models.py"], "/views.py": ["/forms.py", "/models.py"]}
41,680
lemonad/molnet-polls
refs/heads/master
/feeds.py
# -*- coding: utf-8 -*- from django.contrib.auth.models import User from django.contrib.syndication.feeds import Feed from django.core.cache import cache from django.core.urlresolvers import reverse from django.db.models import Count, Q from django.utils.translation import ugettext_lazy as _ from models import Choice, Poll, Vote class LatestPolls(Feed): title = _("Latest polls") description = _("The latest polls submitted by your co-workers") def items(self): return Poll.objects.recent() def item_link(self, item): return reverse('molnet-polls-show-poll', kwargs={'year': item.published_at.year, 'month': item.published_at.month, 'day': item.published_at.day, 'slug': item.slug}) def link(self): """ Defined as a method as reverse will otherwise throw an improperlyConfigured exception because the url patterns have not yet been compiled when importing this class. """ return reverse("molnet-polls-startpage")
{"/tests.py": ["/models.py"], "/urls.py": ["/feeds.py"], "/forms.py": ["/models.py"], "/admin.py": ["/models.py"], "/feeds.py": ["/models.py"], "/views.py": ["/forms.py", "/models.py"]}
41,681
lemonad/molnet-polls
refs/heads/master
/views.py
# -*- coding: utf-8 -*- import datetime from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.cache import cache from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse from django.db.models import Count, Q from django.http import (HttpResponse, HttpResponseNotFound, Http404, HttpResponseRedirect, HttpResponseForbidden) from django.shortcuts import (get_object_or_404, get_list_or_404, render_to_response) from django.template import Context, RequestContext, loader from django.utils.translation import ugettext_lazy as _ from forms import ChoiceForm, PollForm, PollVotingForm from models import Choice, Poll, Vote def get_sidebar_polls(user): created_by_user = None answered_by_user = None if user.is_authenticated(): created_by_user = Poll.objects.created_by_user(user.id) answered_by_user = Poll.objects.answered_by_user(user.id) sidebar_polls = {'created_by_user': created_by_user, 'answered_by_user': answered_by_user, 'recent': Poll.objects.recent()} return sidebar_polls def get_form_choices(choices): form_choices = [] for choice in choices: form_choices.append((str(choice.id), choice.choice)) return form_choices def startpage(request): """ Start page. """ sidebar_polls = get_sidebar_polls(request.user) t = loader.get_template('polls-index.html') c = RequestContext(request, {'sidebar_polls': sidebar_polls, 'navigation': 'polls', 'navigation2': 'polls-all',}) return HttpResponse(t.render(c)) def show_poll(request, year, month, day, slug): form = None poll = get_object_or_404(Poll, slug=slug) choices = Choice.objects.get_choices_and_votes_for_poll(poll.id) show_results = False if 'show-results' in request.GET or poll.status == "CLOSED": show_results = True if not request.user.is_authenticated(): voted_for_choice_id = None else: # Only show form if authenticated try: vote = Vote.objects.get(Q(user=request.user.id)& Q(choice__poll=poll.id)) voted_for_choice_id = vote.choice.id show_results = True except Vote.DoesNotExist: voted_for_choice_id = None form_choices = get_form_choices(choices) if request.method == 'POST': form = PollVotingForm(request.POST, choices=form_choices, allow_new_choices=poll.allow_new_choices) if form.is_valid(): if poll.allow_new_choices: choice_id, choice_text = form.cleaned_data['choices'] else: choice_id = form.cleaned_data['choices'] if choice_id == 'OTHER': # Check for duplicates choice, created = Choice.objects \ .get_or_create(poll=poll, choice=choice_text, defaults={'user': request.user}) # Voted already? if voted_for_choice_id: # Yes, change vote vote.choice = choice vote.save() else: # No, add vote Vote.objects.create(user=request.user, choice=choice) else: # Check that the choice is valid for this poll choice = get_object_or_404(Choice, id=choice_id, poll=poll.id) # Voted already? if voted_for_choice_id: # Yes, change vote vote.choice = choice vote.save() else: # No, add vote Vote.objects.create(user=request.user, choice=choice) voted_for_choice_id = choice.id choices = Choice.objects.get_choices_and_votes_for_poll(poll.id) form_choices = get_form_choices(choices) if poll.allow_new_choices: poll_form_defaults = {'choices': (str(voted_for_choice_id), '')} else: poll_form_defaults = {'choices': str(voted_for_choice_id)} form = PollVotingForm(choices=form_choices, allow_new_choices=poll.allow_new_choices, initial=poll_form_defaults) else: # Form not submitted if voted_for_choice_id: if poll.allow_new_choices: poll_form_defaults = {'choices': (str(voted_for_choice_id), '')} else: poll_form_defaults = {'choices': str(voted_for_choice_id)} form = PollVotingForm(choices=form_choices, allow_new_choices=poll.allow_new_choices, initial=poll_form_defaults) else: form = PollVotingForm(choices=form_choices, allow_new_choices=poll.allow_new_choices) number_of_votes = Vote.objects.votes_for_poll(poll.id).count() related_polls = None sidebar_polls = get_sidebar_polls(request.user) t = loader.get_template('polls-show-poll.html') c = RequestContext(request, {'poll': poll, 'choices': choices, 'form': form, 'vote_id': voted_for_choice_id, 'number_of_votes': number_of_votes, 'related_polls': related_polls, 'sidebar_polls': sidebar_polls, 'show_results': show_results}) return HttpResponse(t.render(c)) @login_required def create_poll(request): if request.method == 'POST': form = PollForm(request, request.POST) if form.is_valid(): p = form.save() return HttpResponseRedirect(reverse('molnet-polls-edit-poll', kwargs={'slug': p.slug})) else: form = PollForm(request) sidebar_polls = get_sidebar_polls(request.user) t = loader.get_template('polls-create-poll.html') c = RequestContext(request, {'form': form, 'sidebar_polls': sidebar_polls, 'navigation': 'polls', 'navigation2': 'polls-create',}) return HttpResponse(t.render(c)) @login_required def edit_poll(request, slug): poll = get_object_or_404(Poll, slug=slug) if request.user != poll.user: raise PermissionDenied("You must own a poll in order to edit it.") choices = Choice.objects.get_choices_and_votes_for_poll(poll.id) poll_form = PollForm(request, instance=poll, prefix='poll') choice_form = ChoiceForm(request, poll, prefix='choice') if request.method == 'POST': if 'poll' in request.POST: poll_form = PollForm(request, request.POST, instance=poll, prefix='poll') if poll_form.is_valid(): p = poll_form.save() return HttpResponseRedirect(reverse('molnet-polls-edit-poll', kwargs={'slug': p.slug})) elif 'choice' in request.POST: choice_form = ChoiceForm(request, poll, request.POST, prefix='choice') if choice_form.is_valid(): choice, created = Choice.objects \ .get_or_create(poll=poll, choice=choice_form.cleaned_data['choice'], defaults={'user': request.user}) return HttpResponseRedirect(reverse('molnet-polls-edit-poll', kwargs={'slug': poll.slug})) elif 'delete-choice' in request.POST and 'choice-id' in request.POST: try: choice = Choice.objects.get(id=request.POST['choice-id'], poll=poll) \ .delete() return HttpResponseRedirect(reverse('molnet-polls-edit-poll', kwargs={'slug': poll.slug})) except Choice.DoesNotExist: raise Http404 elif 'delete' in request.POST: poll.delete() return HttpResponseRedirect(reverse('molnet-polls-startpage')) elif 'close' in request.POST: poll.status="CLOSED" poll.save() return HttpResponseRedirect(reverse('molnet-polls-edit-poll', kwargs={'slug': poll.slug})) elif 're-open' in request.POST: poll.status="PUBLISHED" poll.save() return HttpResponseRedirect(reverse('molnet-polls-edit-poll', kwargs={'slug': poll.slug})) elif 'unpublish' in request.POST: poll.status="DRAFT" poll.save() return HttpResponseRedirect(reverse('molnet-polls-edit-poll', kwargs={'slug': poll.slug})) elif 'publish' in request.POST: poll.status="PUBLISHED" poll.published_at = datetime.datetime.now() poll.save() return HttpResponseRedirect(reverse('molnet-polls-edit-poll', kwargs={'slug': poll.slug})) else: raise Http404 related_polls = None sidebar_polls = get_sidebar_polls(request.user) t = loader.get_template('polls-edit-poll.html') c = RequestContext(request, {'poll': poll, 'choices': choices, 'choice_form': choice_form, 'poll_form': poll_form, 'related_polls': related_polls, 'sidebar_polls': sidebar_polls}) return HttpResponse(t.render(c))
{"/tests.py": ["/models.py"], "/urls.py": ["/feeds.py"], "/forms.py": ["/models.py"], "/admin.py": ["/models.py"], "/feeds.py": ["/models.py"], "/views.py": ["/forms.py", "/models.py"]}
41,682
jeff00seattle/pyfortified-datetime
refs/heads/master
/pyfortified_datetime/dates_range.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # def dates_range(date1, date2): import datetime as dt for n in range(int ((date2 - date1).days)+1): yield date1 + dt.timedelta(n)
{"/examples/example_dates_range_date.py": ["/pyfortified_datetime/__init__.py"], "/pyfortified_datetime/__init__.py": ["/pyfortified_datetime/dates_range.py", "/pyfortified_datetime/dates_month_first_last.py", "/pyfortified_datetime/dates_months.py"], "/examples/example_dates_month_first_last.py": ["/pyfortified_datetime/__init__.py"], "/examples/example_dates_months_generator.py": ["/pyfortified_datetime/__init__.py"]}
41,683
jeff00seattle/pyfortified-datetime
refs/heads/master
/examples/example_dates_range_date.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # from pprintpp import pprint import datetime as dt import pyfortified_datetime start_dt = dt.date(2015, 12, 20) end_dt = dt.date(2016, 1, 11) print(type(pyfortified_datetime.dates_range(start_dt, end_dt))) for dt in pyfortified_datetime.dates_range(start_dt, end_dt): pprint(dt)
{"/examples/example_dates_range_date.py": ["/pyfortified_datetime/__init__.py"], "/pyfortified_datetime/__init__.py": ["/pyfortified_datetime/dates_range.py", "/pyfortified_datetime/dates_month_first_last.py", "/pyfortified_datetime/dates_months.py"], "/examples/example_dates_month_first_last.py": ["/pyfortified_datetime/__init__.py"], "/examples/example_dates_months_generator.py": ["/pyfortified_datetime/__init__.py"]}
41,684
jeff00seattle/pyfortified-datetime
refs/heads/master
/pyfortified_datetime/dates_month_first_last.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # import datetime as dt # requires python-dateutil (http://labix.org/python-dateutil) from dateutil.relativedelta import relativedelta def dates_month_first_last(month_date, date_format="%Y-%m-%d"): if not (isinstance(month_date, str) or isinstance(month_date, dt.datetime) or isinstance(month_date, dt.date)): raise TypeError("Invalid date type: {0}".format(type(month_date))) _month_date = None if isinstance(month_date, str): _month_date = dt.datetime.strptime(date_string=month_date, format=date_format) elif isinstance(month_date, dt.datetime): _month_date = month_date.date() elif isinstance(month_date, dt.date): _month_date = month_date else: raise TypeError("Invalid date type: {0}".format(type(month_date))) month_last_date = _month_date + relativedelta(day=1, months=+1, days=-1) month_first_date = _month_date + relativedelta(day=1) return month_first_date, month_last_date
{"/examples/example_dates_range_date.py": ["/pyfortified_datetime/__init__.py"], "/pyfortified_datetime/__init__.py": ["/pyfortified_datetime/dates_range.py", "/pyfortified_datetime/dates_month_first_last.py", "/pyfortified_datetime/dates_months.py"], "/examples/example_dates_month_first_last.py": ["/pyfortified_datetime/__init__.py"], "/examples/example_dates_months_generator.py": ["/pyfortified_datetime/__init__.py"]}
41,685
jeff00seattle/pyfortified-datetime
refs/heads/master
/pyfortified_datetime/__init__.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @copyright 2017 TUNE, Inc. (http://www.tune.com) # @namespace tune_mv_integration __title__ = 'pyfortified-datetime' __version__ = '0.1.0' __version_info__ = tuple(__version__.split('.')) __author__ = 'jeff00seattle' __license__ = 'MIT License' __copyright__ = 'Copyright 2018 jeff00seattle' from .dates_range import dates_range from .dates_month_first_last import dates_month_first_last from .dates_months import (dates_months_generator, dates_months_list)
{"/examples/example_dates_range_date.py": ["/pyfortified_datetime/__init__.py"], "/pyfortified_datetime/__init__.py": ["/pyfortified_datetime/dates_range.py", "/pyfortified_datetime/dates_month_first_last.py", "/pyfortified_datetime/dates_months.py"], "/examples/example_dates_month_first_last.py": ["/pyfortified_datetime/__init__.py"], "/examples/example_dates_months_generator.py": ["/pyfortified_datetime/__init__.py"]}
41,686
jeff00seattle/pyfortified-datetime
refs/heads/master
/examples/example_dates_month_first_last.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # from pprintpp import pprint import datetime as dt import pyfortified_datetime month_first_date, month_last_date = pyfortified_datetime.dates_month_first_last(dt.date(2016, 12, 20)) pprint(month_first_date) pprint(month_last_date) month_first_date, month_last_date = pyfortified_datetime.dates_month_first_last(dt.date(2016, 2, 3)) pprint(month_first_date) pprint(month_last_date) month_first_date, month_last_date = pyfortified_datetime.dates_month_first_last(dt.date(2017, 2, 3)) pprint(month_first_date) pprint(month_last_date)
{"/examples/example_dates_range_date.py": ["/pyfortified_datetime/__init__.py"], "/pyfortified_datetime/__init__.py": ["/pyfortified_datetime/dates_range.py", "/pyfortified_datetime/dates_month_first_last.py", "/pyfortified_datetime/dates_months.py"], "/examples/example_dates_month_first_last.py": ["/pyfortified_datetime/__init__.py"], "/examples/example_dates_months_generator.py": ["/pyfortified_datetime/__init__.py"]}
41,687
jeff00seattle/pyfortified-datetime
refs/heads/master
/pyfortified_datetime/dates_months.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # def dates_months_list(start_date, end_date, date_format="%Y-%m"): from dateutil.rrule import rrule, MONTHLY return [dt.strftime(date_format) for dt in rrule(MONTHLY, dtstart=start_date, until=end_date)] def dates_months_generator(start_date, end_date, date_format="%Y-%m"): from dateutil.rrule import rrule, MONTHLY return (dt.strftime(date_format) for dt in rrule(MONTHLY, dtstart=start_date, until=end_date))
{"/examples/example_dates_range_date.py": ["/pyfortified_datetime/__init__.py"], "/pyfortified_datetime/__init__.py": ["/pyfortified_datetime/dates_range.py", "/pyfortified_datetime/dates_month_first_last.py", "/pyfortified_datetime/dates_months.py"], "/examples/example_dates_month_first_last.py": ["/pyfortified_datetime/__init__.py"], "/examples/example_dates_months_generator.py": ["/pyfortified_datetime/__init__.py"]}
41,688
jeff00seattle/pyfortified-datetime
refs/heads/master
/examples/example_dates_months_generator.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # from pprintpp import pprint import datetime as dt import pyfortified_datetime start_dt = dt.date(2016, 12, 20) end_dt = dt.date(2018, 1, 11) print(type(pyfortified_datetime.dates_months_generator(start_dt, end_dt))) for dt in pyfortified_datetime.dates_months_generator(start_dt, end_dt): pprint(dt)
{"/examples/example_dates_range_date.py": ["/pyfortified_datetime/__init__.py"], "/pyfortified_datetime/__init__.py": ["/pyfortified_datetime/dates_range.py", "/pyfortified_datetime/dates_month_first_last.py", "/pyfortified_datetime/dates_months.py"], "/examples/example_dates_month_first_last.py": ["/pyfortified_datetime/__init__.py"], "/examples/example_dates_months_generator.py": ["/pyfortified_datetime/__init__.py"]}
41,704
MissionBit/MB_Portal
refs/heads/master
/staff/tasks.py
# Create your tasks here from __future__ import absolute_import, unicode_literals from celery import shared_task """ @shared_task def hello(): print("It's a beautiful day in the neighborhood") """
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,705
MissionBit/MB_Portal
refs/heads/master
/missionbit/azure_storage_backend.py
from django.utils.deconstruct import deconstructible from azure.storage.blob.blockblobservice import BlockBlobService from storages.backends.azure_storage import AzureStorage from storages.utils import setting @deconstructible class CustomAzureStorage(AzureStorage): # This is a workaround for AzureStorage to support custom domains custom_domain = setting("AZURE_CUSTOM_DOMAIN", None) @property def service(self): if self._service is None: self._service = BlockBlobService( self.account_name, self.account_key, is_emulated=self.is_emulated, custom_domain=self.custom_domain, ) return self._service def url(self, name, expire=None): url = super().url(name, expire=expire) if self.is_emulated and url.startswith("https://azurite:"): url = url.replace("https://azurite:", "http://localhost:") return url
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,706
MissionBit/MB_Portal
refs/heads/master
/home/migrations/0005_userprofile_in_classroom.py
# Generated by Django 2.2.3 on 2019-08-02 02:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("home", "0004_auto_20190802_0126")] operations = [ migrations.AddField( model_name="userprofile", name="in_classroom", field=models.BooleanField(default=False), ) ]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,707
MissionBit/MB_Portal
refs/heads/master
/student/urls.py
from django.urls import path, include from . import views urlpatterns = [ path("", views.student, name="student"), path("attendance_student/", views.attendance_student, name="attendance_student"), path("my_class_student/", views.my_class_student, name="my_class_student"), path( "session_view_student/", views.session_view_student, name="session_view_student" ), ]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,708
MissionBit/MB_Portal
refs/heads/master
/attendance/urls.py
from django.urls import path from . import views urlpatterns = [ path("", views.attendance, name="attendance"), path( "take_attendance/<course_id>/<date>/", views.take_attendance, name="take_attendance", ), path( "notify_absent_students/", views.notify_absent_students, name="notify_absent_students", ), ]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,709
MissionBit/MB_Portal
refs/heads/master
/home/generic_notifications.py
def get_generic_absence_notification(student, date): return ( "Hello, our records indicate that %s %s was absent on %s, " "please advise." % (student.first_name, student.last_name, date) )
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,710
MissionBit/MB_Portal
refs/heads/master
/attendance/views.py
from home.decorators import group_required_multiple from django.contrib.auth.models import User as DjangoUser from django.shortcuts import render, redirect from home.models.models import Classroom, Attendance, Notification from home.models.salesforce import ClassOffering from staff.staff_views_helper import class_offering_meeting_dates from datetime import datetime from django.template.defaulttags import register from django_q.tasks import async_task from home.generic_notifications import get_generic_absence_notification from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.conf import settings from django.contrib import messages import statistics @group_required_multiple(["staff", "teacher"]) def attendance(request): user_group = request.user.groups.first() if request.method == "POST": store_attendance_data(request) async_task( "attendance.views.update_course_attendance_statistic", request.POST.get("course_id"), ) return redirect("attendance") if request.GET.get("course_id") is not None: course_id = request.GET.get("course_id") context = get_classroom_attendance(course_id) context.update( { "attendance_statistic": get_course_attendance_statistic(course_id), "user_group": str(user_group), } ) else: attendance_averages = compile_attendance_averages_for_all_courses() context = { "classrooms": Classroom.objects.all(), "attendance_averages": attendance_averages, "user_group": str(user_group), } return render(request, "attendance.html", context) @group_required_multiple(["staff", "teacher"]) def take_attendance(request, course_id, date): context = take_attendance_context(course_id, date) return render(request, "attendance.html", context) @group_required_multiple(["staff", "teacher"]) def notify_absent_students(request): # This method is a candidate for an async_task date = get_date_from_template_returned_string(request.GET.get("date")) course = Classroom.objects.get(id=request.GET.get("course_id")) absences = Attendance.objects.filter( date=date, classroom_id=course.id, presence="Absent" ).select_related("student") # student_list = list(DjangoUser.objects.filter(id__in=[absence.student_id for absence in absences])) create_absence_notifications(request, absences, date) messages.add_message( request, messages.SUCCESS, "Absent Students Successfully Notified" ) return redirect("attendance") def get_classroom_attendance(course_id): dates = get_classroom_meeting_dates(course_id) classroom_attendance = Attendance.objects.filter(classroom_id=course_id) course = Classroom.objects.get(id=course_id).course daily_attendance = compile_daily_attendance_for_course(course_id) return { "classroom_attendance": classroom_attendance, "dates": dates, "course": course, "course_id": course_id, "daily_attendance": daily_attendance, } def take_attendance_context(course_id, date): course = Classroom.objects.get(id=course_id).course attendance_objects = Attendance.objects.filter(classroom_id=course_id, date=date) return { "course_name": course, "course_id": course_id, "attendance_objects": attendance_objects, } @group_required_multiple(["staff", "teacher"]) def store_attendance_data(request): date = get_date_from_template_returned_string(request.POST.get("date")) course_id = request.POST.get("course_id") attendance_objects = Attendance.objects.filter(classroom_id=course_id, date=date) for attendance_object in attendance_objects: attendance_object.presence = request.POST.get(str(attendance_object.student)) attendance_object.save() def compile_attendance_averages_for_all_courses(): attendance_averages = {} for classroom in Classroom.objects.all(): stat = get_course_attendance_statistic(classroom.id) attendance_averages.update({classroom.course: stat}) return attendance_averages def compile_daily_attendance_for_course(course_id): daily_attendance_record = {} dates = get_classroom_meeting_dates(course_id) for date in dates: daily_attendance = Attendance.objects.filter(classroom_id=course_id, date=date) average = round(get_average_attendance_from_list(daily_attendance) * 100, 2) daily_attendance_record.update({date: average}) return daily_attendance_record def get_average_attendance_from_list(daily_attendance): attendance_list = [ attendance_object.presence in ("Present", "Late") for attendance_object in daily_attendance ] return statistics.mean(attendance_list) if len(attendance_list) > 0 else 0 def get_classroom_meeting_dates(course_id): return class_offering_meeting_dates( ClassOffering.objects.get(name=Classroom.objects.get(id=course_id).course) ) @register.filter def get_item(dictionary, key): return dictionary.get(key) def get_date_from_template_returned_string(string_date): for date_format in ["%B %d, %Y", "%b. %d, %Y", "%bt. %d, %Y"]: try: return datetime.strptime(string_date, date_format).date() except ValueError: pass raise ValueError( "time data {!r} does not match any expected date format".format(string_date) ) def update_course_attendance_statistic(course_id): class_attendance = Attendance.objects.filter( classroom_id=course_id, date__range=["2000-01-01", datetime.today().date()] ) average = get_average_attendance_from_list(class_attendance) classroom = Classroom.objects.get(id=course_id) classroom.attendance_summary = {"attendance_statistic": round(average * 100, 2)} classroom.save() def get_course_attendance_statistic(course_id): return Classroom.objects.get(id=course_id).attendance_summary.get( "attendance_statistic" ) def create_absence_notifications(request, absences, date): django_user = DjangoUser.objects.get(id=request.user.id) notifications = [ Notification( subject="%s %s absence on %s" % (absence.student.first_name, absence.student.last_name, date), notification=get_generic_absence_notification(absence.student, date), user_id=absence.student.id, attendance_id=absence.id, created_by=django_user, email_recipients=True, ) for absence in absences ] Notification.objects.bulk_create(notifications) email_absence_notifications(request, absences, date) def email_absence_notifications(request, email_list, date): subject = "Absence on %s" % date msg_html = render_to_string( "email_templates/absence_email.html", { "subject": subject, "date": date, "from": DjangoUser.objects.get(id=request.user.id), }, ) text_content = "You are being notified about something" recipient_list = ["tyler.iams@gmail.com", "iams.sophia@gmail.com"] # Will replace with [absence.student.email for user in email_list] email = EmailMultiAlternatives( subject, text_content, settings.EMAIL_HOST_USER, recipient_list ) email.attach_alternative(msg_html, "text/html") email.send() messages.add_message(request, messages.SUCCESS, "Recipients Successfully Emailed")
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,711
MissionBit/MB_Portal
refs/heads/master
/home/forms.py
from django import forms from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm from django.contrib.auth.models import User as DjangoUser from django.contrib.auth.models import Group from home.models.models import ( Announcement, Classroom, Form, Esign, FormDistribution, Notification, Session, Resource, ) from home.models.salesforce import ( Contact, User, Account, ClassOffering, ClassEnrollment, ) from home.choices import * class DateInput(forms.DateInput): input_type = "date" is_required = True class MissionBitUserCreationForm(forms.ModelForm): account = forms.ModelChoiceField(queryset=Account.objects.all(), required=False) first_name = forms.CharField(label="First name", max_length=100) last_name = forms.CharField(label="Last name", max_length=100) email = forms.EmailField(label="email", max_length=100) owner = forms.ModelChoiceField(queryset=User.objects.filter(is_active=True)) class Meta: model = Contact fields = ["account", "first_name", "last_name", "email", "owner"] class RaceGenderEthnicityForm(forms.ModelForm): which_best_describes_your_ethnicity = forms.ChoiceField( label="Ethnicity - Optional", choices=ETHNICITY_CHOICES, required=False ) race = forms.ChoiceField( label="Race - Optional", choices=RACE_CHOICES, required=False ) gender = forms.ChoiceField( label="Gender - Optional", choices=GENDER_CHOICES, required=False ) class Meta: model = Contact fields = [] class ContactRegisterForm(forms.Form): birthdate = forms.DateField(widget=DateInput) expected_graduation_year = forms.ChoiceField( label="Expected graduation year", choices=GRAD_YEAR_CHOICES, required=False ) which_best_describes_your_ethnicity = forms.ChoiceField( label="Ethnicity - Optional", choices=ETHNICITY_CHOICES, required=False ) race = forms.ChoiceField( label="Race - Optional", choices=RACE_CHOICES, required=False ) gender = forms.ChoiceField( label="Gender - Optional", choices=GENDER_CHOICES, required=False ) class Meta: fields = [ "birthdate", "which_best_describes_your_ethnicity", "race", "gender", "expected_graduation_year", ] class UserRegisterForm(UserCreationForm): username = forms.CharField(label="Choose Username", max_length=100) email = forms.EmailField(label="email", max_length=100) first_name = forms.CharField(label="First name", max_length=100) last_name = forms.CharField(label="Last name", max_length=100) class Meta: model = DjangoUser fields = [ "username", "email", "first_name", "last_name", "password1", "password2", ] class CreateStaffForm(MissionBitUserCreationForm): title = forms.CharField(initial="Staff", disabled=True) class Meta: model = Contact fields = [ "account", "first_name", "last_name", "email", "birthdate", "owner", "title", ] widgets = {"birthdate": DateInput()} class CreateStudentForm(RaceGenderEthnicityForm, MissionBitUserCreationForm): title = forms.CharField(initial="Student", disabled=True) expected_graduation_year = forms.ChoiceField( label="Expected graduation year", choices=GRAD_YEAR_CHOICES, required=False ) class Meta: model = Contact fields = [ "account", "first_name", "last_name", "email", "birthdate", "owner", "title", "expected_graduation_year", "which_best_describes_your_ethnicity", "race", "gender", ] widgets = {"birthdate": DateInput()} class CreateTeacherForm(RaceGenderEthnicityForm, MissionBitUserCreationForm): title = forms.CharField(initial="Teacher", disabled=True) class Meta: model = Contact fields = [ "account", "first_name", "last_name", "email", "birthdate", "owner", "title", "which_best_describes_your_ethnicity", "race", "gender", ] widgets = {"birthdate": DateInput()} class CreateVolunteerForm(RaceGenderEthnicityForm, MissionBitUserCreationForm): title = forms.CharField(initial="Volunteer", disabled=True) class Meta: model = Contact fields = [ "account", "first_name", "last_name", "email", "birthdate", "owner", "title", "which_best_describes_your_ethnicity", "race", "gender", ] widgets = {"birthdate": DateInput()} class CreateClassroomForm(forms.ModelForm): course = forms.ModelChoiceField(queryset=ClassOffering.objects.all()) teacher = forms.ModelChoiceField( queryset=Contact.objects.filter(title="Teacher", is_deleted=False) ) teacher_assistant = forms.ModelChoiceField( queryset=Contact.objects.filter(title="Teacher", is_deleted=False) ) volunteers = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple(), queryset=Contact.objects.filter(title="Volunteer", is_deleted=False), ) students = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple(), queryset=Contact.objects.filter(title="Student", is_deleted=False), ) created_by = forms.ModelChoiceField(queryset=User.objects.filter(is_active=True)) class Meta: model = ClassEnrollment fields = ["course", "teacher", "teacher_assistant", "volunteers", "students"] class CreateClassOfferingForm(forms.ModelForm): name = forms.CharField(max_length="80") location = forms.ModelChoiceField( queryset=Account.objects.filter(npe01_systemis_individual=False) ) created_by = forms.ModelChoiceField(queryset=User.objects.filter(is_active=True)) description = forms.CharField(label="Description", max_length=100) instructor = forms.ModelChoiceField( queryset=Contact.objects.filter(title="Teacher", is_deleted=False) ) meeting_days = forms.ChoiceField(label="Meeting Days", choices=MEETING_DAYS_CHOICES) class Meta: model = ClassOffering fields = [ "name", "location", "created_by", "start_date", "end_date", "description", "instructor", "meeting_days", ] widgets = {"start_date": DateInput(), "end_date": DateInput()} def __str__(self): return "%s" % self.name class ChangePwdForm(PasswordChangeForm): old_password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ["old_password", "new_password1", "new_password2"] widgets = {"password": forms.PasswordInput()} class MakeAnnouncementForm(forms.ModelForm): title = forms.CharField(max_length=240) announcement = forms.Textarea() recipient_groups = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Group.objects.all(), required=False, ) recipient_classrooms = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Classroom.objects.all(), required=False, ) email_recipients = forms.BooleanField(initial=False, required=False) class Meta: model = Announcement fields = [ "title", "announcement", "recipient_groups", "recipient_classrooms", "email_recipients", ] class ChangeTeacherForm(forms.Form): teacher = forms.ModelChoiceField( queryset=DjangoUser.objects.filter(groups__name="teacher"), required=False, label="", ) class Meta: fields = ["teacher"] class AddVolunteerForm(forms.Form): volunteer = forms.ModelChoiceField( queryset=DjangoUser.objects.filter(groups__name="volunteer"), required=False, label="Add Volunteer", ) class Meta: fields = ["volunteers"] class AddStudentForm(forms.Form): student = forms.ModelChoiceField( queryset=DjangoUser.objects.filter(groups__name="student"), required=False, label="Add Student", ) class Meta: fields = ["students"] class PostFormForm(forms.ModelForm): name = forms.CharField(max_length=240) description = forms.Textarea() form = forms.FileField() esign = forms.ModelChoiceField(queryset=Esign.objects.all(), required=False) recipient_groups = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Group.objects.all(), required=False, ) recipient_classrooms = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Classroom.objects.all(), required=False, ) email_recipients = forms.BooleanField(initial=False, required=False) class Meta: model = Form fields = [ "name", "description", "form", "esign", "recipient_groups", "recipient_classrooms", "email_recipients", ] class CreateEsignForm(forms.Form): name = forms.CharField(max_length=240) link = forms.URLField() class Meta: model = Esign fields = ["name", "link"] class CollectForms(forms.ModelForm): submitted = forms.BooleanField(initial=False, required=False) class Meta: model = FormDistribution fields = ["submitted"] class NotifyUnsubmittedUsersForm(forms.ModelForm): subject = forms.CharField(max_length=240, label="Subject") notification = forms.Textarea() email_recipients = forms.BooleanField(initial=False, required=False) class Meta: model = Notification fields = ["subject", "notification", "email_recipients"] class AddCurriculumForm(forms.ModelForm): title = forms.CharField(max_length=240, required=False) description = forms.CharField( max_length=2000, required=False, widget=forms.Textarea ) lesson_plan = forms.FileField(required=False) lecture = forms.FileField(required=False) video = forms.URLField(required=False) activity = forms.FileField(required=False) class Meta: model = Session fields = ["title", "description", "lesson_plan", "lecture", "video", "activity"] class AddResourceForm(forms.ModelForm): title = forms.CharField(max_length=240) description = forms.CharField(max_length=2000, widget=forms.Textarea) link = forms.URLField(required=False) file = forms.FileField(required=False) class Meta: model = Resource fields = ["title", "description", "link", "file"] class AddForumForm(forms.ModelForm): forum_title = forms.CharField(max_length=240) forum = forms.URLField() class Meta: model = Classroom fields = ["forum_title", "forum"]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,712
MissionBit/MB_Portal
refs/heads/master
/tests/test_volunteer.py
from django.test import TestCase, RequestFactory from volunteer.views import * from django.contrib.auth.models import User, Group from django.urls import reverse from rest_framework import status """ class BaseTestCase(TestCase): def create_authenticated_volunteer_user(self): user = User.objects.create_user( username="testuser", email="test@email.com", first_name="testfirst", last_name="testlast", password="beautifulbutterfly125", ) Group.objects.get_or_create(name="volunteer") vol_group = Group.objects.get(name="volunteer") vol_group.user_set.add(user) return user def create_authenticated_nonvolunteer_user(self): user = User.objects.create_user( username="otherstafftestuser", email="othertest@email.com", first_name="othertestfirst", last_name="othertestlast", password="beautifulbutterfly125", ) Group.objects.get_or_create(name="staff") staff_group = Group.objects.get(name="staff") staff_group.user_set.add(user) return user class VolunteerViewsTest(BaseTestCase): def test_volunteer(self): request = RequestFactory().get(reverse("home-home")) request.user = self.create_authenticated_nonvolunteer_user() response = volunteer(request) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) request.user = self.create_authenticated_volunteer_user() response = volunteer(request) self.assertEqual(response.status_code, status.HTTP_200_OK) """
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,713
MissionBit/MB_Portal
refs/heads/master
/tests/test_staff.py
from django.test import TestCase, RequestFactory from staff.views import * from django.contrib.auth.models import User as DjangoUser from home.models.models import Classroom, UserProfile, ClassroomMembership from django.urls import reverse from rest_framework import status from home.models.salesforce import ( Contact, User, Account, ClassOffering, ClassEnrollment, ) class BaseTestCase(TestCase): def setUp(self) -> None: teacher = DjangoUser.objects.create_user( username="classroom_teacher", email="teacher@email.com", first_name="class", last_name="teacher", password="testpassword", ) teacher.userprofile.salesforce_id = "clatea19010101" teacher.save() Group.objects.get(name="teacher").user_set.add(teacher) t_a = DjangoUser.objects.create_user( username="classroom_teacher2", email="teacher2@email.com", first_name="tassist", last_name="user", password="testpassword", ) t_a.userprofile.salesforce_id = "tasuse19010101" t_a.save() Group.objects.get(name="teacher").user_set.add(t_a) student = DjangoUser.objects.create_user( username="classroom_student", email="student@email.com", first_name="student", last_name="user", password="testpassword", ) student.userprofile.salesforce_id = "stuuse19010101" student.save() Group.objects.get(name="teacher").user_set.add(student) volunteer = DjangoUser.objects.create_user( username="classroom_vol", email="teacher2@email.com", first_name="volunteer", last_name="user", password="testpassword", ) volunteer.userprofile.salesforce_id = "voluse19010101" volunteer.save() Group.objects.get(name="teacher").user_set.add(volunteer) classroom = Classroom.objects.create(course="Test_Course") ClassroomMembership.objects.create( member=teacher, classroom=classroom, membership_type="teacher" ) ClassroomMembership.objects.create( member=t_a, classroom=classroom, membership_type="teacher_assistant" ) ClassroomMembership.objects.create( member=volunteer, classroom=classroom, membership_type="volunteer" ) ClassroomMembership.objects.create( member=student, classroom=classroom, membership_type="student" ) def create_staff_user(self): user = DjangoUser.objects.create_user( username="testuser", email="test@email.com", first_name="testfirst", last_name="testlast", password="top_secret125", ) Group.objects.get_or_create(name="staff") staff_group = Group.objects.get(name="staff") staff_group.user_set.add(user) return user def create_nonstaff_user(self): user = DjangoUser.objects.create_user( username="otherstafftestuser", email="othertest@email.com", first_name="othertestfirst", last_name="othertestlast", password="top_secret125", ) Group.objects.get_or_create(name="student") student_group = Group.objects.get(name="student") student_group.user_set.add(user) return user def valid_create_user_form(self, group): return { "first_name": "test_user", "last_name": "test_user", "email": "test@email.com", "birthdate": "01/01/1901", "owner": User.objects.filter(is_active=True).first().id, "title": group, } def valid_create_class_offering_form(self): return { "name": "Test Course", "location": Account.objects.get_or_create(name="Test_Org", npe01_systemis_individual=False)[0].id, "created_by": User.objects.filter(is_active=True).first().id, "start_date": "2019-07-07", "end_date": "2019-09-09", "description": "This is a test classroom", "instructor": self.get_or_create_test_teacher().id, "meeting_days": "M/W", } def valid_create_classroom_form(self): return { "course": self.get_or_create_test_course().id, "teacher": self.get_or_create_test_teacher().id, "teacher_assistant": self.get_or_create_test_teacher().id, "volunteers": self.get_or_create_test_volunteer().id, "students": self.get_or_create_test_student().id, "created_by": User.objects.filter(is_active=True).first().id, } def get_or_create_test_course(self): course = ClassOffering.objects.get_or_create( name="Test Course", location=Account.objects.get_or_create(name="Test_Org", npe01_systemis_individual=False)[0], created_by=User.objects.filter(is_active=True).first(), start_date="2019-07-07", end_date="2019-09-09", instructor=self.get_or_create_test_teacher(), meeting_days="M/W", ) return course[0] def get_or_create_test_teacher(self): contact = Contact.objects.get_or_create( first_name="classroom", last_name="teacher", email="clatea@gmail.com", birthdate="1901-01-01", title="Teacher", owner=User.objects.filter(is_active=True).first(), race="White", which_best_describes_your_ethnicity="Hispanic/Latinx", gender="Female", ) return contact[0] def get_or_create_test_student(self): contact = Contact.objects.get_or_create( first_name="student", last_name="user", email="clastu@gmail.com", birthdate="1901-01-01", title="Student", owner=User.objects.filter(is_active=True).first(), race="White", which_best_describes_your_ethnicity="Hispanic/Latinx", gender="Female", ) return contact[0] def get_or_create_test_volunteer(self): contact = Contact.objects.get_or_create( first_name="volunteer", last_name="user", email="clavol@gmail.com", birthdate="1901-01-01", title="Volunteer", owner=User.objects.filter(is_active=True).first(), race="White", which_best_describes_your_ethnicity="Hispanic/Latinx", gender="Female", ) return contact[0] def valid_make_announcement_form(self): return { "title": "Test Announcement", "announcement": "This is the test announcement", "email_recipients": True, } class StaffViewsTest(BaseTestCase): databases = "__all__" def test_staff(self): self.client.force_login(self.create_staff_user()) response = self.client.get(reverse("staff")) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTemplateUsed(response, "staff.html") self.client.force_login(self.create_nonstaff_user()) self.assertRaises(PermissionError) def test_classroom_management(self): self.client.force_login(self.create_staff_user()) response = self.client.get(reverse("classroom_management")) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTemplateUsed(response, "classroom_management.html") def test_create_classroom(self): self.client.force_login(self.create_staff_user()) response = self.client.get(reverse("create_classroom")) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTemplateUsed(response, "create_classroom.html") response = self.client.post( reverse("create_classroom"), self.valid_create_classroom_form() ) ClassOffering.objects.get(name="Test Course").delete() Contact.objects.get(client_id="clatea19010101").delete() Contact.objects.get(client_id="stuuse19010101").delete() Contact.objects.get(client_id="voluse19010101").delete() Account.objects.get(name="Test_Org").delete() self.assertEqual(response.url, reverse("staff")) self.assertEqual(response.status_code, status.HTTP_302_FOUND) def test_create_classroom_invalid_form(self): self.client.force_login(self.create_staff_user()) response = self.client.post(reverse("create_classroom"), {}) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_create_class_offering(self): self.client.force_login(self.create_staff_user()) response = self.client.get(reverse("create_class_offering")) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTemplateUsed(response, "create_class_offering.html") response = self.client.post( reverse("create_class_offering"), self.valid_create_class_offering_form() ) ClassOffering.objects.get(name="Test Course").delete() Account.objects.get(name="Test_Org").delete() self.assertEqual(response.url, reverse("staff")) self.assertEqual(response.status_code, status.HTTP_302_FOUND) def test_create_class_offering_invalid_form(self): self.client.force_login(self.create_staff_user()) response = self.client.post(reverse("create_class_offering"), {}) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_make_announcement(self): self.client.force_login(self.create_staff_user()) response = self.client.get(reverse("make_announcement")) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTemplateUsed(response, "make_announcement.html") response = self.client.post( reverse("make_announcement"), self.valid_make_announcement_form() ) self.assertEqual(response.url, reverse("staff")) self.assertEqual(response.status_code, status.HTTP_302_FOUND) def test_make_announcement_invalid_form(self): self.client.force_login(self.create_staff_user()) response = self.client.post(reverse("make_announcement"), {}) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_create_staff_user(self): self.client.force_login(self.create_staff_user()) response = self.client.get(reverse("create_staff_user")) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTemplateUsed(response, "create_staff_user.html") response = self.client.post( reverse("create_staff_user"), self.valid_create_user_form("staff") ) Contact.objects.get(client_id="testes19010101").delete() self.assertEqual(response.url, reverse("staff")) self.assertEqual(response.status_code, status.HTTP_302_FOUND) self.client.force_login(self.create_nonstaff_user()) self.assertRaises(PermissionError) def test_create_staff_user_invalid_form(self): self.client.force_login(self.create_staff_user()) response = self.client.post(reverse("create_staff_user"), {}) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_create_teacher_user(self): self.client.force_login(self.create_staff_user()) response = self.client.get(reverse("create_teacher_user")) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTemplateUsed(response, "create_teacher_user.html") response = self.client.post( reverse("create_teacher_user"), self.valid_create_user_form("teacher") ) Contact.objects.get(client_id="testes19010101").delete() self.assertEqual(response.url, reverse("staff")) self.assertEqual(response.status_code, status.HTTP_302_FOUND) self.client.force_login(self.create_nonstaff_user()) self.assertRaises(PermissionError) def test_create_teacher_user_invalid_form(self): self.client.force_login(self.create_staff_user()) response = self.client.post(reverse("create_teacher_user"), {}) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_create_student_user(self): self.client.force_login(self.create_staff_user()) response = self.client.get(reverse("create_student_user")) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTemplateUsed(response, "create_student_user.html") response = self.client.post( reverse("create_student_user"), self.valid_create_user_form("student") ) Contact.objects.get(client_id="testes19010101").delete() self.assertEqual(response.url, reverse("staff")) self.assertEqual(response.status_code, status.HTTP_302_FOUND) self.client.force_login(self.create_nonstaff_user()) self.assertRaises(PermissionError) def test_create_student_user_invalid_form(self): self.client.force_login(self.create_staff_user()) response = self.client.post(reverse("create_student_user"), {}) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_create_volunteer_user(self): self.client.force_login(self.create_staff_user()) response = self.client.get(reverse("create_volunteer_user")) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTemplateUsed(response, "create_volunteer_user.html") response = self.client.post( reverse("create_volunteer_user"), self.valid_create_user_form("volunteer") ) Contact.objects.get(client_id="testes19010101").delete() self.assertEqual(response.url, reverse("staff")) self.assertEqual(response.status_code, status.HTTP_302_FOUND) self.client.force_login(self.create_nonstaff_user()) self.assertRaises(PermissionError) def test_create_volunteer_user_invalid_form(self): self.client.force_login(self.create_staff_user()) response = self.client.post(reverse("create_volunteer_user"), {}) self.assertEqual(response.status_code, status.HTTP_200_OK)
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,714
MissionBit/MB_Portal
refs/heads/master
/tests/test_teacher.py
from django.test import TestCase, RequestFactory from teacher.views import * from django.contrib.auth.models import User, Group from django.urls import reverse from rest_framework import status """ class BaseTestCase(TestCase): def create_authenticated_teacher_user(self): user = User.objects.create_user( username="testuser", email="test@email.com", first_name="testfirst", last_name="testlast", password="beautifulbutterfly125", ) Group.objects.get_or_create(name="teacher") teacher_group = Group.objects.get(name="teacher") teacher_group.user_set.add(user) return user def create_authenticated_nonteacher_user(self): user = User.objects.create_user( username="otherstafftestuser", email="othertest@email.com", first_name="othertestfirst", last_name="othertestlast", password="beautifulbutterfly125", ) Group.objects.get_or_create(name="staff") staff_group = Group.objects.get(name="staff") staff_group.user_set.add(user) return user class TeacherViewsTest(BaseTestCase): def test_teacher(self): request = RequestFactory().get(reverse("home-home")) request.user = self.create_authenticated_nonteacher_user() response = teacher(request) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) request.user = self.create_authenticated_teacher_user() response = teacher(request) self.assertEqual(response.status_code, status.HTTP_200_OK) """
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,715
MissionBit/MB_Portal
refs/heads/master
/home/models/salesforce.py
from salesforce import models from home.choices import * class Account(models.Model): is_deleted = models.BooleanField( verbose_name="Deleted", sf_read_only=models.READ_ONLY, default=False ) master_record = models.ForeignKey( "self", models.DO_NOTHING, related_name="account_masterrecord_set", sf_read_only=models.READ_ONLY, blank=True, null=True, ) name = models.CharField(max_length=255, verbose_name="Account Name") type = models.CharField( max_length=40, verbose_name="Account Type", choices=ACCOUNT_TYPE_CHOICES, blank=True, null=True, ) parent = models.ForeignKey( "self", models.DO_NOTHING, related_name="account_parent_set", blank=True, null=True, ) billing_street = models.TextField(blank=True, null=True) billing_city = models.CharField(max_length=40, blank=True, null=True) billing_state = models.CharField( max_length=80, verbose_name="Billing State/Province", blank=True, null=True ) billing_postal_code = models.CharField( max_length=20, verbose_name="Billing Zip/Postal Code", blank=True, null=True ) billing_country = models.CharField(max_length=80, blank=True, null=True) npe01_systemis_individual = models.BooleanField( db_column="npe01__SYSTEMIsIndividual__c", custom=True, verbose_name="_SYSTEM: IsIndividual", default=models.DEFAULTED_ON_CREATE, help_text="Indicates whether or not this Account is special for Contacts (Household, One-to-One, Individual) vs a normal Account.", ) class Meta(models.Model.Meta): db_table = "Account" verbose_name = "Account" verbose_name_plural = "Accounts" # keyPrefix = '001' def __str__(self): return "%s" % self.name class Contact(models.Model): is_deleted = models.BooleanField( verbose_name="Deleted", sf_read_only=models.READ_ONLY, default=False ) master_record = models.ForeignKey( "self", models.DO_NOTHING, related_name="contact_masterrecord_set", sf_read_only=models.READ_ONLY, blank=True, null=True, ) account = models.ForeignKey( Account, models.DO_NOTHING, related_name="contact_account_set", blank=True, null=True, ) # Master Detail Relationship * last_name = models.CharField(max_length=80) first_name = models.CharField(max_length=40, blank=True, null=True) salutation = models.CharField( max_length=40, choices=SALUTATION_CHOICES, blank=True, null=True ) middle_name = models.CharField(max_length=40, blank=True, null=True) suffix = models.CharField(max_length=40, blank=True, null=True) name = models.CharField( max_length=121, verbose_name="Full Name", sf_read_only=models.READ_ONLY ) mailing_street = models.TextField(blank=True, null=True) mailing_city = models.CharField(max_length=40, blank=True, null=True) mailing_state = models.CharField( max_length=80, verbose_name="Mailing State/Province", blank=True, null=True ) mailing_postal_code = models.CharField( max_length=20, verbose_name="Mailing Zip/Postal Code", blank=True, null=True ) mailing_country = models.CharField(max_length=80, blank=True, null=True) mailing_state_code = models.CharField( max_length=10, verbose_name="Mailing State/Province Code", choices=STATE_CHOICES, blank=True, null=True, ) mailing_country_code = models.CharField( max_length=10, default=models.DEFAULTED_ON_CREATE, choices=STATE_CHOICES, blank=True, null=True, ) mobile_phone = models.CharField(max_length=40, blank=True, null=True) home_phone = models.CharField(max_length=40, blank=True, null=True) other_phone = models.CharField(max_length=40, blank=True, null=True) email = models.EmailField(blank=True, null=True) title = models.CharField(max_length=128, blank=True, null=True) department = models.CharField(max_length=80, blank=True, null=True) birthdate = models.DateField(blank=True, null=True) owner = models.ForeignKey( "User", models.DO_NOTHING, related_name="contact_owner_set", blank=True ) created_date = models.DateTimeField(sf_read_only=models.READ_ONLY) created_by = models.ForeignKey( "User", models.DO_NOTHING, related_name="contact_createdby_set", sf_read_only=models.READ_ONLY, ) last_modified_date = models.DateTimeField(sf_read_only=models.READ_ONLY) last_modified_by = models.ForeignKey( "User", models.DO_NOTHING, related_name="contact_lastmodifiedby_set", sf_read_only=models.READ_ONLY, ) system_modstamp = models.DateTimeField(sf_read_only=models.READ_ONLY) last_activity_date = models.DateField( verbose_name="Last Activity", sf_read_only=models.READ_ONLY, blank=True, null=True, ) last_curequest_date = models.DateTimeField( db_column="LastCURequestDate", verbose_name="Last Stay-in-Touch Request Date", sf_read_only=models.READ_ONLY, blank=True, null=True, ) last_cuupdate_date = models.DateTimeField( db_column="LastCUUpdateDate", verbose_name="Last Stay-in-Touch Save Date", sf_read_only=models.READ_ONLY, blank=True, null=True, ) last_viewed_date = models.DateTimeField( sf_read_only=models.READ_ONLY, blank=True, null=True ) last_referenced_date = models.DateTimeField( sf_read_only=models.READ_ONLY, blank=True, null=True ) email_bounced_reason = models.CharField(max_length=255, blank=True, null=True) email_bounced_date = models.DateTimeField(blank=True, null=True) is_email_bounced = models.BooleanField(sf_read_only=models.READ_ONLY, default=False) photo_url = models.URLField( verbose_name="Photo URL", sf_read_only=models.READ_ONLY, blank=True, null=True ) jigsaw_contact_id = models.CharField( max_length=20, verbose_name="Jigsaw Contact ID", sf_read_only=models.READ_ONLY, blank=True, null=True, ) individual = models.ForeignKey( "Individual", models.DO_NOTHING, blank=True, null=True ) race = models.CharField( custom=True, max_length=255, verbose_name="Which best describes your race?", choices=RACE_CHOICES, blank=True, null=True, ) gender = models.CharField( custom=True, max_length=255, choices=GENDER_CHOICES, blank=True, null=True ) which_best_describes_your_ethnicity = models.CharField( custom=True, db_column="Which_best_describes_your_ethnicity__c", max_length=255, verbose_name="Which best describes your ethnicity?", choices=ETHNICITY_CHOICES, blank=True, null=True, ) expected_graduation_year = models.CharField( custom=True, db_column="Expected_graduation_year__c", max_length=4, verbose_name="Expected graduation year", help_text="Enter the year this contact is expected to graduate. For example, 2020", blank=True, null=True, ) current_grade_level = models.CharField( custom=True, db_column="Current_grade_level__c", max_length=1300, verbose_name="Current grade level", sf_read_only=models.READ_ONLY, blank=True, null=True, ) volunteer_area_s_of_interest = models.CharField( custom=True, db_column="Volunteer_area_s_of_interest__c", max_length=4099, verbose_name="Volunteer area(s) of interest", choices=[("Classroom", "Classroom"), ("Event", "Event"), ("Other", "Other")], blank=True, null=True, ) enrollments_this_semester_applied = models.DecimalField( custom=True, db_column="enrollments_this_semester_Applied__c", max_digits=2, decimal_places=0, verbose_name="# enrollments this semester - Applied", help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", blank=True, null=True, ) enrollments_this_semester_waitlisted = models.DecimalField( custom=True, db_column="enrollments_this_semester_Waitlisted__c", max_digits=2, decimal_places=0, verbose_name="# enrollments this semester - Waitlisted", help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", blank=True, null=True, ) enrollments_this_semester_rejected = models.DecimalField( custom=True, db_column="enrollments_this_semester_Rejected__c", max_digits=2, decimal_places=0, verbose_name="# enrollments this semester - Rejected", help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", blank=True, null=True, ) enrollments_this_semester_drop_out = models.DecimalField( custom=True, db_column="enrollments_this_semester_Drop_out__c", max_digits=2, decimal_places=0, verbose_name="# enrollments this semester - Drop out", help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", blank=True, null=True, ) race_other = models.CharField( custom=True, db_column="Race_Other__c", max_length=100, verbose_name="Which best describes your race? (Other)", blank=True, null=True, ) gender_other = models.CharField( custom=True, db_column="Gender_Other__c", max_length=50, verbose_name="Gender (Other)", blank=True, null=True, ) parent_guardian_first_name = models.CharField( custom=True, db_column="Parent_Guardian_first_name__c", max_length=100, verbose_name="Parent/Guardian first name", blank=True, null=True, ) parent_guardian_last_name = models.CharField( custom=True, db_column="Parent_Guardian_last_name__c", max_length=100, verbose_name="Parent/Guardian last name", blank=True, null=True, ) parent_guardian_phone = models.CharField( custom=True, db_column="Parent_Guardian_phone__c", max_length=40, verbose_name="Parent/Guardian phone", blank=True, null=True, ) parent_guardian_email = models.EmailField( custom=True, db_column="Parent_Guardian_email__c", verbose_name="Parent/Guardian email", blank=True, null=True, ) dm_current_grade = models.CharField( custom=True, db_column="DM_Current_grade__c", max_length=255, verbose_name="DM - Current grade", help_text="Need this for data migration to calculate Expected Graduation Year? If not, delete this field.", choices=CURRENT_GRADE_CHOICES, blank=True, null=True, ) client_id = models.CharField( custom=True, db_column="Client_ID__c", max_length=14, verbose_name="Client ID", help_text='3 first letters of first name, 3 first letters of last name, and birthdate "AAABBB00000000" (Only used for students and parents). This field is auto-populated by FormAssembly.', blank=True, null=True, ) npsp_primary_affiliation = models.ForeignKey( Account, models.DO_NOTHING, db_column="npsp__Primary_Affiliation__c", custom=True, related_name="contact_npspprimaryaffiliation_set", blank=True, null=True, ) class Meta(models.Model.Meta): db_table = "Contact" verbose_name = "Contact" verbose_name_plural = "Contacts" # keyPrefix = '003' def __str__(self): return "%s %s" % (self.first_name, self.last_name) class User(models.Model): username = models.CharField(max_length=80) last_name = models.CharField(max_length=80) first_name = models.CharField(max_length=40, blank=True, null=True) middle_name = models.CharField(max_length=40, blank=True, null=True) suffix = models.CharField(max_length=40, blank=True, null=True) name = models.CharField( max_length=121, verbose_name="Full Name", sf_read_only=models.READ_ONLY ) company_name = models.CharField(max_length=80, blank=True, null=True) division = models.CharField(max_length=80, blank=True, null=True) department = models.CharField(max_length=80, blank=True, null=True) title = models.CharField(max_length=80, blank=True, null=True) street = models.TextField(blank=True, null=True) city = models.CharField(max_length=40, blank=True, null=True) state = models.CharField( max_length=80, verbose_name="State/Province", blank=True, null=True ) postal_code = models.CharField( max_length=20, verbose_name="Zip/Postal Code", blank=True, null=True ) country = models.CharField(max_length=80, blank=True, null=True) is_active = models.BooleanField( verbose_name="Active", default=models.DEFAULTED_ON_CREATE ) class Meta(models.Model.Meta): db_table = "User" verbose_name = "User" verbose_name_plural = "Users" # keyPrefix = '003' def __str__(self): if self.is_active: active = "Active" else: active = "Inactive" return "%s %s -- %s" % (self.first_name, self.last_name, active) class Individual(models.Model): owner = models.ForeignKey( "User", models.DO_NOTHING, related_name="individual_owner_set" ) # Master Detail Relationship * is_deleted = models.BooleanField( verbose_name="Deleted", sf_read_only=models.READ_ONLY, default=False ) last_name = models.CharField(max_length=80) first_name = models.CharField(max_length=40, blank=True, null=True) salutation = models.CharField( max_length=40, choices=SALUTATION_CHOICES, blank=True, null=True ) middle_name = models.CharField(max_length=40, blank=True, null=True) suffix = models.CharField(max_length=40, blank=True, null=True) name = models.CharField(max_length=121, sf_read_only=models.READ_ONLY) class Meta(models.Model.Meta): db_table = "Individual" verbose_name = "Individual" verbose_name_plural = "Individuals" # keyPrefix = '003' class ClassOffering(models.Model): # owner = models.ForeignKey('Group', models.DO_NOTHING) # Reference to tables [Group, User] is_deleted = models.BooleanField( verbose_name="Deleted", sf_read_only=models.READ_ONLY, default=False ) name = models.CharField( max_length=80, verbose_name="Class Offering Name", default=models.DEFAULTED_ON_CREATE, blank=True, null=True, ) created_date = models.DateTimeField(sf_read_only=models.READ_ONLY) created_by = models.ForeignKey( "User", models.DO_NOTHING, related_name="classoffering_createdby_set", sf_read_only=models.READ_ONLY, ) last_modified_date = models.DateTimeField(sf_read_only=models.READ_ONLY) last_modified_by = models.ForeignKey( "User", models.DO_NOTHING, related_name="classoffering_lastmodifiedby_set", sf_read_only=models.READ_ONLY, ) system_modstamp = models.DateTimeField(sf_read_only=models.READ_ONLY) last_viewed_date = models.DateTimeField( sf_read_only=models.READ_ONLY, blank=True, null=True ) last_referenced_date = models.DateTimeField( sf_read_only=models.READ_ONLY, blank=True, null=True ) start_date = models.DateField( custom=True, db_column="Start_Date__c", verbose_name="Start Date", blank=True, null=True, ) end_date = models.DateField( custom=True, db_column="End_Date__c", verbose_name="End Date", blank=True, null=True, ) description = models.TextField(custom=True, blank=True, null=True) location = models.ForeignKey( Account, models.DO_NOTHING, custom=True, blank=True, null=True ) course = models.CharField( custom=True, max_length=255, choices=COURSE_CHOICES, blank=True, null=True ) instructor = models.ForeignKey( "Contact", models.DO_NOTHING, custom=True, blank=True, null=True ) academic_semester = models.CharField( custom=True, db_column="Academic_semester__c", max_length=1300, verbose_name="Academic semester", sf_read_only=models.READ_ONLY, blank=True, null=True, ) meeting_days = models.CharField( custom=True, db_column="Meeting_Days__c", max_length=255, verbose_name="Meeting Days", choices=MEETING_DAYS_CHOICES, blank=True, null=True, ) count_total_female_students = models.DecimalField( custom=True, db_column="Count_total_female_students__c", max_digits=18, decimal_places=0, verbose_name="Count - Total Female Students", sf_read_only=models.READ_ONLY, blank=True, null=True, ) count_total_latino_african_american = models.DecimalField( custom=True, db_column="Count_total_latino_african_american__c", max_digits=18, decimal_places=0, verbose_name="Count - Total African American", sf_read_only=models.READ_ONLY, blank=True, null=True, ) count_total_latino_students = models.DecimalField( custom=True, db_column="Count_Total_Latino_Students__c", max_digits=18, decimal_places=0, verbose_name="Count - Total Latino Students", sf_read_only=models.READ_ONLY, blank=True, null=True, ) female = models.DecimalField( custom=True, max_digits=18, decimal_places=1, verbose_name="% Female", sf_read_only=models.READ_ONLY, blank=True, null=True, ) latino_african_american = models.DecimalField( custom=True, db_column="Latino_African_American__c", max_digits=18, decimal_places=1, verbose_name="% Latino/African American", sf_read_only=models.READ_ONLY, blank=True, null=True, ) current_academic_semester = models.CharField( custom=True, db_column="Current_academic_semester__c", max_length=1300, verbose_name="Current academic semester", sf_read_only=models.READ_ONLY, blank=True, null=True, ) in_current_semester = models.BooleanField( custom=True, db_column="In_current_semester__c", verbose_name="In current semester?", sf_read_only=models.READ_ONLY, ) class Meta(models.Model.Meta): db_table = "Class_Offering__c" verbose_name = "Class Offering" verbose_name_plural = "Class Offerings" # keyPrefix = 'a0h' def __str__(self): return "%s" % self.name class ClassEnrollment(models.Model): is_deleted = models.BooleanField( verbose_name="Deleted", sf_read_only=models.READ_ONLY, default=False ) name = models.CharField( max_length=80, verbose_name="Class Enrollment #", sf_read_only=models.READ_ONLY ) created_date = models.DateTimeField(sf_read_only=models.READ_ONLY) created_by = models.ForeignKey( "User", models.DO_NOTHING, related_name="classenrollment_createdby_set", sf_read_only=models.READ_ONLY, ) last_modified_date = models.DateTimeField(sf_read_only=models.READ_ONLY) last_modified_by = models.ForeignKey( "User", models.DO_NOTHING, related_name="classenrollment_lastmodifiedby_set", sf_read_only=models.READ_ONLY, ) system_modstamp = models.DateTimeField(sf_read_only=models.READ_ONLY) last_activity_date = models.DateField( sf_read_only=models.READ_ONLY, blank=True, null=True ) last_viewed_date = models.DateTimeField( sf_read_only=models.READ_ONLY, blank=True, null=True ) last_referenced_date = models.DateTimeField( sf_read_only=models.READ_ONLY, blank=True, null=True ) contact = models.ForeignKey( "Contact", models.DO_NOTHING, custom=True, related_name="classenrollment_contact_set", ) # Master Detail Relationship 0 role = models.CharField( custom=True, max_length=255, choices=[("Student", "Student"), ("TA", "TA"), ("Volunteer", "Volunteer")], blank=True, null=True, ) class_offering = models.ForeignKey( "ClassOffering", models.DO_NOTHING, db_column="Class_Offering__c", custom=True ) # Master Detail Relationship 1 status = models.CharField( custom=True, max_length=255, choices=STATUS_CHOICES, blank=True, null=True ) in_current_semester = models.BooleanField( custom=True, db_column="In_current_semester__c", verbose_name="In current semester?", sf_read_only=models.READ_ONLY, ) attended_family_orientation = models.BooleanField( custom=True, db_column="Attended_Family_Orientation__c", verbose_name="Attended Family Orientation", default=models.DEFAULTED_ON_CREATE, ) withdrew_application_detail = models.CharField( custom=True, db_column="Withdrew_Application_Detail__c", max_length=255, verbose_name="Withdrew-Application Detail", help_text='"Dropped in first 2 weeks" means that they showed up for class but decided to drop within the first 2 weeks.', choices=APP_WD_CHOICES, blank=True, null=True, ) contact_race = models.CharField( custom=True, db_column="Contact_Race__c", max_length=100, verbose_name="Contact - Race", help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", blank=True, null=True, ) contact_gender = models.CharField( custom=True, db_column="Contact_Gender__c", max_length=30, verbose_name="Contact - Gender", help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", blank=True, null=True, ) parent_contact = models.ForeignKey( "Contact", models.DO_NOTHING, db_column="Parent_Contact__c", custom=True, related_name="classenrollment_parentcontact_set", blank=True, null=True, ) attended_interview = models.BooleanField( custom=True, db_column="Attended_Interview__c", verbose_name="Attended Interview", default=models.DEFAULTED_ON_CREATE, help_text="Check if the student attended the default student admissions interview event. Note: Do not check this field if the student attended a makeup interview.", ) attended_makeup_interview = models.BooleanField( custom=True, db_column="Attended_Makeup_Interview__c", verbose_name="Attended Makeup Interview", default=models.DEFAULTED_ON_CREATE, help_text="Check if the student did not attend the default interview date, but attended a makeup session.", ) cultural_affiliation_or_nationality = models.CharField( custom=True, db_column="Cultural_Affiliation_or_Nationality__c", max_length=100, verbose_name="Cultural Affiliation or Nationality", help_text="(optional)", blank=True, null=True, ) sex_at_birth = models.CharField( custom=True, db_column="Sex_at_birth__c", max_length=255, verbose_name="What was your sex at birth?", help_text="(Check one)", choices=SEX_AT_BIRTH_CHOICES, blank=True, null=True, ) sexual_orientation = models.CharField( custom=True, db_column="Sexual_orientation__c", max_length=255, verbose_name="Sexual orientation or sexual identity", help_text="How do you describe your sexual orientation or sexual identity?", choices=SEXUAL_ORIENTATION_CHOICES, blank=True, null=True, ) other_sexual_orientation = models.CharField( custom=True, db_column="Other_sexual_orientation__c", max_length=30, verbose_name="Other sexual orientation", blank=True, null=True, ) household_type = models.CharField( custom=True, db_column="Household_type__c", max_length=255, verbose_name="Which best describes your family?", help_text="Which best describes your family? (Check one)\r\nFamily includes, but is not limited to the following—regardless of actual or perceived sexual orientation, gender identity, or marital status—a single person or a group of persons residing together.", choices=HOUSEHOLD_TYPE_CHOICES, blank=True, null=True, ) income_certification = models.CharField( custom=True, db_column="Income_Certification__c", max_length=4099, verbose_name="Income Certification", help_text="**current-within 2 months", choices=INCOME_CERT_CHOICES, blank=True, null=True, ) estimated_income = models.DecimalField( custom=True, db_column="Estimated_income__c", max_digits=18, decimal_places=2, verbose_name="Estimated income", help_text="Total estimated income for next 12 months for all adult members.", blank=True, null=True, ) family_size = models.CharField( custom=True, db_column="Family_size__c", max_length=255, verbose_name="Family size", help_text="Number of persons living in your family (including yourself):", choices=FAMILY_SIZE_CHOICES, blank=True, null=True, ) current_income_information = models.CharField( custom=True, db_column="Current_Income_Information__c", max_length=255, verbose_name="Current Income Information", choices=INCOME_LEVEL_CHOICES, blank=True, null=True, ) if_self_certified_please_explain = models.TextField( custom=True, db_column="If_self_certified_please_explain__c", verbose_name="If self-certified, please explain:", blank=True, null=True, ) contact_ethnicity = models.CharField( custom=True, db_column="Contact_Ethnicity__c", max_length=100, verbose_name="Contact - Ethnicity", help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", blank=True, null=True, ) notes = models.TextField(custom=True, blank=True, null=True) interview_date = models.DateTimeField( custom=True, db_column="Interview_Date__c", verbose_name="Interview Date", help_text="This is the interview date and time that the student signed up for. Empty means that the student did not sign up for an interview. Having an interview date does not mean that the student showed up for the interview, only that they RSVP'ed.", blank=True, null=True, ) returner = models.BooleanField( custom=True, verbose_name="Returner?", sf_read_only=models.READ_ONLY ) temp_returner = models.BooleanField( custom=True, db_column="Temp_Returner__c", verbose_name="Returner? (temp)", default=models.DEFAULTED_ON_CREATE, help_text="This is a temporary field that determines if a student is a returner based on their response to this question on the application. Once we complete migrating all of our past data into Salesforce, this field will be deleted.", ) origin_school = models.CharField( custom=True, db_column="Origin_School__c", max_length=1300, verbose_name="School attended by this student", sf_read_only=models.READ_ONLY, blank=True, null=True, ) parent_phone = models.CharField( custom=True, db_column="Parent_Phone__c", max_length=1300, verbose_name="Parent Phone", sf_read_only=models.READ_ONLY, blank=True, null=True, ) parent_email = models.CharField( custom=True, db_column="Parent_Email__c", max_length=1300, verbose_name="Parent Email", sf_read_only=models.READ_ONLY, blank=True, null=True, ) class Meta(models.Model.Meta): db_table = "Class_Enrollment__c" verbose_name = "Class Enrollment" verbose_name_plural = "Class Enrollments" # keyPrefix = 'a0i'
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,716
MissionBit/MB_Portal
refs/heads/master
/home/models/models.py
from time import strftime from secrets import token_urlsafe from django.db import models as mdls from django.contrib.auth.models import User as DjangoUser from django.contrib.auth.models import Group from django.contrib.postgres.fields import JSONField from django.db.models.signals import post_save from django.dispatch import receiver from home.choices import * from werkzeug import secure_filename from django_q.models import Task def get_name(self): return "%s %s" % (self.first_name, self.last_name) DjangoUser.add_to_class("__str__", get_name) Task.add_to_class("minutes", "minutes") def upload_to(instance, filename): return "/".join( [ secure_filename(type(instance).__name__), strftime("%Y/%m/%d"), instance.id or "0", token_urlsafe(8), secure_filename(filename), ] ) class UserProfile(mdls.Model): user = mdls.OneToOneField(DjangoUser, on_delete=mdls.CASCADE) change_pwd = mdls.BooleanField(default=False) date_of_birth = mdls.DateField(default="1901-01-01") salesforce_id = mdls.CharField(default="xxxxxx19010101", max_length=14) @receiver(post_save, sender=DjangoUser) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=DjangoUser) def save_user_profile(sender, instance, **kwargs): instance.userprofile.save() class Classroom(mdls.Model): course = mdls.CharField(max_length=255, choices=COURSE_CHOICES) members = mdls.ManyToManyField(DjangoUser, through="ClassroomMembership") attendance_summary = JSONField(default=None, null=True) forum_title = mdls.CharField(max_length=240, default=None, null=True) forum = mdls.URLField(default=None, null=True) def __str__(self): return "%s" % (self.course) class ClassroomMembership(mdls.Model): member = mdls.ForeignKey( DjangoUser, related_name="classroom_member", on_delete=mdls.CASCADE ) classroom = mdls.ForeignKey( Classroom, related_name="membership_classroom", on_delete=mdls.CASCADE ) membership_type = mdls.CharField( max_length=240, choices=CLASSROOM_MEMBERSHIP_CHOICES ) class Session(mdls.Model): title = mdls.CharField(max_length=240, default="No Title") description = mdls.TextField(max_length=2000, default="No Description Available") lesson_plan = mdls.FileField(default=None, upload_to=upload_to) lecture = mdls.FileField(default=None, upload_to=upload_to) video = mdls.URLField(default=None, null=True) activity = mdls.FileField(default=None, upload_to=upload_to) classroom = mdls.ForeignKey( Classroom, related_name="classroom_session", on_delete=mdls.CASCADE, default=None, ) date = mdls.DateField(default="1901-01-01") def __str__(self): return "%s - %s" % (self.classroom, self.date) class Resource(mdls.Model): title = mdls.TextField(max_length=240, default="No Title") description = mdls.TextField(max_length=2000) link = mdls.URLField(default=None, null=True) file = mdls.FileField(default=None, null=True, upload_to=upload_to) classroom = mdls.ForeignKey( Classroom, related_name="classroom_resource", on_delete=mdls.CASCADE ) session = mdls.ForeignKey( Session, related_name="session_resource", on_delete=mdls.CASCADE ) def __str__(self): return "%s - %s" % (self.title, self.session) class Attendance(mdls.Model): date = mdls.DateField(default="1901-01-01") student = mdls.ForeignKey( DjangoUser, related_name="student", on_delete=mdls.CASCADE ) presence = mdls.CharField(max_length=100, default="Unassigned") session = mdls.ForeignKey( Session, related_name="session", on_delete=mdls.CASCADE, default=None ) classroom = mdls.ForeignKey( Classroom, related_name="attendance_classroom", on_delete=mdls.CASCADE, default=None, ) notes = mdls.TextField(max_length=500, default="") class Announcement(mdls.Model): title = mdls.CharField(max_length=240, unique=True) announcement = mdls.TextField(max_length=2500) posted = mdls.DateTimeField(db_index=True, auto_now=True) recipient_groups = mdls.ManyToManyField(Group, related_name="user_groups") recipient_classrooms = mdls.ManyToManyField( Classroom, related_name="recipient_classroom" ) email_recipients = mdls.BooleanField(null=False, default=False) created_by = mdls.ForeignKey( DjangoUser, related_name="user", on_delete=mdls.CASCADE ) def __str__(self): return "%s, %s" % (self.title, self.posted) class AnnouncementDistribution(mdls.Model): announcement = mdls.ForeignKey( Announcement, related_name="announcement_distributed", on_delete=mdls.CASCADE ) user = mdls.ForeignKey( DjangoUser, related_name="announcement_user", on_delete=mdls.CASCADE ) dismissed = mdls.BooleanField(null=False, default=False) def __str__(self): return "%s - %s - dismissed: %s" % ( self.announcement, self.user, self.dismissed, ) class Esign(mdls.Model): name = mdls.CharField(max_length=240, unique=True) template = mdls.URLField() created_by = mdls.ForeignKey( DjangoUser, related_name="esign_creator_user", on_delete=mdls.CASCADE, default=False, ) def __str__(self): return self.name class Form(mdls.Model): name = mdls.CharField(max_length=240, unique=True) description = mdls.TextField(max_length=2500) form = mdls.FileField(upload_to=upload_to) esign = mdls.ForeignKey( Esign, related_name="esign_form", on_delete=mdls.CASCADE, null=True ) posted = mdls.DateTimeField(db_index=True, auto_now=True) recipient_groups = mdls.ManyToManyField(Group, related_name="form_user_groups") recipient_classrooms = mdls.ManyToManyField( Classroom, related_name="form_recipient_classroom" ) created_by = mdls.ForeignKey( DjangoUser, related_name="form_user", on_delete=mdls.CASCADE ) def __str__(self): return self.name class FormDistribution(mdls.Model): user = mdls.ForeignKey( DjangoUser, related_name="form_signer", on_delete=mdls.CASCADE ) form = mdls.ForeignKey( Form, related_name="form_to_be_signed", on_delete=mdls.CASCADE ) submitted = mdls.BooleanField(null=False, default=False) def __str__(self): return "%s, %s" % (self.user, self.form) class Notification(mdls.Model): user = mdls.ForeignKey( DjangoUser, related_name="notified_user", on_delete=mdls.CASCADE ) subject = mdls.CharField(max_length=240) notification = mdls.TextField(max_length=2500) email_recipients = mdls.BooleanField(null=False, default=False) form = mdls.ForeignKey( Form, related_name="notified_about_form", on_delete=mdls.CASCADE, null=True ) attendance = mdls.ForeignKey( Attendance, related_name="notified_about_attendance", on_delete=mdls.CASCADE, null=True, ) notified = mdls.DateTimeField(db_index=True, auto_now=True) created_by = mdls.ForeignKey( DjangoUser, related_name="notification_user", on_delete=mdls.CASCADE ) acknowledged = mdls.BooleanField(null=False, default=False) def __str__(self): return "%s %s" % (self.subject, self.created_by)
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,717
MissionBit/MB_Portal
refs/heads/master
/home/migrations/0008_remove_userprofile_in_classroom.py
# Generated by Django 2.2.3 on 2019-08-04 20:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [("home", "0007_auto_20190803_1930")] operations = [migrations.RemoveField(model_name="userprofile", name="in_classroom")]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,718
MissionBit/MB_Portal
refs/heads/master
/donor/views.py
from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.shortcuts import render @login_required def donor(request): if not request.user.groups.filter(name="donor").exists(): return HttpResponse("Unauthorized", status=401) return render(request, "donor.html")
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,719
MissionBit/MB_Portal
refs/heads/master
/home/migrations/0002_add_groups.py
from django.db import models, migrations from home.models.models import Group from django.conf import settings def add_groups(apps, schema_editor): """This migration guarantees that group IDs are generated correctly. See missionbit/settings.py for group ID settings""" Group.objects.get_or_create(name="student") Group.objects.get_or_create(name="staff") Group.objects.get_or_create(name="donor") Group.objects.get_or_create(name="teacher") Group.objects.get_or_create(name="volunteer") class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("auth", "0011_update_proxy_permissions"), ("home", "0001_initial"), ] operations = [migrations.RunPython(add_groups)]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,720
MissionBit/MB_Portal
refs/heads/master
/student/views.py
from django.shortcuts import render, redirect from django.contrib.auth.models import Group from home.decorators import group_required from home.models.models import ( Announcement, Form, Notification, Attendance, Classroom, Session, Resource, ) from attendance.views import ( get_average_attendance_from_list, get_date_from_template_returned_string, ) from staff.staff_views_helper import ( get_classroom_by_django_user, get_my_forms, get_my_announcements, ) import os from staff.staff_views_helper import ( mark_announcement_dismissed, mark_notification_acknowledged, ) from django.http import HttpResponse, Http404 from datetime import datetime @group_required("student") def student(request): if request.method == "POST": if request.POST.get("dismiss_announcement") == "true": mark_announcement_dismissed( Announcement.objects.get(id=request.POST.get("announcement")), request.user, ) return redirect("student") elif request.POST.get("acknowledge_notification") == "true": mark_notification_acknowledged( Notification.objects.get(id=request.POST.get("notification")) ) return redirect("student") announcements = get_my_announcements(request, "student") forms = get_my_forms(request, "student") notifications = Notification.objects.filter( user_id=request.user.id, acknowledged=False ) classroom = get_classroom_by_django_user(request.user) return render( request, "student.html", { "announcements": announcements, "forms": forms, "notifications": notifications, "classroom": classroom, }, ) @group_required("student") def attendance_student(request): classroom = get_classroom_by_django_user(request.user) attendance = Attendance.objects.filter( student_id=request.user.id, date__range=["2000-01-01", datetime.today().date()] ).order_by("date") attendance_percentage = get_average_attendance_from_list(attendance) * 100 return render( request, "attendance_student.html", { "attendance": attendance, "attendance_percentage": attendance_percentage, "classroom": classroom, }, ) @group_required("student") def my_class_student(request): classroom = get_classroom_by_django_user(request.user) sessions = Session.objects.filter( classroom_id=classroom.id, date__range=["2000-01-01", datetime.today().date()] ).order_by("date") return render( request, "my_class_student.html", {"classroom": classroom, "sessions": sessions} ) @group_required("student") def session_view_student(request): session = Session.objects.get( classroom_id=request.GET.get("classroom"), date=get_date_from_template_returned_string(request.GET.get("session_date")), ) resources = Resource.objects.filter(session_id=session.id) classroom = get_classroom_by_django_user(request.user) return render( request, "session_view_student.html", {"session": session, "resources": resources, "classroom": classroom}, )
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,721
MissionBit/MB_Portal
refs/heads/master
/home/views.py
from django.shortcuts import render, redirect, render_to_response from django.contrib.auth import logout from django.contrib.auth.models import Group from django.contrib.auth.models import User as DjangoUser from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, ContactRegisterForm, ChangePwdForm from django.contrib import messages from django.contrib.auth import update_session_auth_hash from home.models.salesforce import Contact, User @login_required def home(request): """ If the request's user already has a tag they are redirected to the correct page. When a user first logs in they don't have a tag and they are directed based on the group they belong to with approximately the highest permission level. redirects ref: https://realpython.com/django-redirects/#django-redirects-a-super-simple-example """ if request.user.userprofile.change_pwd: return redirect("change_pwd") else: if request.user.groups.all().count() == 0: return redirect("home-register_after_oauth") elif request.user.groups.filter(name="staff").exists(): return redirect("staff") elif request.user.groups.filter(name="teacher").exists(): return redirect("teacher") elif request.user.groups.filter(name="volunteer").exists(): return redirect("volunteer") elif request.user.groups.filter(name="donor").exists(): return redirect("donor") else: # request.user.groups.filter(name = 'student').exists() return redirect("student") @login_required def change_pwd(request): if request.method == "POST": form = ChangePwdForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, "Your password was successfully updated!") request.user.userprofile.change_pwd = False request.user.userprofile.save() return redirect("home-home") else: return render_to_response("home/change_pwd.html", {"form": form}) form = ChangePwdForm(request.user) return render(request, "home/change_pwd.html", {"form": form}) def logout_view(request): logout(request) return render(request, "home/logout.html") def login(request): return redirect("login") def landing_page(request): return render(request, "home/landing_page.html") @login_required def register_after_oauth(request): """ This method catches a user who logs in with no groups, this may happen in two scenarios. Scenario 1: A user logs in with gmail who has never logged in before. In that situation, the user is required to choose a group to complete registration, and is allowed to proceed. Scenario 2: A user logs in with gmail who has an account already, but has never logged in with gmail. In that situation, our API auto-generates a new user account, creating a duplicate entry. This method takes care of that by adding the new user to the old user's groups, and deleting the old user. """ if request.method == "POST": if request.POST.get("role") == "student": student_group = Group.objects.get(name="student") student_group.user_set.add(request.user) return redirect("home-home") else: # request.POST.get("role") == "volunteer": volunteer_group = Group.objects.get(name="volunteer") volunteer_group.user_set.add(request.user) return redirect("home-home") user_count = DjangoUser.objects.filter(email=request.user.email).count() if user_count >= 2: messages.error( request, "Error, multiple users with that email - please contact Mission Bit Staff", ) logout(request) return render(request, "home/logout.html") return render(request, "home/register_after_oauth.html") def register_as_student(request): if request.method == "POST": user_form = UserRegisterForm(request.POST) contact_form = ContactRegisterForm(request.POST) if user_form.is_valid() and contact_form.is_valid(): create_django_user(request, user_form, "student") create_contact(request, user_form, contact_form, "Student") messages.success( request, f"Student Account Successfully Created For {user_form.cleaned_data.get('first_name')}, please log in", ) return redirect("login") else: return render( request, "home/register.html", { "user_form": user_form, "contact_form": contact_form, "registration_type": "student", }, ) else: user_form = UserRegisterForm() contact_form = ContactRegisterForm() return render( request, "home/register.html", { "user_form": user_form, "contact_form": contact_form, "registration_type": "student", }, ) def register_as_volunteer(request): if request.method == "POST": user_form = UserRegisterForm(request.POST) contact_form = ContactRegisterForm(request.POST) if user_form.is_valid() and contact_form.is_valid(): create_django_user(request, user_form, "volunteer") create_contact(request, user_form, contact_form, "Volunteer") messages.success( request, f"Volunteer Account Successfully Created For {user_form.cleaned_data.get('first_name')}, please log in", ) return redirect("login") else: return render( request, "home/register.html", { "user_form": user_form, "contact_form": contact_form, "registration_type": "volunteer", }, ) else: user_form = UserRegisterForm() contact_form = ContactRegisterForm() return render( request, "home/register.html", { "user_form": user_form, "contact_form": contact_form, "registration_type": "volunteer", }, ) def register_as_donor(request): if request.method == "POST": user_form = UserRegisterForm(request.POST) contact_form = ContactRegisterForm(request.POST) if user_form.is_valid() and contact_form.is_valid(): create_django_user(request, user_form, "donor") create_contact(request, user_form, contact_form, "Donor") messages.success( request, f"Donor Account Successfully Created For {user_form.cleaned_data.get('first_name')}, please log in", ) return redirect("login") else: return render( request, "home/register.html", { "user_form": user_form, "contact_form": contact_form, "registration_type": "donor", }, ) else: user_form = UserRegisterForm() contact_form = ContactRegisterForm() return render( request, "home/register.html", { "user_form": user_form, "contact_form": contact_form, "registration_type": "donor", }, ) def create_django_user(request, form, group): new_user = DjangoUser.objects.create_user( username=form.cleaned_data.get("username"), email=form.cleaned_data.get("email"), first_name=form.cleaned_data.get("first_name"), last_name=form.cleaned_data.get("last_name"), password=form.cleaned_data.get("password1"), ) student_group = Group.objects.get(name=group) student_group.user_set.add(new_user) def create_contact(request, user_form, contact_form, title): Contact.objects.create( first_name=user_form.cleaned_data.get("first_name"), last_name=user_form.cleaned_data.get("last_name"), email=user_form.cleaned_data.get("email"), birthdate=contact_form.cleaned_data.get("birthdate"), title=title, owner=User.objects.filter(is_active=True).first(), race=contact_form.cleaned_data.get("race"), which_best_describes_your_ethnicity=contact_form.cleaned_data.get( "which_best_describes_your_ethnicity" ), gender=contact_form.cleaned_data.get("gender"), )
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,722
MissionBit/MB_Portal
refs/heads/master
/home/migrations/0010_auto_20190806_1917.py
# Generated by Django 2.2.3 on 2019-08-06 19:17 from django.db import migrations, models import home.models.models class Migration(migrations.Migration): dependencies = [("home", "0009_auto_20190804_2253")] operations = [ migrations.AlterField( model_name="form", name="form", field=models.FileField(upload_to=home.models.models.upload_to), ), migrations.AlterField( model_name="resource", name="file", field=models.FileField( default=None, null=True, upload_to=home.models.models.upload_to ), ), migrations.AlterField( model_name="session", name="activity", field=models.FileField( default=None, upload_to=home.models.models.upload_to ), ), migrations.AlterField( model_name="session", name="lecture", field=models.FileField( default=None, upload_to=home.models.models.upload_to ), ), migrations.AlterField( model_name="session", name="lesson_plan", field=models.FileField( default=None, upload_to=home.models.models.upload_to ), ), ]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,723
MissionBit/MB_Portal
refs/heads/master
/home/migrations/0007_auto_20190803_1930.py
# Generated by Django 2.2.3 on 2019-08-03 19:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("home", "0006_session_title")] operations = [ migrations.AddField( model_name="classroom", name="forum", field=models.URLField(default=None, null=True), ), migrations.AddField( model_name="classroom", name="forum_title", field=models.CharField(default=None, max_length=240, null=True), ), migrations.AlterField( model_name="resource", name="file", field=models.FileField(default=None, null=True, upload_to="documents/"), ), migrations.AlterField( model_name="session", name="activity", field=models.FileField(default=None, upload_to="documents/"), ), migrations.AlterField( model_name="session", name="lecture", field=models.FileField(default=None, upload_to="documents/"), ), migrations.AlterField( model_name="session", name="lesson_plan", field=models.FileField(default=None, upload_to="documents/"), ), ]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,724
MissionBit/MB_Portal
refs/heads/master
/donor/urls.py
from django.urls import path from . import views urlpatterns = [path("", views.donor, name="donor")]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,725
MissionBit/MB_Portal
refs/heads/master
/home/decorators.py
from django.core.exceptions import PermissionDenied def group_required(group): def user_in_group(func): def wrapper(request, *args, **kwargs): if request.user.groups.filter(name=group).exists(): return func(request, *args, **kwargs) else: raise PermissionDenied return wrapper return user_in_group def group_required_multiple(group_list): def user_in_group(func): def wrapper(request, *args, **kwargs): if request.user.groups.filter(name__in=group_list).exists(): return func(request, *args, **kwargs) else: raise PermissionDenied return wrapper return user_in_group
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,726
MissionBit/MB_Portal
refs/heads/master
/context_processors.py
from staff.staff_views_helper import get_classroom_by_django_user def user_groups(request): user_groups = set(request.user.groups.all().values_list("name", flat=True)) return {"user_groups": user_groups} def user_classroom(request): classroom = get_classroom_by_django_user(request.user) return {"classroom": classroom}
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,727
MissionBit/MB_Portal
refs/heads/master
/home/migrations/0001_initial.py
# Generated by Django 2.2.3 on 2019-07-30 02:59 from django.conf import settings import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion import salesforce.backend.operations import salesforce.fields class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("auth", "0011_update_proxy_permissions"), ] operations = [ migrations.CreateModel( name="Account", fields=[ ( "id", salesforce.fields.SalesforceAutoField( auto_created=True, db_column="Id", primary_key=True, serialize=False, verbose_name="ID", ), ), ( "is_deleted", salesforce.fields.BooleanField( default=False, verbose_name="Deleted" ), ), ( "name", salesforce.fields.CharField( max_length=255, verbose_name="Account Name" ), ), ( "type", salesforce.fields.CharField( blank=True, choices=[ ("School", "School"), ("Foundation", "Foundation"), ("Government", "Government"), ("Business", "Business"), ("Nonprofit", "Nonprofit"), ], max_length=40, null=True, verbose_name="Account Type", ), ), ("billing_street", salesforce.fields.TextField(blank=True, null=True)), ( "billing_city", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "billing_state", salesforce.fields.CharField( blank=True, max_length=80, null=True, verbose_name="Billing State/Province", ), ), ( "billing_postal_code", salesforce.fields.CharField( blank=True, max_length=20, null=True, verbose_name="Billing Zip/Postal Code", ), ), ( "billing_country", salesforce.fields.CharField(blank=True, max_length=80, null=True), ), ( "npe01_systemis_individual", salesforce.fields.BooleanField( db_column="npe01__SYSTEMIsIndividual__c", default=salesforce.backend.operations.DefaultedOnCreate(), help_text="Indicates whether or not this Account is special for Contacts (Household, One-to-One, Individual) vs a normal Account.", verbose_name="_SYSTEM: IsIndividual", ), ), ( "master_record", salesforce.fields.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name="account_masterrecord_set", to="home.Account", ), ), ( "parent", salesforce.fields.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name="account_parent_set", to="home.Account", ), ), ], options={ "verbose_name": "Account", "verbose_name_plural": "Accounts", "db_table": "Account", "abstract": False, "base_manager_name": "objects", }, ), migrations.CreateModel( name="Attendance", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("date", models.DateField(default="1901-01-01")), ("presence", models.CharField(default="Unassigned", max_length=100)), ("notes", models.TextField(default="", max_length=500)), ], ), migrations.CreateModel( name="Classroom", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "course", models.CharField( choices=[ ("Android Game Design", "Android Game Design"), ("Intro to Web Programming", "Intro to Web Programming"), ("Field Trips", "Field Trips"), ( "Intro to Game Design with Unity", "Intro to Game Design with Unity", ), ("Web Design 101", "Web Design 101"), ("Mobile App Dev with Ionic", "Mobile App Dev with Ionic"), ("MB Internship", "MB Internship"), ("Structured Study Program", "Structured Study Program"), ], max_length=255, ), ), ( "attendance_summary", django.contrib.postgres.fields.jsonb.JSONField( default=None, null=True ), ), ( "students", models.ManyToManyField( related_name="classroom_students", to=settings.AUTH_USER_MODEL ), ), ( "teacher", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="classroom_lead_teacher", to=settings.AUTH_USER_MODEL, ), ), ( "teacher_assistant", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="classroom_teacher_assistant", to=settings.AUTH_USER_MODEL, ), ), ( "volunteers", models.ManyToManyField( related_name="classroom_volunteers", to=settings.AUTH_USER_MODEL ), ), ], ), migrations.CreateModel( name="Esign", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(max_length=240, unique=True)), ("template", models.URLField()), ( "created_by", models.ForeignKey( default=False, on_delete=django.db.models.deletion.CASCADE, related_name="esign_creator_user", to=settings.AUTH_USER_MODEL, ), ), ], ), migrations.CreateModel( name="Form", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(max_length=240, unique=True)), ("description", models.TextField(max_length=2500)), ("form", models.FileField(upload_to="documents/")), ("posted", models.DateTimeField(auto_now=True, db_index=True)), ( "created_by", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="form_user", to=settings.AUTH_USER_MODEL, ), ), ( "esign", models.ForeignKey( null=True, on_delete=django.db.models.deletion.CASCADE, related_name="esign_form", to="home.Esign", ), ), ( "recipient_classrooms", models.ManyToManyField( related_name="form_recipient_classroom", to="home.Classroom" ), ), ( "recipient_groups", models.ManyToManyField( related_name="form_user_groups", to="auth.Group" ), ), ], ), migrations.CreateModel( name="Session", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "description", models.TextField( default="No Description Available", max_length=2000 ), ), ("lesson_plan", models.FileField(default=None, upload_to="")), ("lecture", models.FileField(default=None, upload_to="")), ("video", models.URLField(default=None, null=True)), ("activity", models.FileField(default=None, upload_to="")), ], ), migrations.CreateModel( name="User", fields=[ ( "id", salesforce.fields.SalesforceAutoField( auto_created=True, db_column="Id", primary_key=True, serialize=False, verbose_name="ID", ), ), ("username", salesforce.fields.CharField(max_length=80)), ("last_name", salesforce.fields.CharField(max_length=80)), ( "first_name", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "middle_name", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "suffix", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "name", salesforce.fields.CharField( max_length=121, verbose_name="Full Name" ), ), ( "company_name", salesforce.fields.CharField(blank=True, max_length=80, null=True), ), ( "division", salesforce.fields.CharField(blank=True, max_length=80, null=True), ), ( "department", salesforce.fields.CharField(blank=True, max_length=80, null=True), ), ( "title", salesforce.fields.CharField(blank=True, max_length=80, null=True), ), ("street", salesforce.fields.TextField(blank=True, null=True)), ( "city", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "state", salesforce.fields.CharField( blank=True, max_length=80, null=True, verbose_name="State/Province", ), ), ( "postal_code", salesforce.fields.CharField( blank=True, max_length=20, null=True, verbose_name="Zip/Postal Code", ), ), ( "country", salesforce.fields.CharField(blank=True, max_length=80, null=True), ), ( "is_active", salesforce.fields.BooleanField( default=salesforce.backend.operations.DefaultedOnCreate(), verbose_name="Active", ), ), ], options={ "verbose_name": "User", "verbose_name_plural": "Users", "db_table": "User", "abstract": False, "base_manager_name": "objects", }, ), migrations.CreateModel( name="UserProfile", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("change_pwd", models.BooleanField(default=False)), ("date_of_birth", models.DateField(default="1901-01-01")), ( "salesforce_id", models.CharField(default="xxxxxx19010101", max_length=14), ), ( "user", models.OneToOneField( on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, ), ), ], ), migrations.CreateModel( name="Notification", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("subject", models.CharField(max_length=240)), ("notification", models.TextField(max_length=2500)), ("email_recipients", models.BooleanField(default=False)), ("notified", models.DateTimeField(auto_now=True, db_index=True)), ("acknowledged", models.BooleanField(default=False)), ( "attendance", models.ForeignKey( null=True, on_delete=django.db.models.deletion.CASCADE, related_name="notified_about_attendance", to="home.Attendance", ), ), ( "created_by", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="notification_user", to=settings.AUTH_USER_MODEL, ), ), ( "form", models.ForeignKey( null=True, on_delete=django.db.models.deletion.CASCADE, related_name="notified_about_form", to="home.Form", ), ), ( "user", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="notified_user", to=settings.AUTH_USER_MODEL, ), ), ], ), migrations.CreateModel( name="Individual", fields=[ ( "id", salesforce.fields.SalesforceAutoField( auto_created=True, db_column="Id", primary_key=True, serialize=False, verbose_name="ID", ), ), ( "is_deleted", salesforce.fields.BooleanField( default=False, verbose_name="Deleted" ), ), ("last_name", salesforce.fields.CharField(max_length=80)), ( "first_name", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "salutation", salesforce.fields.CharField( blank=True, choices=[ ("Mr.", "Mr."), ("Ms.", "Ms."), ("Mrs.", "Mrs."), ("Dr.", "Dr."), ("Prof.", "Prof."), ], max_length=40, null=True, ), ), ( "middle_name", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "suffix", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ("name", salesforce.fields.CharField(max_length=121)), ( "owner", salesforce.fields.ForeignKey( on_delete=django.db.models.deletion.DO_NOTHING, related_name="individual_owner_set", to="home.User", ), ), ], options={ "verbose_name": "Individual", "verbose_name_plural": "Individuals", "db_table": "Individual", "abstract": False, "base_manager_name": "objects", }, ), migrations.CreateModel( name="FormDistribution", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("submitted", models.BooleanField(default=False)), ( "form", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="form_to_be_signed", to="home.Form", ), ), ( "user", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="form_signer", to=settings.AUTH_USER_MODEL, ), ), ], ), migrations.CreateModel( name="Contact", fields=[ ( "id", salesforce.fields.SalesforceAutoField( auto_created=True, db_column="Id", primary_key=True, serialize=False, verbose_name="ID", ), ), ( "is_deleted", salesforce.fields.BooleanField( default=False, verbose_name="Deleted" ), ), ("last_name", salesforce.fields.CharField(max_length=80)), ( "first_name", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "salutation", salesforce.fields.CharField( blank=True, choices=[ ("Mr.", "Mr."), ("Ms.", "Ms."), ("Mrs.", "Mrs."), ("Dr.", "Dr."), ("Prof.", "Prof."), ], max_length=40, null=True, ), ), ( "middle_name", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "suffix", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "name", salesforce.fields.CharField( max_length=121, verbose_name="Full Name" ), ), ("mailing_street", salesforce.fields.TextField(blank=True, null=True)), ( "mailing_city", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "mailing_state", salesforce.fields.CharField( blank=True, max_length=80, null=True, verbose_name="Mailing State/Province", ), ), ( "mailing_postal_code", salesforce.fields.CharField( blank=True, max_length=20, null=True, verbose_name="Mailing Zip/Postal Code", ), ), ( "mailing_country", salesforce.fields.CharField(blank=True, max_length=80, null=True), ), ( "mailing_state_code", salesforce.fields.CharField( blank=True, choices=[ ("AC", "Acre"), ("AG", "Agrigento"), ("AG", "Aguascalientes"), ("AL", "Alabama"), ("AL", "Alagoas"), ("AK", "Alaska"), ("AB", "Alberta"), ("AL", "Alessandria"), ("AP", "Amapá"), ("AM", "Amazonas"), ("AN", "Ancona"), ("AN", "Andaman and Nicobar Islands"), ("AP", "Andhra Pradesh"), ("34", "Anhui"), ("AO", "Aosta"), ("AR", "Arezzo"), ("AZ", "Arizona"), ("AR", "Arkansas"), ("AR", "Arunachal Pradesh"), ("AP", "Ascoli Piceno"), ("AS", "Assam"), ("AT", "Asti"), ("ACT", "Australian Capital Territory"), ("AV", "Avellino"), ("BA", "Bahia"), ("BC", "Baja California"), ("BS", "Baja California Sur"), ("BA", "Bari"), ("BT", "Barletta-Andria-Trani"), ("11", "Beijing"), ("BL", "Belluno"), ("BN", "Benevento"), ("BG", "Bergamo"), ("BI", "Biella"), ("BR", "Bihar"), ("BO", "Bologna"), ("BZ", "Bolzano"), ("BS", "Brescia"), ("BR", "Brindisi"), ("BC", "British Columbia"), ("CA", "Cagliari"), ("CA", "California"), ("CL", "Caltanissetta"), ("CM", "Campeche"), ("CB", "Campobasso"), ("CI", "Carbonia-Iglesias"), ("CW", "Carlow"), ("CE", "Caserta"), ("CT", "Catania"), ("CZ", "Catanzaro"), ("CN", "Cavan"), ("CE", "Ceará"), ("CH", "Chandigarh"), ("CT", "Chhattisgarh"), ("CS", "Chiapas"), ("CH", "Chieti"), ("CH", "Chihuahua"), ("71", "Chinese Taipei"), ("50", "Chongqing"), ("CE", "Clare"), ("CO", "Coahuila"), ("CL", "Colima"), ("CO", "Colorado"), ("CO", "Como"), ("CT", "Connecticut"), ("CO", "Cork"), ("CS", "Cosenza"), ("CR", "Cremona"), ("KR", "Crotone"), ("CN", "Cuneo"), ("DN", "Dadra and Nagar Haveli"), ("DD", "Daman and Diu"), ("DE", "Delaware"), ("DL", "Delhi"), ("DC", "District of Columbia"), ("DF", "Distrito Federal"), ("DL", "Donegal"), ("D", "Dublin"), ("DG", "Durango"), ("EN", "Enna"), ("ES", "Espírito Santo"), ("DF", "Federal District"), ("FM", "Fermo"), ("FE", "Ferrara"), ("FI", "Florence"), ("FL", "Florida"), ("FG", "Foggia"), ("FC", "Forlì-Cesena"), ("FR", "Frosinone"), ("35", "Fujian"), ("G", "Galway"), ("62", "Gansu"), ("GE", "Genoa"), ("GA", "Georgia"), ("GA", "Goa"), ("GO", "Goiás"), ("GO", "Gorizia"), ("GR", "Grosseto"), ("GT", "Guanajuato"), ("44", "Guangdong"), ("45", "Guangxi"), ("GR", "Guerrero"), ("52", "Guizhou"), ("GJ", "Gujarat"), ("46", "Hainan"), ("HR", "Haryana"), ("HI", "Hawaii"), ("13", "Hebei"), ("23", "Heilongjiang"), ("41", "Henan"), ("HG", "Hidalgo"), ("HP", "Himachal Pradesh"), ("91", "Hong Kong"), ("42", "Hubei"), ("43", "Hunan"), ("ID", "Idaho"), ("IL", "Illinois"), ("IM", "Imperia"), ("IN", "Indiana"), ("IA", "Iowa"), ("IS", "Isernia"), ("JA", "Jalisco"), ("JK", "Jammu and Kashmir"), ("JH", "Jharkhand"), ("32", "Jiangsu"), ("36", "Jiangxi"), ("22", "Jilin"), ("KS", "Kansas"), ("KA", "Karnataka"), ("KY", "Kentucky"), ("KL", "Kerala"), ("KY", "Kerry"), ("KE", "Kildare"), ("KK", "Kilkenny"), ("AQ", "L'Aquila"), ("LD", "Lakshadweep"), ("LS", "Laois"), ("SP", "La Spezia"), ("LT", "Latina"), ("LE", "Lecce"), ("LC", "Lecco"), ("LM", "Leitrim"), ("21", "Liaoning"), ("LK", "Limerick"), ("LI", "Livorno"), ("LO", "Lodi"), ("LD", "Longford"), ("LA", "Louisiana"), ("LH", "Louth"), ("LU", "Lucca"), ("92", "Macao"), ("MC", "Macerata"), ("MP", "Madhya Pradesh"), ("MH", "Maharashtra"), ("ME", "Maine"), ("MN", "Manipur"), ("MB", "Manitoba"), ("MN", "Mantua"), ("MA", "Maranhão"), ("MD", "Maryland"), ("MS", "Massa and Carrara"), ("MA", "Massachusetts"), ("MT", "Matera"), ("MT", "Mato Grosso"), ("MS", "Mato Grosso do Sul"), ("MO", "Mayo"), ("MH", "Meath"), ("VS", "Medio Campidano"), ("ML", "Meghalaya"), ("ME", "Messina"), ("ME", "Mexico State"), ("MI", "Michigan"), ("MI", "Michoacán"), ("MI", "Milan"), ("MG", "Minas Gerais"), ("MN", "Minnesota"), ("MS", "Mississippi"), ("MO", "Missouri"), ("MZ", "Mizoram"), ("MO", "Modena"), ("MN", "Monaghan"), ("MT", "Montana"), ("MB", "Monza and Brianza"), ("MO", "Morelos"), ("NL", "Nagaland"), ("NA", "Naples"), ("NA", "Nayarit"), ("NE", "Nebraska"), ("15", "Nei Mongol"), ("NV", "Nevada"), ("NB", "New Brunswick"), ("NL", "Newfoundland and Labrador"), ("NH", "New Hampshire"), ("NJ", "New Jersey"), ("NM", "New Mexico"), ("NSW", "New South Wales"), ("NY", "New York"), ("64", "Ningxia"), ("NC", "North Carolina"), ("ND", "North Dakota"), ("NT", "Northern Territory"), ("NT", "Northwest Territories"), ("NO", "Novara"), ("NS", "Nova Scotia"), ("NL", "Nuevo León"), ("NU", "Nunavut"), ("NU", "Nuoro"), ("OA", "Oaxaca"), ("OR", "Odisha"), ("OY", "Offaly"), ("OG", "Ogliastra"), ("OH", "Ohio"), ("OK", "Oklahoma"), ("OT", "Olbia-Tempio"), ("ON", "Ontario"), ("OR", "Oregon"), ("OR", "Oristano"), ("PD", "Padua"), ("PA", "Palermo"), ("PA", "Pará"), ("PB", "Paraíba"), ("PR", "Paraná"), ("PR", "Parma"), ("PV", "Pavia"), ("PA", "Pennsylvania"), ("PE", "Pernambuco"), ("PG", "Perugia"), ("PU", "Pesaro and Urbino"), ("PE", "Pescara"), ("PC", "Piacenza"), ("PI", "Piauí"), ("PI", "Pisa"), ("PT", "Pistoia"), ("PN", "Pordenone"), ("PZ", "Potenza"), ("PO", "Prato"), ("PE", "Prince Edward Island"), ("PY", "Puducherry"), ("PB", "Puebla"), ("PB", "Punjab"), ("63", "Qinghai"), ("QC", "Quebec"), ("QLD", "Queensland"), ("QE", "Querétaro"), ("QR", "Quintana Roo"), ("RG", "Ragusa"), ("RJ", "Rajasthan"), ("RA", "Ravenna"), ("RC", "Reggio Calabria"), ("RE", "Reggio Emilia"), ("RI", "Rhode Island"), ("RI", "Rieti"), ("RN", "Rimini"), ("RJ", "Rio de Janeiro"), ("RN", "Rio Grande do Norte"), ("RS", "Rio Grande do Sul"), ("RM", "Rome"), ("RO", "Rondônia"), ("RR", "Roraima"), ("RN", "Roscommon"), ("RO", "Rovigo"), ("SA", "Salerno"), ("SL", "San Luis Potosí"), ("SC", "Santa Catarina"), ("SP", "São Paulo"), ("SK", "Saskatchewan"), ("SS", "Sassari"), ("SV", "Savona"), ("SE", "Sergipe"), ("61", "Shaanxi"), ("37", "Shandong"), ("31", "Shanghai"), ("14", "Shanxi"), ("51", "Sichuan"), ("SI", "Siena"), ("SK", "Sikkim"), ("SI", "Sinaloa"), ("SO", "Sligo"), ("SO", "Sondrio"), ("SO", "Sonora"), ("SA", "South Australia"), ("SC", "South Carolina"), ("SD", "South Dakota"), ("SR", "Syracuse"), ("TB", "Tabasco"), ("TM", "Tamaulipas"), ("TN", "Tamil Nadu"), ("TA", "Taranto"), ("TAS", "Tasmania"), ("TN", "Tennessee"), ("TE", "Teramo"), ("TR", "Terni"), ("TX", "Texas"), ("12", "Tianjin"), ("TA", "Tipperary"), ("TL", "Tlaxcala"), ("TO", "Tocantins"), ("TP", "Trapani"), ("TN", "Trento"), ("TV", "Treviso"), ("TS", "Trieste"), ("TR", "Tripura"), ("TO", "Turin"), ("UD", "Udine"), ("UT", "Utah"), ("UT", "Uttarakhand"), ("UP", "Uttar Pradesh"), ("VA", "Varese"), ("VE", "Venice"), ("VE", "Veracruz"), ("VB", "Verbano-Cusio-Ossola"), ("VC", "Vercelli"), ("VT", "Vermont"), ("VR", "Verona"), ("VV", "Vibo Valentia"), ("VI", "Vicenza"), ("VIC", "Victoria"), ("VA", "Virginia"), ("VT", "Viterbo"), ("WA", "Washington"), ("WD", "Waterford"), ("WB", "West Bengal"), ("WA", "Western Australia"), ("WH", "Westmeath"), ("WV", "West Virginia"), ("WX", "Wexford"), ("WW", "Wicklow"), ("WI", "Wisconsin"), ("WY", "Wyoming"), ("65", "Xinjiang"), ("54", "Xizang"), ("YU", "Yucatán"), ("YT", "Yukon Territories"), ("53", "Yunnan"), ("ZA", "Zacatecas"), ("33", "Zhejiang"), ], max_length=10, null=True, verbose_name="Mailing State/Province Code", ), ), ( "mailing_country_code", salesforce.fields.CharField( blank=True, choices=[ ("AC", "Acre"), ("AG", "Agrigento"), ("AG", "Aguascalientes"), ("AL", "Alabama"), ("AL", "Alagoas"), ("AK", "Alaska"), ("AB", "Alberta"), ("AL", "Alessandria"), ("AP", "Amapá"), ("AM", "Amazonas"), ("AN", "Ancona"), ("AN", "Andaman and Nicobar Islands"), ("AP", "Andhra Pradesh"), ("34", "Anhui"), ("AO", "Aosta"), ("AR", "Arezzo"), ("AZ", "Arizona"), ("AR", "Arkansas"), ("AR", "Arunachal Pradesh"), ("AP", "Ascoli Piceno"), ("AS", "Assam"), ("AT", "Asti"), ("ACT", "Australian Capital Territory"), ("AV", "Avellino"), ("BA", "Bahia"), ("BC", "Baja California"), ("BS", "Baja California Sur"), ("BA", "Bari"), ("BT", "Barletta-Andria-Trani"), ("11", "Beijing"), ("BL", "Belluno"), ("BN", "Benevento"), ("BG", "Bergamo"), ("BI", "Biella"), ("BR", "Bihar"), ("BO", "Bologna"), ("BZ", "Bolzano"), ("BS", "Brescia"), ("BR", "Brindisi"), ("BC", "British Columbia"), ("CA", "Cagliari"), ("CA", "California"), ("CL", "Caltanissetta"), ("CM", "Campeche"), ("CB", "Campobasso"), ("CI", "Carbonia-Iglesias"), ("CW", "Carlow"), ("CE", "Caserta"), ("CT", "Catania"), ("CZ", "Catanzaro"), ("CN", "Cavan"), ("CE", "Ceará"), ("CH", "Chandigarh"), ("CT", "Chhattisgarh"), ("CS", "Chiapas"), ("CH", "Chieti"), ("CH", "Chihuahua"), ("71", "Chinese Taipei"), ("50", "Chongqing"), ("CE", "Clare"), ("CO", "Coahuila"), ("CL", "Colima"), ("CO", "Colorado"), ("CO", "Como"), ("CT", "Connecticut"), ("CO", "Cork"), ("CS", "Cosenza"), ("CR", "Cremona"), ("KR", "Crotone"), ("CN", "Cuneo"), ("DN", "Dadra and Nagar Haveli"), ("DD", "Daman and Diu"), ("DE", "Delaware"), ("DL", "Delhi"), ("DC", "District of Columbia"), ("DF", "Distrito Federal"), ("DL", "Donegal"), ("D", "Dublin"), ("DG", "Durango"), ("EN", "Enna"), ("ES", "Espírito Santo"), ("DF", "Federal District"), ("FM", "Fermo"), ("FE", "Ferrara"), ("FI", "Florence"), ("FL", "Florida"), ("FG", "Foggia"), ("FC", "Forlì-Cesena"), ("FR", "Frosinone"), ("35", "Fujian"), ("G", "Galway"), ("62", "Gansu"), ("GE", "Genoa"), ("GA", "Georgia"), ("GA", "Goa"), ("GO", "Goiás"), ("GO", "Gorizia"), ("GR", "Grosseto"), ("GT", "Guanajuato"), ("44", "Guangdong"), ("45", "Guangxi"), ("GR", "Guerrero"), ("52", "Guizhou"), ("GJ", "Gujarat"), ("46", "Hainan"), ("HR", "Haryana"), ("HI", "Hawaii"), ("13", "Hebei"), ("23", "Heilongjiang"), ("41", "Henan"), ("HG", "Hidalgo"), ("HP", "Himachal Pradesh"), ("91", "Hong Kong"), ("42", "Hubei"), ("43", "Hunan"), ("ID", "Idaho"), ("IL", "Illinois"), ("IM", "Imperia"), ("IN", "Indiana"), ("IA", "Iowa"), ("IS", "Isernia"), ("JA", "Jalisco"), ("JK", "Jammu and Kashmir"), ("JH", "Jharkhand"), ("32", "Jiangsu"), ("36", "Jiangxi"), ("22", "Jilin"), ("KS", "Kansas"), ("KA", "Karnataka"), ("KY", "Kentucky"), ("KL", "Kerala"), ("KY", "Kerry"), ("KE", "Kildare"), ("KK", "Kilkenny"), ("AQ", "L'Aquila"), ("LD", "Lakshadweep"), ("LS", "Laois"), ("SP", "La Spezia"), ("LT", "Latina"), ("LE", "Lecce"), ("LC", "Lecco"), ("LM", "Leitrim"), ("21", "Liaoning"), ("LK", "Limerick"), ("LI", "Livorno"), ("LO", "Lodi"), ("LD", "Longford"), ("LA", "Louisiana"), ("LH", "Louth"), ("LU", "Lucca"), ("92", "Macao"), ("MC", "Macerata"), ("MP", "Madhya Pradesh"), ("MH", "Maharashtra"), ("ME", "Maine"), ("MN", "Manipur"), ("MB", "Manitoba"), ("MN", "Mantua"), ("MA", "Maranhão"), ("MD", "Maryland"), ("MS", "Massa and Carrara"), ("MA", "Massachusetts"), ("MT", "Matera"), ("MT", "Mato Grosso"), ("MS", "Mato Grosso do Sul"), ("MO", "Mayo"), ("MH", "Meath"), ("VS", "Medio Campidano"), ("ML", "Meghalaya"), ("ME", "Messina"), ("ME", "Mexico State"), ("MI", "Michigan"), ("MI", "Michoacán"), ("MI", "Milan"), ("MG", "Minas Gerais"), ("MN", "Minnesota"), ("MS", "Mississippi"), ("MO", "Missouri"), ("MZ", "Mizoram"), ("MO", "Modena"), ("MN", "Monaghan"), ("MT", "Montana"), ("MB", "Monza and Brianza"), ("MO", "Morelos"), ("NL", "Nagaland"), ("NA", "Naples"), ("NA", "Nayarit"), ("NE", "Nebraska"), ("15", "Nei Mongol"), ("NV", "Nevada"), ("NB", "New Brunswick"), ("NL", "Newfoundland and Labrador"), ("NH", "New Hampshire"), ("NJ", "New Jersey"), ("NM", "New Mexico"), ("NSW", "New South Wales"), ("NY", "New York"), ("64", "Ningxia"), ("NC", "North Carolina"), ("ND", "North Dakota"), ("NT", "Northern Territory"), ("NT", "Northwest Territories"), ("NO", "Novara"), ("NS", "Nova Scotia"), ("NL", "Nuevo León"), ("NU", "Nunavut"), ("NU", "Nuoro"), ("OA", "Oaxaca"), ("OR", "Odisha"), ("OY", "Offaly"), ("OG", "Ogliastra"), ("OH", "Ohio"), ("OK", "Oklahoma"), ("OT", "Olbia-Tempio"), ("ON", "Ontario"), ("OR", "Oregon"), ("OR", "Oristano"), ("PD", "Padua"), ("PA", "Palermo"), ("PA", "Pará"), ("PB", "Paraíba"), ("PR", "Paraná"), ("PR", "Parma"), ("PV", "Pavia"), ("PA", "Pennsylvania"), ("PE", "Pernambuco"), ("PG", "Perugia"), ("PU", "Pesaro and Urbino"), ("PE", "Pescara"), ("PC", "Piacenza"), ("PI", "Piauí"), ("PI", "Pisa"), ("PT", "Pistoia"), ("PN", "Pordenone"), ("PZ", "Potenza"), ("PO", "Prato"), ("PE", "Prince Edward Island"), ("PY", "Puducherry"), ("PB", "Puebla"), ("PB", "Punjab"), ("63", "Qinghai"), ("QC", "Quebec"), ("QLD", "Queensland"), ("QE", "Querétaro"), ("QR", "Quintana Roo"), ("RG", "Ragusa"), ("RJ", "Rajasthan"), ("RA", "Ravenna"), ("RC", "Reggio Calabria"), ("RE", "Reggio Emilia"), ("RI", "Rhode Island"), ("RI", "Rieti"), ("RN", "Rimini"), ("RJ", "Rio de Janeiro"), ("RN", "Rio Grande do Norte"), ("RS", "Rio Grande do Sul"), ("RM", "Rome"), ("RO", "Rondônia"), ("RR", "Roraima"), ("RN", "Roscommon"), ("RO", "Rovigo"), ("SA", "Salerno"), ("SL", "San Luis Potosí"), ("SC", "Santa Catarina"), ("SP", "São Paulo"), ("SK", "Saskatchewan"), ("SS", "Sassari"), ("SV", "Savona"), ("SE", "Sergipe"), ("61", "Shaanxi"), ("37", "Shandong"), ("31", "Shanghai"), ("14", "Shanxi"), ("51", "Sichuan"), ("SI", "Siena"), ("SK", "Sikkim"), ("SI", "Sinaloa"), ("SO", "Sligo"), ("SO", "Sondrio"), ("SO", "Sonora"), ("SA", "South Australia"), ("SC", "South Carolina"), ("SD", "South Dakota"), ("SR", "Syracuse"), ("TB", "Tabasco"), ("TM", "Tamaulipas"), ("TN", "Tamil Nadu"), ("TA", "Taranto"), ("TAS", "Tasmania"), ("TN", "Tennessee"), ("TE", "Teramo"), ("TR", "Terni"), ("TX", "Texas"), ("12", "Tianjin"), ("TA", "Tipperary"), ("TL", "Tlaxcala"), ("TO", "Tocantins"), ("TP", "Trapani"), ("TN", "Trento"), ("TV", "Treviso"), ("TS", "Trieste"), ("TR", "Tripura"), ("TO", "Turin"), ("UD", "Udine"), ("UT", "Utah"), ("UT", "Uttarakhand"), ("UP", "Uttar Pradesh"), ("VA", "Varese"), ("VE", "Venice"), ("VE", "Veracruz"), ("VB", "Verbano-Cusio-Ossola"), ("VC", "Vercelli"), ("VT", "Vermont"), ("VR", "Verona"), ("VV", "Vibo Valentia"), ("VI", "Vicenza"), ("VIC", "Victoria"), ("VA", "Virginia"), ("VT", "Viterbo"), ("WA", "Washington"), ("WD", "Waterford"), ("WB", "West Bengal"), ("WA", "Western Australia"), ("WH", "Westmeath"), ("WV", "West Virginia"), ("WX", "Wexford"), ("WW", "Wicklow"), ("WI", "Wisconsin"), ("WY", "Wyoming"), ("65", "Xinjiang"), ("54", "Xizang"), ("YU", "Yucatán"), ("YT", "Yukon Territories"), ("53", "Yunnan"), ("ZA", "Zacatecas"), ("33", "Zhejiang"), ], default=salesforce.backend.operations.DefaultedOnCreate(), max_length=10, null=True, ), ), ( "mobile_phone", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "home_phone", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "other_phone", salesforce.fields.CharField(blank=True, max_length=40, null=True), ), ( "email", salesforce.fields.EmailField(blank=True, max_length=254, null=True), ), ( "title", salesforce.fields.CharField(blank=True, max_length=128, null=True), ), ( "department", salesforce.fields.CharField(blank=True, max_length=80, null=True), ), ("birthdate", salesforce.fields.DateField(blank=True, null=True)), ("created_date", salesforce.fields.DateTimeField()), ("last_modified_date", salesforce.fields.DateTimeField()), ("system_modstamp", salesforce.fields.DateTimeField()), ( "last_activity_date", salesforce.fields.DateField( blank=True, null=True, verbose_name="Last Activity" ), ), ( "last_curequest_date", salesforce.fields.DateTimeField( blank=True, db_column="LastCURequestDate", null=True, verbose_name="Last Stay-in-Touch Request Date", ), ), ( "last_cuupdate_date", salesforce.fields.DateTimeField( blank=True, db_column="LastCUUpdateDate", null=True, verbose_name="Last Stay-in-Touch Save Date", ), ), ( "last_viewed_date", salesforce.fields.DateTimeField(blank=True, null=True), ), ( "last_referenced_date", salesforce.fields.DateTimeField(blank=True, null=True), ), ( "email_bounced_reason", salesforce.fields.CharField(blank=True, max_length=255, null=True), ), ( "email_bounced_date", salesforce.fields.DateTimeField(blank=True, null=True), ), ("is_email_bounced", salesforce.fields.BooleanField(default=False)), ( "photo_url", salesforce.fields.URLField( blank=True, null=True, verbose_name="Photo URL" ), ), ( "jigsaw_contact_id", salesforce.fields.CharField( blank=True, max_length=20, null=True, verbose_name="Jigsaw Contact ID", ), ), ( "race", salesforce.fields.CharField( blank=True, choices=[ ( "American Indian/Alaskan Native", "American Indian/Alaskan Native", ), ("Asian", "Asian"), ("Black/African American", "Black/African American"), ( "Native Hawaiian/Other Pacific Islander", "Native Hawaiian/Other Pacific Islander", ), ("White", "White"), ( "American Indian/Alaskan Native AND Black/African American", "American Indian/Alaskan Native AND Black/African American", ), ( "American Indian/Alaskan Native AND White", "American Indian/Alaskan Native AND White", ), ("Asian AND White", "Asian AND White"), ( "Black/African American AND White", "Black/African American AND White", ), ("Other/Multiracial", "Other/Multiracial"), ("Politely Decline", "Politely Decline"), ], max_length=255, null=True, verbose_name="Which best describes your race?", ), ), ( "gender", salesforce.fields.CharField( blank=True, choices=[ ("Female", "Female"), ("Male", "Male"), ( "Genderqueer/Gender Non-binary", "Genderqueer/Gender Non-binary", ), ("Trans Female", "Trans Female"), ("Trans Male", "Trans Male"), ("Other", "Not Listed"), ], max_length=255, null=True, ), ), ( "which_best_describes_your_ethnicity", salesforce.fields.CharField( blank=True, choices=[ ("Hispanic/Latinx", "Hispanic/Latinx"), ("Not Hispanic/Latinx", "Not Hispanic/Latinx"), ("Politely Decline", "Politely Decline"), ], db_column="Which_best_describes_your_ethnicity__c", max_length=255, null=True, verbose_name="Which best describes your ethnicity?", ), ), ( "expected_graduation_year", salesforce.fields.CharField( blank=True, db_column="Expected_graduation_year__c", help_text="Enter the year this contact is expected to graduate. For example, 2020", max_length=4, null=True, verbose_name="Expected graduation year", ), ), ( "current_grade_level", salesforce.fields.CharField( blank=True, db_column="Current_grade_level__c", max_length=1300, null=True, verbose_name="Current grade level", ), ), ( "volunteer_area_s_of_interest", salesforce.fields.CharField( blank=True, choices=[ ("Classroom", "Classroom"), ("Event", "Event"), ("Other", "Other"), ], db_column="Volunteer_area_s_of_interest__c", max_length=4099, null=True, verbose_name="Volunteer area(s) of interest", ), ), ( "enrollments_this_semester_applied", salesforce.fields.DecimalField( blank=True, db_column="enrollments_this_semester_Applied__c", decimal_places=0, help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", max_digits=2, null=True, verbose_name="# enrollments this semester - Applied", ), ), ( "enrollments_this_semester_waitlisted", salesforce.fields.DecimalField( blank=True, db_column="enrollments_this_semester_Waitlisted__c", decimal_places=0, help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", max_digits=2, null=True, verbose_name="# enrollments this semester - Waitlisted", ), ), ( "enrollments_this_semester_rejected", salesforce.fields.DecimalField( blank=True, db_column="enrollments_this_semester_Rejected__c", decimal_places=0, help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", max_digits=2, null=True, verbose_name="# enrollments this semester - Rejected", ), ), ( "enrollments_this_semester_drop_out", salesforce.fields.DecimalField( blank=True, db_column="enrollments_this_semester_Drop_out__c", decimal_places=0, help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", max_digits=2, null=True, verbose_name="# enrollments this semester - Drop out", ), ), ( "race_other", salesforce.fields.CharField( blank=True, db_column="Race_Other__c", max_length=100, null=True, verbose_name="Which best describes your race? (Other)", ), ), ( "gender_other", salesforce.fields.CharField( blank=True, db_column="Gender_Other__c", max_length=50, null=True, verbose_name="Gender (Other)", ), ), ( "parent_guardian_first_name", salesforce.fields.CharField( blank=True, db_column="Parent_Guardian_first_name__c", max_length=100, null=True, verbose_name="Parent/Guardian first name", ), ), ( "parent_guardian_last_name", salesforce.fields.CharField( blank=True, db_column="Parent_Guardian_last_name__c", max_length=100, null=True, verbose_name="Parent/Guardian last name", ), ), ( "parent_guardian_phone", salesforce.fields.CharField( blank=True, db_column="Parent_Guardian_phone__c", max_length=40, null=True, verbose_name="Parent/Guardian phone", ), ), ( "parent_guardian_email", salesforce.fields.EmailField( blank=True, db_column="Parent_Guardian_email__c", max_length=254, null=True, verbose_name="Parent/Guardian email", ), ), ( "dm_current_grade", salesforce.fields.CharField( blank=True, choices=[ ("Graduating 8th", "Graduating 8th"), ("Freshman, 9th", "Freshman, 9th"), ("Sophomore, 10th", "Sophomore, 10th"), ("Junior, 11th", "Junior, 11th"), ("Senior, 12th", "Senior, 12th"), ], db_column="DM_Current_grade__c", help_text="Need this for data migration to calculate Expected Graduation Year? If not, delete this field.", max_length=255, null=True, verbose_name="DM - Current grade", ), ), ( "client_id", salesforce.fields.CharField( blank=True, db_column="Client_ID__c", help_text='3 first letters of first name, 3 first letters of last name, and birthdate "AAABBB00000000" (Only used for students and parents). This field is auto-populated by FormAssembly.', max_length=14, null=True, verbose_name="Client ID", ), ), ( "account", salesforce.fields.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name="contact_account_set", to="home.Account", ), ), ( "created_by", salesforce.fields.ForeignKey( on_delete=django.db.models.deletion.DO_NOTHING, related_name="contact_createdby_set", to="home.User", ), ), ( "individual", salesforce.fields.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to="home.Individual", ), ), ( "last_modified_by", salesforce.fields.ForeignKey( on_delete=django.db.models.deletion.DO_NOTHING, related_name="contact_lastmodifiedby_set", to="home.User", ), ), ( "master_record", salesforce.fields.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name="contact_masterrecord_set", to="home.Contact", ), ), ( "npsp_primary_affiliation", salesforce.fields.ForeignKey( blank=True, db_column="npsp__Primary_Affiliation__c", null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name="contact_npspprimaryaffiliation_set", to="home.Account", ), ), ( "owner", salesforce.fields.ForeignKey( blank=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name="contact_owner_set", to="home.User", ), ), ], options={ "verbose_name": "Contact", "verbose_name_plural": "Contacts", "db_table": "Contact", "abstract": False, "base_manager_name": "objects", }, ), migrations.CreateModel( name="ClassOffering", fields=[ ( "id", salesforce.fields.SalesforceAutoField( auto_created=True, db_column="Id", primary_key=True, serialize=False, verbose_name="ID", ), ), ( "is_deleted", salesforce.fields.BooleanField( default=False, verbose_name="Deleted" ), ), ( "name", salesforce.fields.CharField( blank=True, default=salesforce.backend.operations.DefaultedOnCreate(), max_length=80, null=True, verbose_name="Class Offering Name", ), ), ("created_date", salesforce.fields.DateTimeField()), ("last_modified_date", salesforce.fields.DateTimeField()), ("system_modstamp", salesforce.fields.DateTimeField()), ( "last_viewed_date", salesforce.fields.DateTimeField(blank=True, null=True), ), ( "last_referenced_date", salesforce.fields.DateTimeField(blank=True, null=True), ), ( "start_date", salesforce.fields.DateField( blank=True, db_column="Start_Date__c", null=True, verbose_name="Start Date", ), ), ( "end_date", salesforce.fields.DateField( blank=True, db_column="End_Date__c", null=True, verbose_name="End Date", ), ), ("description", salesforce.fields.TextField(blank=True, null=True)), ( "course", salesforce.fields.CharField( blank=True, choices=[ ("Android Game Design", "Android Game Design"), ("Intro to Web Programming", "Intro to Web Programming"), ("Field Trips", "Field Trips"), ( "Intro to Game Design with Unity", "Intro to Game Design with Unity", ), ("Web Design 101", "Web Design 101"), ("Mobile App Dev with Ionic", "Mobile App Dev with Ionic"), ("MB Internship", "MB Internship"), ("Structured Study Program", "Structured Study Program"), ], max_length=255, null=True, ), ), ( "academic_semester", salesforce.fields.CharField( blank=True, db_column="Academic_semester__c", max_length=1300, null=True, verbose_name="Academic semester", ), ), ( "meeting_days", salesforce.fields.CharField( blank=True, choices=[("M/W", "M/W"), ("T/R", "T/R"), ("M-F", "M-F")], db_column="Meeting_Days__c", max_length=255, null=True, verbose_name="Meeting Days", ), ), ( "count_total_female_students", salesforce.fields.DecimalField( blank=True, db_column="Count_total_female_students__c", decimal_places=0, max_digits=18, null=True, verbose_name="Count - Total Female Students", ), ), ( "count_total_latino_african_american", salesforce.fields.DecimalField( blank=True, db_column="Count_total_latino_african_american__c", decimal_places=0, max_digits=18, null=True, verbose_name="Count - Total African American", ), ), ( "count_total_latino_students", salesforce.fields.DecimalField( blank=True, db_column="Count_Total_Latino_Students__c", decimal_places=0, max_digits=18, null=True, verbose_name="Count - Total Latino Students", ), ), ( "female", salesforce.fields.DecimalField( blank=True, decimal_places=1, max_digits=18, null=True, verbose_name="% Female", ), ), ( "latino_african_american", salesforce.fields.DecimalField( blank=True, db_column="Latino_African_American__c", decimal_places=1, max_digits=18, null=True, verbose_name="% Latino/African American", ), ), ( "current_academic_semester", salesforce.fields.CharField( blank=True, db_column="Current_academic_semester__c", max_length=1300, null=True, verbose_name="Current academic semester", ), ), ( "in_current_semester", salesforce.fields.BooleanField( db_column="In_current_semester__c", default=False, verbose_name="In current semester?", ), ), ( "created_by", salesforce.fields.ForeignKey( on_delete=django.db.models.deletion.DO_NOTHING, related_name="classoffering_createdby_set", to="home.User", ), ), ( "instructor", salesforce.fields.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to="home.Contact", ), ), ( "last_modified_by", salesforce.fields.ForeignKey( on_delete=django.db.models.deletion.DO_NOTHING, related_name="classoffering_lastmodifiedby_set", to="home.User", ), ), ( "location", salesforce.fields.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to="home.Account", ), ), ], options={ "verbose_name": "Class Offering", "verbose_name_plural": "Class Offerings", "db_table": "Class_Offering__c", "abstract": False, "base_manager_name": "objects", }, ), migrations.CreateModel( name="ClassEnrollment", fields=[ ( "id", salesforce.fields.SalesforceAutoField( auto_created=True, db_column="Id", primary_key=True, serialize=False, verbose_name="ID", ), ), ( "is_deleted", salesforce.fields.BooleanField( default=False, verbose_name="Deleted" ), ), ( "name", salesforce.fields.CharField( max_length=80, verbose_name="Class Enrollment #" ), ), ("created_date", salesforce.fields.DateTimeField()), ("last_modified_date", salesforce.fields.DateTimeField()), ("system_modstamp", salesforce.fields.DateTimeField()), ( "last_activity_date", salesforce.fields.DateField(blank=True, null=True), ), ( "last_viewed_date", salesforce.fields.DateTimeField(blank=True, null=True), ), ( "last_referenced_date", salesforce.fields.DateTimeField(blank=True, null=True), ), ( "role", salesforce.fields.CharField( blank=True, choices=[ ("Student", "Student"), ("TA", "TA"), ("Volunteer", "Volunteer"), ], max_length=255, null=True, ), ), ( "status", salesforce.fields.CharField( blank=True, choices=[ ("Applied", "Applied"), ("Waitlisted", "Waitlisted"), ("Enrolled", "Enrolled"), ("Completed-Course", "Completed-Course"), ("Withdrew-Application", "Withdrew-Application"), ("Rejected", "Rejected"), ("Dropped", "Dropped"), ], max_length=255, null=True, ), ), ( "in_current_semester", salesforce.fields.BooleanField( db_column="In_current_semester__c", default=False, verbose_name="In current semester?", ), ), ( "attended_family_orientation", salesforce.fields.BooleanField( db_column="Attended_Family_Orientation__c", default=salesforce.backend.operations.DefaultedOnCreate(), verbose_name="Attended Family Orientation", ), ), ( "withdrew_application_detail", salesforce.fields.CharField( blank=True, choices=[ ( "Didn't show up for interview", "Didn't show up for interview", ), ("Acceptance-offer-rejected", "Acceptance-offer-rejected"), ("Didn’t show up for class", "Didn’t show up for class"), ("Dropped in first 2 weeks", "Dropped in first 2 weeks"), ("Withdrew before interview", "Withdrew before interview"), ("Class Cancelled", "Class Cancelled"), ], db_column="Withdrew_Application_Detail__c", help_text='"Dropped in first 2 weeks" means that they showed up for class but decided to drop within the first 2 weeks.', max_length=255, null=True, verbose_name="Withdrew-Application Detail", ), ), ( "contact_race", salesforce.fields.CharField( blank=True, db_column="Contact_Race__c", help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", max_length=100, null=True, verbose_name="Contact - Race", ), ), ( "contact_gender", salesforce.fields.CharField( blank=True, db_column="Contact_Gender__c", help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", max_length=30, null=True, verbose_name="Contact - Gender", ), ), ( "attended_interview", salesforce.fields.BooleanField( db_column="Attended_Interview__c", default=salesforce.backend.operations.DefaultedOnCreate(), help_text="Check if the student attended the default student admissions interview event. Note: Do not check this field if the student attended a makeup interview.", verbose_name="Attended Interview", ), ), ( "attended_makeup_interview", salesforce.fields.BooleanField( db_column="Attended_Makeup_Interview__c", default=salesforce.backend.operations.DefaultedOnCreate(), help_text="Check if the student did not attend the default interview date, but attended a makeup session.", verbose_name="Attended Makeup Interview", ), ), ( "cultural_affiliation_or_nationality", salesforce.fields.CharField( blank=True, db_column="Cultural_Affiliation_or_Nationality__c", help_text="(optional)", max_length=100, null=True, verbose_name="Cultural Affiliation or Nationality", ), ), ( "sex_at_birth", salesforce.fields.CharField( blank=True, choices=[ ("Female", "Female"), ("Male", "Male"), ("Decline to answer", "Decline to answer"), ], db_column="Sex_at_birth__c", help_text="(Check one)", max_length=255, null=True, verbose_name="What was your sex at birth?", ), ), ( "sexual_orientation", salesforce.fields.CharField( blank=True, choices=[ ("Bisexual", "Bisexual"), ( "Gay / Lesbian / Same-Gender Loving", "Gay / Lesbian / Same-Gender Loving", ), ("Questioning / Unsure", "Questioning / Unsure"), ("Straight / Heterosexual", "Straight / Heterosexual"), ("Not Listed.", "Not Listed."), ("Decline to answer", "Decline to answer"), ], db_column="Sexual_orientation__c", help_text="How do you describe your sexual orientation or sexual identity?", max_length=255, null=True, verbose_name="Sexual orientation or sexual identity", ), ), ( "other_sexual_orientation", salesforce.fields.CharField( blank=True, db_column="Other_sexual_orientation__c", max_length=30, null=True, verbose_name="Other sexual orientation", ), ), ( "household_type", salesforce.fields.CharField( blank=True, choices=[ ( "Single Female Headed Family", "Single Female Headed Family", ), ("Single Male Headed Family", "Single Male Headed Family"), ("Dual Headed Family", "Dual Headed Family"), ], db_column="Household_type__c", help_text="Which best describes your family? (Check one)\r\nFamily includes, but is not limited to the following—regardless of actual or perceived sexual orientation, gender identity, or marital status—a single person or a group of persons residing together.", max_length=255, null=True, verbose_name="Which best describes your family?", ), ), ( "income_certification", salesforce.fields.CharField( blank=True, choices=[ ("CalWorks", "CalWorks"), ("Food Stamps", "Food Stamps"), ("Medi-CAL", "Medi-CAL"), ("Tax Return (most recent)", "Tax Return (most recent)"), ("Unemployment (check stub)", "Unemployment (check stub)"), ("SSI**", "SSI**"), ("Payroll Stub**", "Payroll Stub**"), ( "Other (i.e. public housing/foster care)**", "Other (i.e. public housing/foster care)**", ), ("Self-certified", "Self-certified"), ], db_column="Income_Certification__c", help_text="**current-within 2 months", max_length=4099, null=True, verbose_name="Income Certification", ), ), ( "estimated_income", salesforce.fields.DecimalField( blank=True, db_column="Estimated_income__c", decimal_places=2, help_text="Total estimated income for next 12 months for all adult members.", max_digits=18, null=True, verbose_name="Estimated income", ), ), ( "family_size", salesforce.fields.CharField( blank=True, choices=[ ("1 person", "1 person"), ("2 persons", "2 persons"), ("3 persons", "3 persons"), ("4 persons", "4 persons"), ("5 persons", "5 persons"), ("6 persons", "6 persons"), ("7 persons", "7 persons"), ("8 persons", "8 persons"), ("9+ persons", "9+ persons"), ], db_column="Family_size__c", help_text="Number of persons living in your family (including yourself):", max_length=255, null=True, verbose_name="Family size", ), ), ( "current_income_information", salesforce.fields.CharField( blank=True, choices=[ ( "Extremely Low Income $0 - 27,650 (1 person)", "Extremely Low Income $0 - 27,650 (1 person)", ), ( "Low Income $27,651 - 46,100 (1 person)", "Low Income $27,651 - 46,100 (1 person)", ), ( "Moderate Income $46,101 - 73,750 (1 person)", "Moderate Income $46,101 - 73,750 (1 person)", ), ( "Above Moderate Income $73,751 or greater (1 person)", "Above Moderate Income $73,751 or greater (1 person)", ), ( "Extremely Low Income $0 - 31,600 (2 persons)", "Extremely Low Income $0 - 31,600 (2 persons)", ), ( "Low Income $31,601 - 52,650 (2 persons)", "Low Income $31,601 - 52,650 (2 persons)", ), ( "Moderate Income $52,651 - 84,300 (2 persons)", "Moderate Income $52,651 - 84,300 (2 persons)", ), ( "Above Moderate Income $84,301 or greater (2 persons)", "Above Moderate Income $84,301 or greater (2 persons)", ), ( "Extremely Low Income $0 - 35,550 (3 persons)", "Extremely Low Income $0 - 35,550 (3 persons)", ), ( "Low Income $35,551 - 59,250 (3 persons)", "Low Income $35,551 - 59,250 (3 persons)", ), ( "Moderate Income $59,251 - 94,850 (3 persons)", "Moderate Income $59,251 - 94,850 (3 persons)", ), ( "Above Moderate Income $94,851 or greater (3 persons)", "Above Moderate Income $94,851 or greater (3 persons)", ), ( "Extremely Low Income $0 - 39,500 (4 persons)", "Extremely Low Income $0 - 39,500 (4 persons)", ), ( "Low Income $39,501 - 65,800 (4 persons)", "Low Income $39,501 - 65,800 (4 persons)", ), ( "Moderate Income $65,801 - 105,350 (4 persons)", "Moderate Income $65,801 - 105,350 (4 persons)", ), ( "Above Moderate Income $105,351 or greater (4 persons)", "Above Moderate Income $105,351 or greater (4 persons)", ), ( "Extremely Low Income $0 - 42,700 (5 persons)", "Extremely Low Income $0 - 42,700 (5 persons)", ), ( "Low Income $42,701 - 71,100 (5 persons)", "Low Income $42,701 - 71,100 (5 persons)", ), ( "Moderate Income $71,101 - 113,800 (5 persons)", "Moderate Income $71,101 - 113,800 (5 persons)", ), ( "Above Moderate Income $113,801 or greater (5 persons)", "Above Moderate Income $113,801 or greater (5 persons)", ), ( "Extremely Low Income $0 - 45,850 (6 persons)", "Extremely Low Income $0 - 45,850 (6 persons)", ), ( "Low Income $45,851 - 76,350 (6 persons)", "Low Income $45,851 - 76,350 (6 persons)", ), ( "Moderate Income $76,351 - 122,250 (6 persons)", "Moderate Income $76,351 - 122,250 (6 persons)", ), ( "Above Moderate Income $122,251 or greater (6 persons)", "Above Moderate Income $122,251 or greater (6 persons)", ), ( "Extremely Low Income $0 - 49,000 (7 persons)", "Extremely Low Income $0 - 49,000 (7 persons)", ), ( "Low Income $49,001 - 81,600 (7 persons)", "Low Income $49,001 - 81,600 (7 persons)", ), ( "Moderate Income $81,601 - 130,650 (7 persons)", "Moderate Income $81,601 - 130,650 (7 persons)", ), ( "Above Moderate Income $130,651 or greater (7 persons)", "Above Moderate Income $130,651 or greater (7 persons)", ), ( "Extremely Low Income $0 - 52,150 (8 persons)", "Extremely Low Income $0 - 52,150 (8 persons)", ), ( "Low Income $52,151 - 86,900 (8 persons)", "Low Income $52,151 - 86,900 (8 persons)", ), ( "Moderate Income $86,901 - 139,100 (8 persons)", "Moderate Income $86,901 - 139,100 (8 persons)", ), ( "Above Moderate Income $139,101 or greater (8 persons)", "Above Moderate Income $139,101 or greater (8 persons)", ), ], db_column="Current_Income_Information__c", max_length=255, null=True, verbose_name="Current Income Information", ), ), ( "if_self_certified_please_explain", salesforce.fields.TextField( blank=True, db_column="If_self_certified_please_explain__c", null=True, verbose_name="If self-certified, please explain:", ), ), ( "contact_ethnicity", salesforce.fields.CharField( blank=True, db_column="Contact_Ethnicity__c", help_text="DO NOT EDIT - AUTO-POPULATED BY SYSTEM", max_length=100, null=True, verbose_name="Contact - Ethnicity", ), ), ("notes", salesforce.fields.TextField(blank=True, null=True)), ( "interview_date", salesforce.fields.DateTimeField( blank=True, db_column="Interview_Date__c", help_text="This is the interview date and time that the student signed up for. Empty means that the student did not sign up for an interview. Having an interview date does not mean that the student showed up for the interview, only that they RSVP'ed.", null=True, verbose_name="Interview Date", ), ), ( "returner", salesforce.fields.BooleanField( default=False, verbose_name="Returner?" ), ), ( "temp_returner", salesforce.fields.BooleanField( db_column="Temp_Returner__c", default=salesforce.backend.operations.DefaultedOnCreate(), help_text="This is a temporary field that determines if a student is a returner based on their response to this question on the application. Once we complete migrating all of our past data into Salesforce, this field will be deleted.", verbose_name="Returner? (temp)", ), ), ( "origin_school", salesforce.fields.CharField( blank=True, db_column="Origin_School__c", max_length=1300, null=True, verbose_name="School attended by this student", ), ), ( "parent_phone", salesforce.fields.CharField( blank=True, db_column="Parent_Phone__c", max_length=1300, null=True, verbose_name="Parent Phone", ), ), ( "parent_email", salesforce.fields.CharField( blank=True, db_column="Parent_Email__c", max_length=1300, null=True, verbose_name="Parent Email", ), ), ( "class_offering", salesforce.fields.ForeignKey( db_column="Class_Offering__c", on_delete=django.db.models.deletion.DO_NOTHING, to="home.ClassOffering", ), ), ( "contact", salesforce.fields.ForeignKey( on_delete=django.db.models.deletion.DO_NOTHING, related_name="classenrollment_contact_set", to="home.Contact", ), ), ( "created_by", salesforce.fields.ForeignKey( on_delete=django.db.models.deletion.DO_NOTHING, related_name="classenrollment_createdby_set", to="home.User", ), ), ( "last_modified_by", salesforce.fields.ForeignKey( on_delete=django.db.models.deletion.DO_NOTHING, related_name="classenrollment_lastmodifiedby_set", to="home.User", ), ), ( "parent_contact", salesforce.fields.ForeignKey( blank=True, db_column="Parent_Contact__c", null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name="classenrollment_parentcontact_set", to="home.Contact", ), ), ], options={ "verbose_name": "Class Enrollment", "verbose_name_plural": "Class Enrollments", "db_table": "Class_Enrollment__c", "abstract": False, "base_manager_name": "objects", }, ), migrations.AddField( model_name="attendance", name="classroom", field=models.ForeignKey( default=None, on_delete=django.db.models.deletion.CASCADE, related_name="attendance_classroom", to="home.Classroom", ), ), migrations.AddField( model_name="attendance", name="session", field=models.ForeignKey( default=None, on_delete=django.db.models.deletion.CASCADE, related_name="session", to="home.Session", ), ), migrations.AddField( model_name="attendance", name="student", field=models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="student", to=settings.AUTH_USER_MODEL, ), ), migrations.CreateModel( name="Announcement", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("title", models.CharField(max_length=240, unique=True)), ("announcement", models.TextField(max_length=2500)), ("posted", models.DateTimeField(auto_now=True, db_index=True)), ("email_recipients", models.BooleanField(default=False)), ( "created_by", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="user", to=settings.AUTH_USER_MODEL, ), ), ( "recipient_classrooms", models.ManyToManyField( related_name="recipient_classroom", to="home.Classroom" ), ), ( "recipient_groups", models.ManyToManyField(related_name="user_groups", to="auth.Group"), ), ], ), ]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,728
MissionBit/MB_Portal
refs/heads/master
/teacher/views.py
from django.shortcuts import render, redirect from home.decorators import group_required from home.models.models import ( Announcement, Form, Notification, Classroom, Session, Resource, ) from home.forms import AddResourceForm from attendance.views import get_date_from_template_returned_string from staff.staff_views_helper import get_classroom_by_django_user from staff.staff_views_helper import ( mark_announcement_dismissed, mark_notification_acknowledged, get_my_announcements, get_my_forms, ) import os from django.http import HttpResponse, Http404 from django.contrib import messages @group_required("teacher") def teacher(request): if request.method == "POST": if request.POST.get("dismiss_announcement") == "true": mark_announcement_dismissed( Announcement.objects.get(id=request.POST.get("announcement")), request.user, ) return redirect("teacher") elif request.POST.get("acknowledge_notification") == "true": mark_notification_acknowledged( Notification.objects.get(id=request.POST.get("notification")) ) return redirect("teacher") announcements = get_my_announcements(request, "teacher") forms = get_my_forms(request, "teacher") notifications = Notification.objects.filter(user_id=request.user.id) classroom = get_classroom_by_django_user(request.user) return render( request, "teacher.html", { "announcements": announcements, "forms": forms, "notifications": notifications, "classroom": classroom, }, ) @group_required("teacher") def my_class_teacher(request): classroom = get_classroom_by_django_user(request.user) sessions = Session.objects.filter(classroom_id=classroom.id).order_by("date") return render( request, "my_class_teacher.html", {"sessions": sessions, "classroom": classroom} ) @group_required("teacher") def session_view_teacher(request): if request.method == "POST": form = AddResourceForm(request.POST, request.FILES) if form.is_valid(): resource = Resource( title=form.cleaned_data.get("title"), description=form.cleaned_data.get("description"), classroom_id=request.POST.get("classroom"), session_id=request.POST.get("session"), ) if request.POST.get("link"): resource.link = form.cleaned_data.get("link") if request.FILES.get("file"): resource.file = form.cleaned_data.get("file") resource.save() messages.add_message(request, messages.SUCCESS, "Resource Added To Session") return redirect("teacher") else: return render(request, "session_view_teacher.html", {"form": form}) session = Session.objects.get( classroom_id=request.GET.get("classroom"), date=get_date_from_template_returned_string(request.GET.get("session_date")), ) resources = Resource.objects.filter(session_id=session.id) classroom = get_classroom_by_django_user(request.user) form = AddResourceForm() return render( request, "session_view_teacher.html", { "session": session, "resources": resources, "form": form, "classroom": classroom, }, )
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,729
MissionBit/MB_Portal
refs/heads/master
/staff/urls.py
from django.urls import path from . import views urlpatterns = [ path("", views.staff, name="staff"), path( "classroom_management/", views.classroom_management, name="classroom_management" ), path("create_staff_user/", views.create_staff_user, name="create_staff_user"), path("create_teacher_user/", views.create_teacher_user, name="create_teacher_user"), path("create_student_user/", views.create_student_user, name="create_student_user"), path( "create_volunteer_user", views.create_volunteer_user, name="create_volunteer_user", ), path("create_classroom/", views.create_classroom, name="create_classroom"), path( "create_class_offering/", views.create_class_offering, name="create_class_offering", ), path("make_announcement/", views.make_announcement, name="make_announcement"), path("post_form/", views.post_form, name="post_form"), path("create_esign", views.create_esign, name="create_esign"), path("form_overview", views.form_overview, name="form_overview"), path( "notify_unsubmitted_users/<notify_about>", views.notify_unsubmitted_users, name="notify_unsubmitted_users", ), path( "communication_manager/", views.communication_manager, name="communication_manager", ), path("curriculum/", views.curriculum, name="curriculum"), path( "modify_session/<date>/<classroom>", views.modify_session, name="modify_session" ), path("add_forum/", views.add_forum, name="add_forum"), path( "classroom_detail/<course_id>", views.classroom_detail, name="classroom_detail" ), ]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,730
MissionBit/MB_Portal
refs/heads/master
/home/apps.py
from django.apps import AppConfig from django.db.models.signals import pre_migrate from azure.storage.blob import PublicAccess def ensure_azure_container(sender, **kwargs): """ Ensure that the expected Azure Storage container exists when running with an emulated service. """ from missionbit.azure_storage_backend import CustomAzureStorage if not CustomAzureStorage.is_emulated: return CustomAzureStorage().service.create_container( CustomAzureStorage.azure_container, public_access=PublicAccess.Blob ) class HomeConfig(AppConfig): name = "home" def ready(self): pre_migrate.connect(ensure_azure_container, sender=self)
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,731
MissionBit/MB_Portal
refs/heads/master
/home/choices.py
RACE_CHOICES = ( ("American Indian/Alaskan Native", "American Indian/Alaskan Native"), ("Asian", "Asian"), ("Black/African American", "Black/African American"), ( "Native Hawaiian/Other Pacific Islander", "Native Hawaiian/Other Pacific Islander", ), ("White", "White"), ( "American Indian/Alaskan Native AND Black/African American", "American Indian/Alaskan Native AND Black/African American", ), ( "American Indian/Alaskan Native AND White", "American Indian/Alaskan Native AND White", ), ("Asian AND White", "Asian AND White"), ("Black/African American AND White", "Black/African American AND White"), ("Other/Multiracial", "Other/Multiracial"), ) ETHNICITY_CHOICES = ( ("Hispanic/Latinx", "Hispanic/Latinx"), ("Not Hispanic/Latinx", "Not Hispanic/Latinx"), ) GENDER_CHOICES = ( ("Female", "Female"), ("Male", "Male"), ("Genderqueer/Gender Non-binary", "Genderqueer/Gender Non-binary"), ("Trans Female", "Trans Female"), ("Trans Male", "Trans Male"), ("Other", "Not Listed"), ) GRAD_YEAR_CHOICES = ( ("2019", "2019"), ("2020", "2020"), ("2021", "2021"), ("2022", "2022"), ("2023", "2023"), ("2024", "2024"), ("2025", "2025"), ("2026", "2026"), ("2027", "2027"), ("2028", "2028"), ("2029", "2029"), ("2030", "2030"), ("2031", "2031"), ("2032", "2032"), ("2033", "2033"), ("2034", "2034"), ) COURSE_CHOICES = ( ("Android Game Design", "Android Game Design"), ("Intro to Web Programming", "Intro to Web Programming"), ("Field Trips", "Field Trips"), ("Intro to Game Design with Unity", "Intro to Game Design with Unity"), ("Web Design 101", "Web Design 101"), ("Mobile App Dev with Ionic", "Mobile App Dev with Ionic"), ("MB Internship", "MB Internship"), ("Structured Study Program", "Structured Study Program"), ) MEETING_DAYS_CHOICES = (("M/W", "M/W"), ("T/R", "T/R"), ("M-F", "M-F")) ACCOUNT_TYPE_CHOICES = ( ("School", "School"), ("Foundation", "Foundation"), ("Government", "Government"), ("Business", "Business"), ("Nonprofit", "Nonprofit"), ) SALUTATION_CHOICES = ( ("Mr.", "Mr."), ("Ms.", "Ms."), ("Mrs.", "Mrs."), ("Dr.", "Dr."), ("Prof.", "Prof."), ) STATE_CHOICES = ( ("AC", "Acre"), ("AG", "Agrigento"), ("AG", "Aguascalientes"), ("AL", "Alabama"), ("AL", "Alagoas"), ("AK", "Alaska"), ("AB", "Alberta"), ("AL", "Alessandria"), ("AP", "Amapá"), ("AM", "Amazonas"), ("AN", "Ancona"), ("AN", "Andaman and Nicobar Islands"), ("AP", "Andhra Pradesh"), ("34", "Anhui"), ("AO", "Aosta"), ("AR", "Arezzo"), ("AZ", "Arizona"), ("AR", "Arkansas"), ("AR", "Arunachal Pradesh"), ("AP", "Ascoli Piceno"), ("AS", "Assam"), ("AT", "Asti"), ("ACT", "Australian Capital Territory"), ("AV", "Avellino"), ("BA", "Bahia"), ("BC", "Baja California"), ("BS", "Baja California Sur"), ("BA", "Bari"), ("BT", "Barletta-Andria-Trani"), ("11", "Beijing"), ("BL", "Belluno"), ("BN", "Benevento"), ("BG", "Bergamo"), ("BI", "Biella"), ("BR", "Bihar"), ("BO", "Bologna"), ("BZ", "Bolzano"), ("BS", "Brescia"), ("BR", "Brindisi"), ("BC", "British Columbia"), ("CA", "Cagliari"), ("CA", "California"), ("CL", "Caltanissetta"), ("CM", "Campeche"), ("CB", "Campobasso"), ("CI", "Carbonia-Iglesias"), ("CW", "Carlow"), ("CE", "Caserta"), ("CT", "Catania"), ("CZ", "Catanzaro"), ("CN", "Cavan"), ("CE", "Ceará"), ("CH", "Chandigarh"), ("CT", "Chhattisgarh"), ("CS", "Chiapas"), ("CH", "Chieti"), ("CH", "Chihuahua"), ("71", "Chinese Taipei"), ("50", "Chongqing"), ("CE", "Clare"), ("CO", "Coahuila"), ("CL", "Colima"), ("CO", "Colorado"), ("CO", "Como"), ("CT", "Connecticut"), ("CO", "Cork"), ("CS", "Cosenza"), ("CR", "Cremona"), ("KR", "Crotone"), ("CN", "Cuneo"), ("DN", "Dadra and Nagar Haveli"), ("DD", "Daman and Diu"), ("DE", "Delaware"), ("DL", "Delhi"), ("DC", "District of Columbia"), ("DF", "Distrito Federal"), ("DL", "Donegal"), ("D", "Dublin"), ("DG", "Durango"), ("EN", "Enna"), ("ES", "Espírito Santo"), ("DF", "Federal District"), ("FM", "Fermo"), ("FE", "Ferrara"), ("FI", "Florence"), ("FL", "Florida"), ("FG", "Foggia"), ("FC", "Forlì-Cesena"), ("FR", "Frosinone"), ("35", "Fujian"), ("G", "Galway"), ("62", "Gansu"), ("GE", "Genoa"), ("GA", "Georgia"), ("GA", "Goa"), ("GO", "Goiás"), ("GO", "Gorizia"), ("GR", "Grosseto"), ("GT", "Guanajuato"), ("44", "Guangdong"), ("45", "Guangxi"), ("GR", "Guerrero"), ("52", "Guizhou"), ("GJ", "Gujarat"), ("46", "Hainan"), ("HR", "Haryana"), ("HI", "Hawaii"), ("13", "Hebei"), ("23", "Heilongjiang"), ("41", "Henan"), ("HG", "Hidalgo"), ("HP", "Himachal Pradesh"), ("91", "Hong Kong"), ("42", "Hubei"), ("43", "Hunan"), ("ID", "Idaho"), ("IL", "Illinois"), ("IM", "Imperia"), ("IN", "Indiana"), ("IA", "Iowa"), ("IS", "Isernia"), ("JA", "Jalisco"), ("JK", "Jammu and Kashmir"), ("JH", "Jharkhand"), ("32", "Jiangsu"), ("36", "Jiangxi"), ("22", "Jilin"), ("KS", "Kansas"), ("KA", "Karnataka"), ("KY", "Kentucky"), ("KL", "Kerala"), ("KY", "Kerry"), ("KE", "Kildare"), ("KK", "Kilkenny"), ("AQ", "L'Aquila"), ("LD", "Lakshadweep"), ("LS", "Laois"), ("SP", "La Spezia"), ("LT", "Latina"), ("LE", "Lecce"), ("LC", "Lecco"), ("LM", "Leitrim"), ("21", "Liaoning"), ("LK", "Limerick"), ("LI", "Livorno"), ("LO", "Lodi"), ("LD", "Longford"), ("LA", "Louisiana"), ("LH", "Louth"), ("LU", "Lucca"), ("92", "Macao"), ("MC", "Macerata"), ("MP", "Madhya Pradesh"), ("MH", "Maharashtra"), ("ME", "Maine"), ("MN", "Manipur"), ("MB", "Manitoba"), ("MN", "Mantua"), ("MA", "Maranhão"), ("MD", "Maryland"), ("MS", "Massa and Carrara"), ("MA", "Massachusetts"), ("MT", "Matera"), ("MT", "Mato Grosso"), ("MS", "Mato Grosso do Sul"), ("MO", "Mayo"), ("MH", "Meath"), ("VS", "Medio Campidano"), ("ML", "Meghalaya"), ("ME", "Messina"), ("ME", "Mexico State"), ("MI", "Michigan"), ("MI", "Michoacán"), ("MI", "Milan"), ("MG", "Minas Gerais"), ("MN", "Minnesota"), ("MS", "Mississippi"), ("MO", "Missouri"), ("MZ", "Mizoram"), ("MO", "Modena"), ("MN", "Monaghan"), ("MT", "Montana"), ("MB", "Monza and Brianza"), ("MO", "Morelos"), ("NL", "Nagaland"), ("NA", "Naples"), ("NA", "Nayarit"), ("NE", "Nebraska"), ("15", "Nei Mongol"), ("NV", "Nevada"), ("NB", "New Brunswick"), ("NL", "Newfoundland and Labrador"), ("NH", "New Hampshire"), ("NJ", "New Jersey"), ("NM", "New Mexico"), ("NSW", "New South Wales"), ("NY", "New York"), ("64", "Ningxia"), ("NC", "North Carolina"), ("ND", "North Dakota"), ("NT", "Northern Territory"), ("NT", "Northwest Territories"), ("NO", "Novara"), ("NS", "Nova Scotia"), ("NL", "Nuevo León"), ("NU", "Nunavut"), ("NU", "Nuoro"), ("OA", "Oaxaca"), ("OR", "Odisha"), ("OY", "Offaly"), ("OG", "Ogliastra"), ("OH", "Ohio"), ("OK", "Oklahoma"), ("OT", "Olbia-Tempio"), ("ON", "Ontario"), ("OR", "Oregon"), ("OR", "Oristano"), ("PD", "Padua"), ("PA", "Palermo"), ("PA", "Pará"), ("PB", "Paraíba"), ("PR", "Paraná"), ("PR", "Parma"), ("PV", "Pavia"), ("PA", "Pennsylvania"), ("PE", "Pernambuco"), ("PG", "Perugia"), ("PU", "Pesaro and Urbino"), ("PE", "Pescara"), ("PC", "Piacenza"), ("PI", "Piauí"), ("PI", "Pisa"), ("PT", "Pistoia"), ("PN", "Pordenone"), ("PZ", "Potenza"), ("PO", "Prato"), ("PE", "Prince Edward Island"), ("PY", "Puducherry"), ("PB", "Puebla"), ("PB", "Punjab"), ("63", "Qinghai"), ("QC", "Quebec"), ("QLD", "Queensland"), ("QE", "Querétaro"), ("QR", "Quintana Roo"), ("RG", "Ragusa"), ("RJ", "Rajasthan"), ("RA", "Ravenna"), ("RC", "Reggio Calabria"), ("RE", "Reggio Emilia"), ("RI", "Rhode Island"), ("RI", "Rieti"), ("RN", "Rimini"), ("RJ", "Rio de Janeiro"), ("RN", "Rio Grande do Norte"), ("RS", "Rio Grande do Sul"), ("RM", "Rome"), ("RO", "Rondônia"), ("RR", "Roraima"), ("RN", "Roscommon"), ("RO", "Rovigo"), ("SA", "Salerno"), ("SL", "San Luis Potosí"), ("SC", "Santa Catarina"), ("SP", "São Paulo"), ("SK", "Saskatchewan"), ("SS", "Sassari"), ("SV", "Savona"), ("SE", "Sergipe"), ("61", "Shaanxi"), ("37", "Shandong"), ("31", "Shanghai"), ("14", "Shanxi"), ("51", "Sichuan"), ("SI", "Siena"), ("SK", "Sikkim"), ("SI", "Sinaloa"), ("SO", "Sligo"), ("SO", "Sondrio"), ("SO", "Sonora"), ("SA", "South Australia"), ("SC", "South Carolina"), ("SD", "South Dakota"), ("SR", "Syracuse"), ("TB", "Tabasco"), ("TM", "Tamaulipas"), ("TN", "Tamil Nadu"), ("TA", "Taranto"), ("TAS", "Tasmania"), ("TN", "Tennessee"), ("TE", "Teramo"), ("TR", "Terni"), ("TX", "Texas"), ("12", "Tianjin"), ("TA", "Tipperary"), ("TL", "Tlaxcala"), ("TO", "Tocantins"), ("TP", "Trapani"), ("TN", "Trento"), ("TV", "Treviso"), ("TS", "Trieste"), ("TR", "Tripura"), ("TO", "Turin"), ("UD", "Udine"), ("UT", "Utah"), ("UT", "Uttarakhand"), ("UP", "Uttar Pradesh"), ("VA", "Varese"), ("VE", "Venice"), ("VE", "Veracruz"), ("VB", "Verbano-Cusio-Ossola"), ("VC", "Vercelli"), ("VT", "Vermont"), ("VR", "Verona"), ("VV", "Vibo Valentia"), ("VI", "Vicenza"), ("VIC", "Victoria"), ("VA", "Virginia"), ("VT", "Viterbo"), ("WA", "Washington"), ("WD", "Waterford"), ("WB", "West Bengal"), ("WA", "Western Australia"), ("WH", "Westmeath"), ("WV", "West Virginia"), ("WX", "Wexford"), ("WW", "Wicklow"), ("WI", "Wisconsin"), ("WY", "Wyoming"), ("65", "Xinjiang"), ("54", "Xizang"), ("YU", "Yucatán"), ("YT", "Yukon Territories"), ("53", "Yunnan"), ("ZA", "Zacatecas"), ("33", "Zhejiang"), ) CURRENT_GRADE_CHOICES = ( ("Graduating 8th", "Graduating 8th"), ("Freshman, 9th", "Freshman, 9th"), ("Sophomore, 10th", "Sophomore, 10th"), ("Junior, 11th", "Junior, 11th"), ("Senior, 12th", "Senior, 12th"), ) STATUS_CHOICES = ( ("Applied", "Applied"), ("Waitlisted", "Waitlisted"), ("Enrolled", "Enrolled"), ("Completed-Course", "Completed-Course"), ("Withdrew-Application", "Withdrew-Application"), ("Rejected", "Rejected"), ("Dropped", "Dropped"), ) APP_WD_CHOICES = ( ("Didn't show up for interview", "Didn't show up for interview"), ("Acceptance-offer-rejected", "Acceptance-offer-rejected"), ("Didn’t show up for class", "Didn’t show up for class"), ("Dropped in first 2 weeks", "Dropped in first 2 weeks"), ("Withdrew before interview", "Withdrew before interview"), ("Class Cancelled", "Class Cancelled"), ) SEX_AT_BIRTH_CHOICES = ( ("Female", "Female"), ("Male", "Male"), ("Decline to answer", "Decline to answer"), ) SEXUAL_ORIENTATION_CHOICES = ( ("Bisexual", "Bisexual"), ("Gay / Lesbian / Same-Gender Loving", "Gay / Lesbian / Same-Gender Loving"), ("Questioning / Unsure", "Questioning / Unsure"), ("Straight / Heterosexual", "Straight / Heterosexual"), ("Not Listed.", "Not Listed."), ("Decline to answer", "Decline to answer"), ) HOUSEHOLD_TYPE_CHOICES = ( ("Single Female Headed Family", "Single Female Headed Family"), ("Single Male Headed Family", "Single Male Headed Family"), ("Dual Headed Family", "Dual Headed Family"), ) INCOME_CERT_CHOICES = ( ("CalWorks", "CalWorks"), ("Food Stamps", "Food Stamps"), ("Medi-CAL", "Medi-CAL"), ("Tax Return (most recent)", "Tax Return (most recent)"), ("Unemployment (check stub)", "Unemployment (check stub)"), ("SSI**", "SSI**"), ("Payroll Stub**", "Payroll Stub**"), ( "Other (i.e. public housing/foster care)**", "Other (i.e. public housing/foster care)**", ), ("Self-certified", "Self-certified"), ) FAMILY_SIZE_CHOICES = ( ("1 person", "1 person"), ("2 persons", "2 persons"), ("3 persons", "3 persons"), ("4 persons", "4 persons"), ("5 persons", "5 persons"), ("6 persons", "6 persons"), ("7 persons", "7 persons"), ("8 persons", "8 persons"), ("9+ persons", "9+ persons"), ) INCOME_LEVEL_CHOICES = ( ( "Extremely Low Income $0 - 27,650 (1 person)", "Extremely Low Income $0 - 27,650 (1 person)", ), ( "Low Income $27,651 - 46,100 (1 person)", "Low Income $27,651 - 46,100 (1 person)", ), ( "Moderate Income $46,101 - 73,750 (1 person)", "Moderate Income $46,101 - 73,750 (1 person)", ), ( "Above Moderate Income $73,751 or greater (1 person)", "Above Moderate Income $73,751 or greater (1 person)", ), ( "Extremely Low Income $0 - 31,600 (2 persons)", "Extremely Low Income $0 - 31,600 (2 persons)", ), ( "Low Income $31,601 - 52,650 (2 persons)", "Low Income $31,601 - 52,650 (2 persons)", ), ( "Moderate Income $52,651 - 84,300 (2 persons)", "Moderate Income $52,651 - 84,300 (2 persons)", ), ( "Above Moderate Income $84,301 or greater (2 persons)", "Above Moderate Income $84,301 or greater (2 persons)", ), ( "Extremely Low Income $0 - 35,550 (3 persons)", "Extremely Low Income $0 - 35,550 (3 persons)", ), ( "Low Income $35,551 - 59,250 (3 persons)", "Low Income $35,551 - 59,250 (3 persons)", ), ( "Moderate Income $59,251 - 94,850 (3 persons)", "Moderate Income $59,251 - 94,850 (3 persons)", ), ( "Above Moderate Income $94,851 or greater (3 persons)", "Above Moderate Income $94,851 or greater (3 persons)", ), ( "Extremely Low Income $0 - 39,500 (4 persons)", "Extremely Low Income $0 - 39,500 (4 persons)", ), ( "Low Income $39,501 - 65,800 (4 persons)", "Low Income $39,501 - 65,800 (4 persons)", ), ( "Moderate Income $65,801 - 105,350 (4 persons)", "Moderate Income $65,801 - 105,350 (4 persons)", ), ( "Above Moderate Income $105,351 or greater (4 persons)", "Above Moderate Income $105,351 or greater (4 persons)", ), ( "Extremely Low Income $0 - 42,700 (5 persons)", "Extremely Low Income $0 - 42,700 (5 persons)", ), ( "Low Income $42,701 - 71,100 (5 persons)", "Low Income $42,701 - 71,100 (5 persons)", ), ( "Moderate Income $71,101 - 113,800 (5 persons)", "Moderate Income $71,101 - 113,800 (5 persons)", ), ( "Above Moderate Income $113,801 or greater (5 persons)", "Above Moderate Income $113,801 or greater (5 persons)", ), ( "Extremely Low Income $0 - 45,850 (6 persons)", "Extremely Low Income $0 - 45,850 (6 persons)", ), ( "Low Income $45,851 - 76,350 (6 persons)", "Low Income $45,851 - 76,350 (6 persons)", ), ( "Moderate Income $76,351 - 122,250 (6 persons)", "Moderate Income $76,351 - 122,250 (6 persons)", ), ( "Above Moderate Income $122,251 or greater (6 persons)", "Above Moderate Income $122,251 or greater (6 persons)", ), ( "Extremely Low Income $0 - 49,000 (7 persons)", "Extremely Low Income $0 - 49,000 (7 persons)", ), ( "Low Income $49,001 - 81,600 (7 persons)", "Low Income $49,001 - 81,600 (7 persons)", ), ( "Moderate Income $81,601 - 130,650 (7 persons)", "Moderate Income $81,601 - 130,650 (7 persons)", ), ( "Above Moderate Income $130,651 or greater (7 persons)", "Above Moderate Income $130,651 or greater (7 persons)", ), ( "Extremely Low Income $0 - 52,150 (8 persons)", "Extremely Low Income $0 - 52,150 (8 persons)", ), ( "Low Income $52,151 - 86,900 (8 persons)", "Low Income $52,151 - 86,900 (8 persons)", ), ( "Moderate Income $86,901 - 139,100 (8 persons)", "Moderate Income $86,901 - 139,100 (8 persons)", ), ( "Above Moderate Income $139,101 or greater (8 persons)", "Above Moderate Income $139,101 or greater (8 persons)", ), ) CHANGE_STUDENT_CHOICES = (("Add", "Add"), ("Remove", "Remove"), ("None", "None")) CLASSROOM_MEMBERSHIP_CHOICES = ( ("teacher", "teacher"), ("teacher_assistant", "teacher_assistant"), ("student", "student"), ("volunteer", "volunteer"), )
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,732
MissionBit/MB_Portal
refs/heads/master
/home/migrations/0003_announcementdistribution.py
# Generated by Django 2.2.3 on 2019-07-31 18:32 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("home", "0002_add_groups"), ] operations = [ migrations.CreateModel( name="AnnouncementDistribution", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("dismissed", models.BooleanField(default=False)), ( "announcement", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="announcement_distributed", to="home.Announcement", ), ), ( "user", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="announcement_user", to=settings.AUTH_USER_MODEL, ), ), ], ) ]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,733
MissionBit/MB_Portal
refs/heads/master
/staff/staff_views_helper.py
from django.contrib.auth.models import User as DjangoUser from django.contrib.auth.models import Group from django.shortcuts import render from home.models.salesforce import ClassEnrollment, Contact, ClassOffering from home.models.models import ( Announcement, UserProfile, Classroom, ClassroomMembership, Attendance, Session, FormDistribution, Form, AnnouncementDistribution, ) from social_django.models import UserSocialAuth from django.core.mail import send_mail, EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags from django.conf import settings from django.contrib import messages from datetime import timedelta, datetime from salesforce.dbapi.exceptions import * import random def create_user_with_profile(form, random_password): username = validate_username( "%s.%s" % (form.cleaned_data.get("first_name"), form.cleaned_data.get("last_name")) ) new_user = DjangoUser.objects.create_user( username=username, email=form.cleaned_data.get("email"), first_name=form.cleaned_data.get("first_name"), last_name=form.cleaned_data.get("last_name"), password=random_password, ) new_user = parse_new_user(new_user, form) new_user.save() return new_user def validate_username(username): res_username = username while DjangoUser.objects.filter(username=res_username).exists(): random_number = random.randint(1, 10000) res_username = username + str(random_number) return res_username def parse_new_user(new_user, form): birthdate = form.cleaned_data.get("birthdate") if birthdate is None: birthdate = datetime(1901, 1, 1) new_user.userprofile.change_pwd = True new_user.userprofile.salesforce_id = "%s%s%s%s%s" % ( form.cleaned_data.get("first_name")[:3].lower(), form.cleaned_data.get("last_name")[:3].lower(), "%04d" % birthdate.year, "%02d" % birthdate.month, "%02d" % birthdate.day, ) new_user.userprofile.date_of_birth = birthdate return new_user def save_user_to_salesforce(request, form): try: form.save() except SalesforceError: messages.error(request, "Error Saving User To Salesforce Database.") return render(request, "create_staff_user.html", {"form": form}) def create_mission_bit_user(request, form, group): random_password = DjangoUser.objects.make_random_password() new_user = create_user_with_profile(form, random_password) email = form.cleaned_data.get("email") student_group = Group.objects.get(name=group) student_group.user_set.add(new_user) UserSocialAuth.objects.create( uid=form.cleaned_data.get("email"), user_id=new_user.userprofile.user_id, provider="google-oauth2", ) first_name = form.cleaned_data.get("first_name") messages.success(request, f"Student Account Successfully Created For {first_name}") email_new_user( request, email, first_name, group, new_user.username, random_password ) def enroll_in_class(form, contact): ClassEnrollment.objects.get_or_create( name=form.cleaned_data.get("course"), created_by=form.cleaned_data.get("created_by"), contact=contact, status="Enrolled", class_offering=form.cleaned_data.get("course"), ) def setup_classroom(request, form): email_list = [] teacher = get_django_user_from_contact(form.cleaned_data.get("teacher")) teacher_assistant = get_django_user_from_contact( form.cleaned_data.get("teacher_assistant") ) email_list.append(teacher.email) email_list.append(teacher_assistant.email) classroom = Classroom.objects.create(course=form.cleaned_data.get("course").name) create_classroom_membership(teacher, classroom, "teacher") create_classroom_membership(teacher_assistant, classroom, "teacher_assistant") enroll_in_class(form, form.cleaned_data.get("teacher")) enroll_in_class(form, form.cleaned_data.get("teacher_assistant")) for volunteer in form.cleaned_data.get("volunteers"): enroll_in_class(form, volunteer) django_volunteer = get_django_user_from_contact(volunteer) create_classroom_membership(django_volunteer, classroom, "volunteer") email_list.append(django_volunteer.email) for student in form.cleaned_data.get("students"): enroll_in_class(form, student) django_student = get_django_user_from_contact(student) create_classroom_membership(django_student, classroom, "student") email_list.append(django_student.email) generate_classroom_sessions_and_attendance(classroom) email_classroom(request, email_list, classroom.course) def get_django_user_from_contact(contact): return DjangoUser.objects.get( id=UserProfile.objects.get(salesforce_id=contact.client_id.lower()).user_id ) def retrieve_userprofile_from_form(form, name_string): return UserProfile.objects.get( salesforce_id=form.cleaned_data.get(name_string).client_id.lower() ) def create_classroom_membership(django_user_member, classroom, membership_type): cm = ClassroomMembership( member=django_user_member, classroom=classroom, membership_type=membership_type ) cm.save() def generate_classroom_sessions_and_attendance(classroom): classroom.attendance_summary = { "attendance_statistic": get_course_attendance_statistic(classroom.id) } classroom.save() class_offering = ClassOffering.objects.get(name=classroom.course) dates = class_offering_meeting_dates(class_offering) sessions = [Session(classroom_id=classroom.id, date=day) for day in dates] Session.objects.bulk_create(sessions) classroom_students = get_users_of_type_from_classroom(classroom, "student") attendances = [ Attendance( student_id=student.id, session_id=session.id, classroom_id=classroom.id, date=session.date, ) for student in classroom_students for session in sessions ] Attendance.objects.bulk_create(attendances) def get_classroom_sessions(classroom): return Session.objects.filter(classroom=classroom) def get_users_of_type_from_classroom(classroom, type): return DjangoUser.objects.filter( classroom=classroom, classroom_member__membership_type=type ) # Handle Empty Set Case def get_teacher_from_classroom(classroom): return DjangoUser.objects.get( classroom=classroom, classroom_member__membership_type="teacher" ) # Handle a multiple values returned exception def get_teacher_assistant_from_classroom(classroom): return DjangoUser.objects.get( classroom=classroom, classroom_member__membership_type="teacher_assistant" ) # Handle a multiple values returned exception def get_classroom_by_django_user(django_user): try: return Classroom.objects.get(membership_classroom__member=django_user) except TypeError: return None except Classroom.DoesNotExist: return None def email_new_user(request, email, first_name, account_type, username, password): subject = "%s - Your new %s account has been set up" % (first_name, account_type) msg_html = render_to_string( "email_templates/new_user_email.html", { "first_name": first_name, "email": email, "username": username, "password": password, "account_type": account_type, }, ) from_user = settings.EMAIL_HOST_USER send_mail( subject=subject, message=strip_tags(msg_html), from_email=from_user, recipient_list=["tyler.iams@gmail.com"], # Will replace with email html_message=msg_html, ) messages.add_message(request, messages.SUCCESS, "Email sent successfully") def email_classroom(request, email_list, classroom_name): subject = "Your Mission Bit %s Classroom Has Been Created" % classroom_name msg_html = render_to_string( "email_templates/new_classroom_email.html", {"classroom_name": classroom_name} ) from_user = settings.EMAIL_HOST_USER recipient_list = [ "tyler.iams@gmail.com", "iams.sophia@gmail.com", ] # Will replace with email_list send_mail( subject=subject, message=strip_tags(msg_html), from_email=from_user, recipient_list=recipient_list, html_message=msg_html, ) messages.add_message(request, messages.SUCCESS, "Email sent successfully") def get_users_from_form(form): group_users = DjangoUser.objects.filter( groups__name__in=list(form.cleaned_data.get("recipient_groups")) ) classroom_users = DjangoUser.objects.filter( classroom__in=list(form.cleaned_data.get("recipient_classrooms")) ) return (classroom_users | group_users).distinct() def get_emails_from_form_distributions(form_distributions): return DjangoUser.objects.filter( email__in=[form_dist.user.email for form_dist in form_distributions] ) def email_announcement(request, subject, message, email_list): msg_html = render_to_string( "email_templates/announcement_email.html", {"subject": subject, "message": message, "from": request.user}, ) from_user = settings.EMAIL_HOST_USER recipient_list = [ "tyler.iams@gmail.com", "iams.sophia@gmail.com", ] # Will replace with email_list send_mail( subject=subject, message=strip_tags(msg_html), from_email=from_user, recipient_list=recipient_list, html_message=msg_html, ) messages.add_message(request, messages.SUCCESS, "Recipients Successfully Emailed") def bulk_distribute_announcement(user_list, announcement): announcement_distributions = [ AnnouncementDistribution( user_id=user.id, announcement_id=announcement.id, dismissed=False ) for user in user_list ] AnnouncementDistribution.objects.bulk_create(announcement_distributions) def email_posted_form(request, esign, subject, message, posted_form, email_list): msg_html = render_to_string( "email_templates/post_form_email.html", { "subject": subject, "message": message, "from": DjangoUser.objects.get(id=request.user.id), "esign_link": esign, "posted_form": posted_form }, ) text_content = "Please view your new form (attached)" recipient_list = [ "tyler.iams@gmail.com", "iams.sophia@gmail.com", ] # Will replace with email_list email = EmailMultiAlternatives( subject, text_content, settings.EMAIL_HOST_USER, recipient_list ) email.attach_alternative(msg_html, "text/html") email.send() messages.add_message(request, messages.SUCCESS, "Recipients Successfully Emailed") def change_classroom_lead( former_leader_user_id, new_leader_user_id, course_id, leader_type ): class_offering = get_class_offering_by_id(course_id) new_lead_contact = get_contact_by_user_id(new_leader_user_id) classroom = Classroom.objects.get(id=course_id) remove_user_from_classroom(former_leader_user_id, course_id) create_classroom_membership( DjangoUser.objects.get(id=new_leader_user_id), classroom, leader_type ) ClassEnrollment.objects.get_or_create( created_by=class_offering.created_by, contact=new_lead_contact, status="Enrolled", class_offering=class_offering, ) if leader_type is "teacher": class_offering.instructor = new_lead_contact class_offering.save() def remove_user_from_classroom(user_id, course_id): remove_enrollment( get_contact_by_user_id(user_id), get_class_offering_by_id(course_id) ) ClassroomMembership.objects.get( classroom=Classroom.objects.get(id=course_id), member_id=user_id ).delete() def add_user_to_classroom(user_id, course_id, member_type): class_offering = get_class_offering_by_id(course_id) ClassroomMembership.objects.create( classroom=Classroom.objects.get(id=course_id), member=DjangoUser.objects.get(id=user_id), membership_type=member_type, ) ClassEnrollment.objects.create( created_by=class_offering.created_by, contact=get_contact_by_user_id(user_id), status="Enrolled", class_offering=class_offering, ) def remove_enrollment(contact, class_offering): old_enrollment = ClassEnrollment.objects.get( contact=contact, status="Enrolled", class_offering=class_offering ) created_by = old_enrollment.created_by old_enrollment.delete() return created_by def get_contact_by_user_id(id): return Contact.objects.get( client_id=UserProfile.objects.get(user_id=id).salesforce_id ) def get_class_offering_by_id(id): course_name = get_course_name_by_id(id) return ClassOffering.objects.get(name=course_name) def get_course_name_by_id(id): return Classroom.objects.get(id=id).course def class_offering_meeting_dates(class_offering): int_days = get_integer_days(class_offering) class_range = class_offering.end_date - class_offering.start_date dates = [] for i in range(class_range.days + 1): the_date = class_offering.start_date + timedelta(days=i) if the_date.weekday() in int_days: dates.append(the_date) return dates def get_integer_days(class_offering): if class_offering.meeting_days == "M-F": return [0, 1, 2, 3, 4] elif class_offering.meeting_days == "M/W": return [0, 2] elif class_offering.meeting_days == "T/R": return [1, 3] def distribute_forms(request, posted_form, user_list): bulk_create_form_distributions(posted_form, user_list) messages.add_message(request, messages.SUCCESS, "Form Distributed Successfully") def bulk_create_form_distributions(form, users): form_dists = [ FormDistribution(form=form, user=user, submitted=False) for user in users ] FormDistribution.objects.bulk_create(form_dists) def create_form_distribution(posted_form, user): dist = FormDistribution(form=posted_form, user=user, submitted=False) dist.save() def get_outstanding_forms(): outstanding_form_dict = {} for form in Form.objects.all(): distributions = form.form_to_be_signed.all() outstanding_form_dict.update({form.name: distributions}) return outstanding_form_dict def email_form_notification(request, form, email_list): subject = form.cleaned_data.get("subject") msg_html = render_to_string( "email_templates/post_form_email.html", { "subject": subject, "message": form.cleaned_data.get("notification"), "from": DjangoUser.objects.get(id=request.user.id), }, ) text_content = "You are being notified about something" recipient_list = [ "tyler.iams@gmail.com", "iams.sophia@gmail.com", ] # Will replace with email_list email = EmailMultiAlternatives( subject, text_content, settings.EMAIL_HOST_USER, recipient_list ) email.attach_alternative(msg_html, "text/html") email.attach_file(str(Form.objects.get(name=request.POST.get("notify_about")).form)) email.send() messages.add_message(request, messages.SUCCESS, "Recipients Successfully Emailed") def mark_announcement_dismissed(announcement, user): announcement = AnnouncementDistribution.objects.get( announcement_id=announcement.id, user_id=user.id ) announcement.dismissed = True announcement.save() def mark_notification_acknowledged(notification): notification.acknowledged = True notification.save() def update_session(request, form): session = Session.objects.get(id=request.POST.get("session_id")) if request.POST.get("change_title"): session.title = form.cleaned_data.get("title") messages.add_message(request, messages.SUCCESS, "Session Title Updated") if request.POST.get("change_description"): session.description = form.cleaned_data.get("description") messages.add_message(request, messages.SUCCESS, "Session Description Updated") if request.POST.get("change_lesson_plan"): session.lesson_plan = str(form.cleaned_data.get("lesson_plan")) messages.add_message(request, messages.SUCCESS, "Session Lesson Plan Updated") if request.POST.get("change_activity"): session.activity = str(form.cleaned_data.get("activity")) messages.add_message(request, messages.SUCCESS, "Session Activity Updated") if request.POST.get("change_lecture"): session.lecture = str(form.cleaned_data.get("lecture")) messages.add_message(request, messages.SUCCESS, "Session Lecture Updated") if request.POST.get("change_video"): session.video = str(form.cleaned_data.get("video")) messages.add_message(request, messages.SUCCESS, "Session Video Updated") session.save() def get_class_member_dict(classroom): teacher = get_users_of_type_from_classroom(classroom, "teacher").first() teacher_id = teacher.id teacher_assistant = get_users_of_type_from_classroom( classroom, "teacher_assistant" ).first() teacher_assistant_id = teacher_assistant.id return { "teacher": teacher, "teacher_id": teacher_id, "teacher_assistant": teacher_assistant, "teacher_assistant_id": teacher_assistant_id, "volunteers": get_users_of_type_from_classroom(classroom, "volunteer"), "students": get_users_of_type_from_classroom(classroom, "student"), } def get_course_attendance_statistic(course_id): try: return Classroom.objects.get(id=course_id).attendance_summary.get( "attendance_statistic" ) except AttributeError: return 0.0 def get_my_announcements(request, group): return AnnouncementDistribution.objects.filter( announcement__in=( Announcement.objects.filter( recipient_groups__in=Group.objects.filter(name=group) ) | Announcement.objects.filter( recipient_classrooms__in=[get_classroom_by_django_user(request.user)] ) ), dismissed=False, user_id=request.user ) def get_my_forms(request, group): return FormDistribution.objects.filter( form__in=Form.objects.filter( recipient_groups__in=Group.objects.filter(name=group) ) | Form.objects.filter( recipient_classrooms__in=[get_classroom_by_django_user(request.user)] ), submitted=False, user_id=request.user )
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,734
MissionBit/MB_Portal
refs/heads/master
/tests/test_home.py
from django.test import TestCase, RequestFactory, Client from django.contrib.auth.models import User, AnonymousUser as DjangoUser, AnonymousUser from django.contrib.auth import authenticate from django.urls import reverse from rest_framework import status from django.contrib.messages.storage.fallback import FallbackStorage from home.forms import ContactRegisterForm, UserRegisterForm from home.views import * class BaseTestCase(TestCase): def create_user(self): DjangoUser.objects.create_user( username="testuser", email="test@email.com", first_name="testfirst", last_name="testlast", password="testpassword", ) test_user = authenticate(username="testuser", password="testpassword") return test_user def create_user_change_pwd(self): test_user = self.create_user() test_user.userprofile.change_pwd = True return test_user def create_user_in_group(self, group): test_user = self.create_user() self.add_user_to_group(test_user, group) return test_user def create_user_with_tag(self, tag): test_user = self.create_user() setattr(test_user, "tag", str(tag)) return test_user def add_user_to_group(self, user, group): add_to_group = Group.objects.get(name=group) add_to_group.user_set.add(user) def create_valid_user_and_contact_form( self, username="testuser2", email="test@email.com", firstname="test", lastname="user", ): return { "username": username, "email": email, "first_name": firstname, "last_name": lastname, "password1": "top_secret_123", "password2": "top_secret_123", "birthdate": "01/01/1901", "owner": User.objects.filter(is_active=True).first().id, "title": "Staff", "race": "White", "which_best_describes_your_ethnicity": "Hispanic/Latinx", "gender": "Female", } def create_valid_contact_form(self): return { "first_name": "test_user", "last_name": "test_user", "email": "test@email.com", } def create_change_pwd_form(self): return { "old_password": "testpassword", "new_password1": "new_testpassword123", "new_password2": "new_testpassword123", } class HomeViewsTest(BaseTestCase): databases = "__all__" def test_home_unauthenticated(self): request = RequestFactory().get(reverse("home-home")) request.user = AnonymousUser() response = home(request) response.client = Client() self.assertRedirects( response=response, expected_url=reverse("home-landing_page") + "?next=/home/", status_code=302, target_status_code=200, ) def test_home_authenticated_student(self): self.client.force_login(self.create_user_in_group("student")) response = self.client.get(reverse("home-home")) self.assertRedirects( response=response, expected_url="/student/", status_code=302, target_status_code=200, ) def test_home_authenticated_staff(self): self.client.force_login(self.create_user_in_group("staff")) response = self.client.get(reverse("home-home")) self.assertRedirects( response=response, expected_url="/staff/", status_code=302, target_status_code=200, ) def test_home_authenticated_teacher(self): self.client.force_login(self.create_user_in_group("teacher")) response = self.client.get(reverse("home-home")) self.assertRedirects( response=response, expected_url="/teacher/", status_code=302, target_status_code=200, ) def test_home_authenticated_volunteer(self): self.client.force_login(self.create_user_in_group("volunteer")) response = self.client.get(reverse("home-home")) self.assertRedirects( response=response, expected_url="/volunteer/", status_code=302, target_status_code=200, ) def test_home_authenticated_donor(self): self.client.force_login(self.create_user_in_group("donor")) response = self.client.get(reverse("home-home")) self.assertRedirects( response=response, expected_url="/donor/", status_code=302, target_status_code=200, ) def test_home_user_has_no_group(self): self.client.force_login(self.create_user()) response = self.client.get(reverse("home-home")) self.assertRedirects( response=response, expected_url="/register_after_oauth/", status_code=302, target_status_code=200, ) def test_home_change_pwd(self): self.client.force_login(self.create_user_change_pwd()) response = self.client.get(reverse("home-home")) self.assertRedirects( response=response, expected_url="/change_pwd/", status_code=302, target_status_code=200, ) def test_logout(self): self.client.force_login( DjangoUser.objects.create_user( username="testuser", email="testuser.example.com", password="top_secret" ) ) response = self.client.get(reverse("home-logout")) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.wsgi_request.user.is_authenticated, False) def test_login(self): response = login(RequestFactory()) self.assertEqual(response.status_code, status.HTTP_302_FOUND) def test_landing_page(self): response = self.client.get(reverse("home-landing_page")) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_register_as_student(self): response = self.client.get(reverse("home-register_as_student")) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_change_pwd(self): self.client.force_login(self.create_user_change_pwd()) response = self.client.post( reverse("change_pwd"), self.create_change_pwd_form() ) self.assertEqual(response.url, reverse("home-home")) self.assertEqual(response.status_code, status.HTTP_302_FOUND) response = self.client.post(reverse("change_pwd"), {}) self.assertTemplateUsed(response, template_name="home/change_pwd.html") def test_register_after_oauth(self): self.client.force_login(self.create_user()) response = self.client.post( reverse("home-register_after_oauth"), {"role": "student"} ) self.assertEqual(response.url, reverse("home-home")) self.assertEqual(response.status_code, status.HTTP_302_FOUND) response = self.client.post( reverse("home-register_after_oauth"), {"role": "volunteer"} ) self.assertEqual(response.url, reverse("home-home")) self.assertEqual(response.status_code, status.HTTP_302_FOUND) def test_register_as_student_post(self): self.client.force_login(self.create_user()) response = self.client.post( reverse("home-register_as_student"), self.create_valid_user_and_contact_form(), ) Contact.objects.get(client_id="tesuse19010101").delete() self.assertEqual( DjangoUser.objects.filter(first_name="test").first().first_name, "test" ) self.assertEqual(response.url, reverse("login")) self.assertEqual(response.status_code, status.HTTP_302_FOUND) def test_register_as_student_invalid_form(self): self.client.force_login(self.create_user()) response = self.client.post(reverse("home-register_as_student"), {}) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_register_as_volunteer(self): response = self.client.get(reverse("home-register_as_volunteer")) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_register_as_volunteer_post(self): self.client.force_login(self.create_user()) response = self.client.post( reverse("home-register_as_volunteer"), self.create_valid_user_and_contact_form(), ) Contact.objects.get(client_id="tesuse19010101").delete() self.assertEqual( DjangoUser.objects.filter(first_name="test").first().first_name, "test" ) self.assertEqual(response.url, reverse("login")) self.assertEqual(response.status_code, status.HTTP_302_FOUND) def test_register_as_volunteer_invalid_form(self): self.client.force_login(self.create_user()) response = self.client.post(reverse("home-register_as_volunteer"), {}) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_register_as_donor(self): response = self.client.get(reverse("home-register_as_donor")) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_register_as_donor_post(self): self.client.force_login(self.create_user()) response = self.client.post( reverse("home-register_as_donor"), self.create_valid_user_and_contact_form() ) Contact.objects.get(client_id="tesuse19010101").delete() self.assertEqual( DjangoUser.objects.filter(first_name="test").first().first_name, "test" ) self.assertEqual(response.url, reverse("login")) self.assertEqual(response.status_code, status.HTTP_302_FOUND) def test_register_as_donor_invalid_form(self): self.client.force_login(self.create_user()) response = self.client.post(reverse("home-register_as_donor"), {}) self.assertEqual(response.status_code, status.HTTP_200_OK)
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,735
MissionBit/MB_Portal
refs/heads/master
/tests/test_student.py
from django.test import TestCase, RequestFactory from student.views import * from django.contrib.auth.models import User, Group from django.urls import reverse from rest_framework import status """ class BaseTestCase(TestCase): def create_authenticated_student_user(self): user = User.objects.create_user( username="testuser", email="test@email.com", first_name="testfirst", last_name="testlast", password="beautifulbutterfly125", ) Group.objects.get_or_create(name="student") student_group = Group.objects.get(name="student") student_group.user_set.add(user) return user def create_authenticated_nonstudent_user(self): user = User.objects.create_user( username="otherstafftestuser", email="othertest@email.com", first_name="othertestfirst", last_name="othertestlast", password="beautifulbutterfly125", ) Group.objects.get_or_create(name="staff") staff_group = Group.objects.get(name="staff") staff_group.user_set.add(user) return user class StudentViewsTest(BaseTestCase): def test_student(self): request = RequestFactory().get(reverse("home-home")) request.user = self.create_authenticated_nonstudent_user() response = student(request) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) request.user = self.create_authenticated_student_user() response = student(request) self.assertEqual(response.status_code, status.HTTP_200_OK) """
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,736
MissionBit/MB_Portal
refs/heads/master
/home/urls.py
from django.urls import path, include from . import views urlpatterns = [ path("", views.landing_page, name="home-landing_page"), path("logout/", views.logout_view, name="home-logout"), path("home/", views.home, name="home-home"), path( "register_as_student/", views.register_as_student, name="home-register_as_student", ), path( "register_as_volunteer/", views.register_as_volunteer, name="home-register_as_volunteer", ), path("register_as_donor/", views.register_as_donor, name="home-register_as_donor"), path( "register_after_oauth/", views.register_after_oauth, name="home-register_after_oauth", ), path("login/", include("django.contrib.auth.urls")), path("change_pwd/", views.change_pwd, name="change_pwd"), ]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,737
MissionBit/MB_Portal
refs/heads/master
/staff/views.py
from django.template.defaulttags import register from django.shortcuts import render, redirect from home.decorators import group_required from django.http import HttpResponse, Http404 from home.forms import ( CreateStaffForm, CreateClassroomForm, CreateTeacherForm, CreateVolunteerForm, CreateStudentForm, CreateClassOfferingForm, MakeAnnouncementForm, ChangeTeacherForm, PostFormForm, CreateEsignForm, CollectForms, NotifyUnsubmittedUsersForm, AddCurriculumForm, AddForumForm, AddVolunteerForm, AddStudentForm, ) from .staff_views_helper import * from attendance.views import get_date_from_template_returned_string from home.models.models import Classroom, Form, Esign, Notification, Announcement from django_q.models import Schedule from datetime import datetime from pytz import timezone as tz import os @group_required("staff") def staff(request): if request.method == "POST": if request.POST.get("dismiss_announcement") == "true": mark_announcement_dismissed( Announcement.objects.get(id=request.POST.get("announcement")), request.user, ) return redirect("staff") elif request.POST.get("acknowledge_notification") == "true": mark_notification_acknowledged( Notification.objects.get(id=request.POST.get("notification")) ) return redirect("staff") announcements = get_my_announcements(request, "staff") forms = get_my_forms(request, "staff") notifications = Notification.objects.filter( user_id=request.user.id, acknowledged=False ) return render( request, "staff.html", { "announcements": announcements, "forms": forms, "notifications": notifications, }, ) @group_required("staff") def classroom_management(request): class_dict = {} classroom_list = Classroom.objects.all() for classroom in classroom_list: class_dict.update({classroom.course: get_class_member_dict(classroom)}) return render( request, "classroom_management.html", { "classrooms": classroom_list, "class_dicts": class_dict, "user_groups": set( request.user.groups.all().values_list("name", flat=True) ), }, ) @group_required("staff") def create_staff_user(request): if request.method == "POST": form = CreateStaffForm(request.POST) if form.is_valid(): save_user_to_salesforce(request, form) create_mission_bit_user(request, form, "staff") messages.add_message(request, messages.SUCCESS, "Staff User Created") return redirect("staff") else: return render( request, "create_staff_user.html", { "form": form, "user_groups": set( request.user.groups.all().values_list("name", flat=True) ), }, ) form = CreateStaffForm() return render( request, "create_staff_user.html", { "form": form, "user_groups": set( request.user.groups.all().values_list("name", flat=True) ), }, ) @group_required("staff") def create_teacher_user(request): if request.method == "POST": form = CreateTeacherForm(request.POST) if form.is_valid(): save_user_to_salesforce(request, form) create_mission_bit_user(request, form, "teacher") messages.add_message(request, messages.SUCCESS, "Teacher User Created") return redirect("staff") else: return render(request, "create_teacher_user.html", {"form": form}) form = CreateTeacherForm() return render(request, "create_teacher_user.html", {"form": form}) @group_required("staff") def create_student_user(request): if request.method == "POST": form = CreateStudentForm(request.POST) if form.is_valid(): form.save() create_mission_bit_user(request, form, "student") messages.add_message(request, messages.SUCCESS, "Student User Created") return redirect("staff") else: return render(request, "create_student_user.html", {"form": form}) form = CreateStudentForm() return render(request, "create_student_user.html", {"form": form}) @group_required("staff") def create_volunteer_user(request): if request.method == "POST": form = CreateVolunteerForm(request.POST) if form.is_valid(): save_user_to_salesforce(request, form) create_mission_bit_user(request, form, "volunteer") messages.add_message(request, messages.SUCCESS, "Volunteer User Created") return redirect("staff") else: return render(request, "create_volunteer_user.html", {"form": form}) form = CreateVolunteerForm() return render(request, "create_volunteer_user.html", {"form": form}) @group_required("staff") def create_classroom(request): if request.method == "POST": form = CreateClassroomForm(request.POST) if form.is_valid(): setup_classroom(request, form) messages.success( request, f'{form.cleaned_data.get("course")} Successfully Created' ) return redirect("staff") else: return render(request, "create_classroom.html", {"form": form}) form = CreateClassroomForm() return render(request, "create_classroom.html", {"form": form}) @group_required("staff") def create_class_offering(request): if request.method == "POST": form = CreateClassOfferingForm(request.POST) if form.is_valid(): form.save() messages.add_message( request, messages.SUCCESS, "Successfully Added Class Offering" ) return redirect("staff") else: return render(request, "create_class_offering.html", {"form": form}) form = CreateClassOfferingForm() return render(request, "create_class_offering.html", {"form": form}) @group_required("staff") def make_announcement(request): if request.method == "POST": form = MakeAnnouncementForm(request.POST) if form.is_valid(): form.instance.created_by = DjangoUser.objects.get(id=request.user.id) user_list = get_users_from_form(form) email_list = [user.email for user in user_list] if form.instance.email_recipients: subject = form.cleaned_data.get("title") message = form.cleaned_data.get("announcement") email_announcement(request, subject, message, email_list) announcement = form.save() bulk_distribute_announcement(user_list, announcement) messages.add_message( request, messages.SUCCESS, "Successfully Made Announcement" ) return redirect("staff") else: return render(request, "make_announcement.html", {"form": form}) form = MakeAnnouncementForm( initial={"created_by": DjangoUser.objects.get(id=request.user.id)} ) return render(request, "make_announcement.html", {"form": form}) @group_required("staff") def post_form(request): if request.method == "POST": form = PostFormForm(request.POST, request.FILES) if form.is_valid(): posted_form = Form( name=form.cleaned_data.get("name"), description=form.cleaned_data.get("description"), form=request.FILES["form"], created_by=DjangoUser.objects.get(id=request.user.id), ) if form.cleaned_data.get("esign") is not None: posted_form.esign = form.cleaned_data.get("esign") posted_form.save() posted_form.recipient_groups.set(form.cleaned_data.get("recipient_groups")) posted_form.recipient_classrooms.set( form.cleaned_data.get("recipient_classrooms") ) user_list = get_users_from_form(form) email_list = [user.email for user in user_list] if form.cleaned_data.get("email_recipients"): subject = form.cleaned_data.get("name") message = form.cleaned_data.get("description") email_posted_form( request, form.cleaned_data.get("esign", None), subject, message, posted_form, email_list, ) distribute_forms(request, posted_form, user_list) messages.add_message(request, messages.SUCCESS, "Successfully Posted Form") return redirect("staff") else: return render(request, "post_form.html", {"form": form}) form = PostFormForm( initial={"created_by": DjangoUser.objects.get(id=request.user.id)} ) return render(request, "post_form.html", {"form": form}) @group_required("staff") def form_overview(request): if request.method == "POST": form = CollectForms(request.POST) if form.is_valid(): form_id = Form.objects.get(name=request.POST.get("form_name")) form_distribution = FormDistribution.objects.get( user_id=request.POST.get("user_id"), form_id=form_id ) form_distribution.submitted = form.cleaned_data.get("submitted") form_distribution.save() messages.add_message(request, messages.SUCCESS, "Collected Form") return redirect("form_overview") else: return render(request, "form_overview.html", {"form": form}) outstanding_form_dict = get_outstanding_forms() form = CollectForms() return render( request, "form_overview.html", {"outstanding_form_dict": outstanding_form_dict, "form": form}, ) @group_required("staff") def notify_unsubmitted_users(request, notify_about=None): if request.method == "POST": form = NotifyUnsubmittedUsersForm(request.POST) if form.is_valid(): print("notify_about: ", request.POST.get("notify_about")) form_id = Form.objects.get(name=request.POST.get("notify_about")).id form_distributions = FormDistribution.objects.filter( form_id=form_id, submitted=False ) for form_dist in form_distributions: create_form_notification(request, form, form_dist.user_id) if form.cleaned_data.get("email_recipients"): email_list = get_emails_from_form_distributions(form_distributions) email_form_notification(request, form, email_list) messages.add_message( request, messages.SUCCESS, "Successfully Notified Users" ) return redirect("staff") else: return render(request, "notify_unsubmitted_users.html", {"form": form}) form = NotifyUnsubmittedUsersForm() return render( request, "notify_unsubmitted_users.html", {"form": form, "notify_about": notify_about}, ) @group_required("staff") def create_form_notification(request, form, user_id): notification = Notification( subject=form.cleaned_data.get("subject"), notification=form.cleaned_data.get("notification"), email_recipients=form.cleaned_data.get("email_recipients"), created_by=DjangoUser.objects.get(id=request.user.id), form_id=Form.objects.get(name=request.POST.get("notify_about")).id, user_id=user_id, ) notification.save() @group_required("staff") def communication_manager(request): if request.method == "POST": if request.POST.get("delete_announcement"): Announcement.objects.get(id=request.POST.get("announcement_id")).delete() elif request.POST.get("delete_notification"): Notification.objects.get(id=request.POST.get("notification_id")).delete() elif request.POST.get("delete_form"): Form.objects.get(id=request.POST.get("form_id")).delete() messages.add_message(request, messages.SUCCESS, "Deleted Successfully") return redirect("staff") announcements = Announcement.objects.all() notifications = Notification.objects.all() forms = Form.objects.all() return render( request, "communication_manager.html", { "announcements": announcements, "notifications": notifications, "forms": forms, }, ) @group_required("staff") def create_esign(request): if request.method == "POST": form = CreateEsignForm(request.POST) if form.is_valid(): esign = Esign( name=form.cleaned_data.get("name"), template=form.cleaned_data.get("link"), created_by=DjangoUser.objects.get(id=request.user.id), ) esign.save() messages.add_message( request, messages.SUCCESS, "Esign Created Successfully" ) return redirect("staff") else: return render(request, "create_esign.html", {"form": form}) form = CreateEsignForm( initial={"created_by": DjangoUser.objects.get(id=request.user.id)} ) return render(request, "create_esign.html", {"form": form}) @group_required("staff") def add_forum(request): if request.method == "POST": form = AddForumForm(request.POST) if form.is_valid(): classroom = Classroom.objects.get(id=request.POST.get("classroom")) classroom.forum_title = form.cleaned_data.get("forum_title") classroom.forum = form.cleaned_data.get("forum") classroom.save() messages.add_message(request, messages.SUCCESS, "Forum Added Successfully") return redirect("staff") else: classroom = Classroom.objects.get(id=request.GET.get("classroom")) return render( request, "add_forum.html", {"form": form, "classroom": classroom} ) classroom = Classroom.objects.get(id=request.GET.get("classroom")) form = AddForumForm() return render(request, "add_forum.html", {"form": form, "classroom": classroom}) @group_required("staff") def curriculum(request): classroom = Classroom.objects.get(id=request.GET.get("classroom_id")) sessions = Session.objects.filter(classroom_id=classroom.id).order_by("date") return render( request, "curriculum.html", {"sessions": sessions, "classroom": classroom} ) @group_required("staff") def modify_session(request, date=None, classroom=None): if request.method == "POST": form = AddCurriculumForm(request.POST, request.FILES) if form.is_valid(): update_session(request, form) return redirect("classroom_management") else: date = request.GET.get("date") classroom = Classroom.objects.get(id=request.GET.get("classroom")) session = Session.objects.get( classroom_id=request.GET.get("classroom"), date=get_date_from_template_returned_string(request.GET.get("date")), ) return render( request, "modify_session.html", { "form": form, "date": date, "classroom": classroom, "session": session, }, ) form = AddCurriculumForm() date = date course = Classroom.objects.get(id=classroom) session = Session.objects.get(classroom=classroom, date=date) return render( request, "modify_session.html", {"form": form, "date": date, "classroom": course, "session": session}, ) @group_required("staff") def classroom_detail(request, course_id): if request.method == "POST": if request.POST.get("swap_teacher"): form = ChangeTeacherForm(request.POST) if form.is_valid(): change_classroom_lead( request.POST.get("fmr_teacher", None), form.cleaned_data.get("teacher").id, request.POST.get("course_id", None), "teacher", ) messages.add_message( request, messages.SUCCESS, "Teacher Successfully Changed" ) return redirect("staff") else: return render(request, "classroom_detail.html", {"form": form}) if request.POST.get("swap_teacher_assistant"): form = ChangeTeacherForm(request.POST) if form.is_valid(): change_classroom_lead( request.POST.get("fmr_teacher_assistant", None), form.cleaned_data.get("teacher").id, request.POST.get("course_id", None), "teacher_assistant", ) messages.add_message( request, messages.SUCCESS, "Teacher Assistant Successfully Changed" ) return redirect("staff") else: return render(request, "classroom_detail.html", {"form": form}) if request.POST.get("remove_student"): # Input Validation Needed remove_user_from_classroom( request.POST["fmr_student"], request.POST["course_id"] ) messages.add_message( request, messages.SUCCESS, "Student Successfully Removed From Class" ) return redirect("staff") if request.POST.get("remove_volunteer"): # Input Validation Needed remove_user_from_classroom( request.POST["fmr_volunteer"], request.POST["course_id"] ) messages.add_message( request, messages.SUCCESS, "Volunteer Successfully Removed From Class" ) return redirect("staff") if request.POST.get("add_volunteer"): form = AddVolunteerForm(request.POST) if form.is_valid(): add_user_to_classroom( form.cleaned_data.get("volunteer").id, request.POST["course_id"], "volunteer", ) messages.add_message( request, messages.SUCCESS, "Volunteer Added To Class" ) return redirect("staff") else: return render(request, "classroom_detail.html", {"form": form}) if request.POST.get("add_student"): form = AddStudentForm(request.POST) if form.is_valid(): add_user_to_classroom( form.cleaned_data.get("student").id, request.POST["course_id"], "student", ) messages.add_message( request, messages.SUCCESS, "Student Added To Class" ) return redirect("staff") else: messages.add_message( request, messages.ERROR, "Invalid Form" ) # Need to have fall through here return redirect("staff") classroom = Classroom.objects.get(id=course_id) class_members = get_class_member_dict(classroom) return render( request, "classroom_detail.html", { "change_teacher_form": ChangeTeacherForm(), "add_volunteer_form": AddVolunteerForm(), "add_student_form": AddStudentForm(), "classroom": classroom, "class_members": class_members, }, ) @register.filter def get_item(dictionary, key): return dictionary.get(key)
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,738
MissionBit/MB_Portal
refs/heads/master
/volunteer/urls.py
from django.urls import path from . import views urlpatterns = [path("", views.volunteer, name="volunteer")]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,739
MissionBit/MB_Portal
refs/heads/master
/home/migrations/0004_auto_20190802_0126.py
# Generated by Django 2.2.3 on 2019-08-02 01:26 from django.db import migrations, models import django.db.models.deletion import salesforce.fields class Migration(migrations.Migration): dependencies = [("home", "0003_announcementdistribution")] operations = [ migrations.AddField( model_name="session", name="classroom", field=models.ForeignKey( default=None, on_delete=django.db.models.deletion.CASCADE, related_name="classroom_session", to="home.Classroom", ), ), migrations.AddField( model_name="session", name="date", field=models.DateField(default="1901-01-01"), ), migrations.AlterField( model_name="contact", name="race", field=salesforce.fields.CharField( blank=True, choices=[ ( "American Indian/Alaskan Native", "American Indian/Alaskan Native", ), ("Asian", "Asian"), ("Black/African American", "Black/African American"), ( "Native Hawaiian/Other Pacific Islander", "Native Hawaiian/Other Pacific Islander", ), ("White", "White"), ( "American Indian/Alaskan Native AND Black/African American", "American Indian/Alaskan Native AND Black/African American", ), ( "American Indian/Alaskan Native AND White", "American Indian/Alaskan Native AND White", ), ("Asian AND White", "Asian AND White"), ( "Black/African American AND White", "Black/African American AND White", ), ("Other/Multiracial", "Other/Multiracial"), ], max_length=255, null=True, verbose_name="Which best describes your race?", ), ), migrations.AlterField( model_name="contact", name="which_best_describes_your_ethnicity", field=salesforce.fields.CharField( blank=True, choices=[ ("Hispanic/Latinx", "Hispanic/Latinx"), ("Not Hispanic/Latinx", "Not Hispanic/Latinx"), ], db_column="Which_best_describes_your_ethnicity__c", max_length=255, null=True, verbose_name="Which best describes your ethnicity?", ), ), migrations.CreateModel( name="Resource", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("title", models.TextField(default="No Title", max_length=240)), ("description", models.TextField(max_length=2000)), ("link", models.URLField(default=None, null=True)), ("file", models.FileField(default=None, null=True, upload_to="")), ( "classroom", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="classroom_resource", to="home.Classroom", ), ), ( "session", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="session_resource", to="home.Session", ), ), ], ), ]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,740
MissionBit/MB_Portal
refs/heads/master
/volunteer/views.py
from django.shortcuts import render from home.decorators import group_required @group_required("volunteer") def volunteer(request): return render(request, "volunteer.html")
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,741
MissionBit/MB_Portal
refs/heads/master
/ci/rewrite_sources.py
#!/bin/python """ Rewrite the source code path in coverage.xml to a new value for use by CI. In the container it's always: <sources><source>/code</source></sources> However, the coverage tool for Azure Pipelines needs the path to match the directory outside of the container. """ import sys import xml.etree.ElementTree as ET def main(path, new_sources): tree = ET.parse(path) for elem in tree.findall("sources/source"): elem.text = new_sources tree.write(path) if __name__ == "__main__": main(*sys.argv[1:])
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,742
MissionBit/MB_Portal
refs/heads/master
/teacher/urls.py
from django.urls import path, include from . import views urlpatterns = [ path("", views.teacher, name="teacher"), path("my_class_teacher/", views.my_class_teacher, name="my_class_teacher"), path( "session_view_teacher/", views.session_view_teacher, name="session_view_teacher" ), ]
{"/attendance/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/models/salesforce.py", "/staff/staff_views_helper.py", "/home/generic_notifications.py"], "/home/forms.py": ["/home/models/models.py", "/home/models/salesforce.py", "/home/choices.py"], "/tests/test_volunteer.py": ["/volunteer/views.py"], "/tests/test_staff.py": ["/staff/views.py", "/home/models/models.py", "/home/models/salesforce.py"], "/tests/test_teacher.py": ["/teacher/views.py"], "/home/models/salesforce.py": ["/home/choices.py"], "/home/models/models.py": ["/home/choices.py"], "/home/migrations/0002_add_groups.py": ["/home/models/models.py"], "/student/views.py": ["/home/decorators.py", "/home/models/models.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/views.py": ["/home/forms.py", "/home/models/salesforce.py"], "/home/migrations/0010_auto_20190806_1917.py": ["/home/models/models.py"], "/context_processors.py": ["/staff/staff_views_helper.py"], "/teacher/views.py": ["/home/decorators.py", "/home/models/models.py", "/home/forms.py", "/attendance/views.py", "/staff/staff_views_helper.py"], "/home/apps.py": ["/missionbit/azure_storage_backend.py"], "/staff/staff_views_helper.py": ["/home/models/salesforce.py", "/home/models/models.py"], "/tests/test_home.py": ["/home/forms.py", "/home/views.py"], "/tests/test_student.py": ["/student/views.py"], "/staff/views.py": ["/home/decorators.py", "/home/forms.py", "/staff/staff_views_helper.py", "/attendance/views.py", "/home/models/models.py"], "/volunteer/views.py": ["/home/decorators.py"]}
41,925
1Jayso/Flask_Blog
refs/heads/master
/flaskblog/__init__.py
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_login import LoginManager import flask_whooshalchemy from flask_mail import Mail app = Flask(__name__) app.config['SECRET_KEY'] = 'c2cf55a7b26cf64dbe60700f89c74650' # SQLAlchemy configuration app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db' app.config["DEBUG"] = True app.config['WHOOSH_BASE'] = 'whoosh' db = SQLAlchemy(app) # Flask bcrypt instance login_manager=LoginManager() login_manager.init_app(app) bcrypt = Bcrypt(app) login_manager.login_view = "login" login_manager.login_message_category = "info" mail_settings = { "MAIL_SERVER": 'smtp.gmail.com', "MAIL_PORT": 465, "MAIL_USE_TLS": False, "MAIL_USE_SSL": True, "MAIL_USERNAME":"#", "MAIL_PASSWORD": "#" } app.config.update(mail_settings) mail = Mail(app) from flaskblog import routes
{"/flaskblog/routes.py": ["/flaskblog/__init__.py"], "/run.py": ["/flaskblog/__init__.py"]}
41,926
1Jayso/Flask_Blog
refs/heads/master
/flaskblog/routes.py
import os import secrets from PIL import Image from flask import render_template, url_for, flash, redirect, request, abort import flask_whooshalchemy from flaskblog.forms import LoginForm, RegistrationForm, UpdateAccountForm, PostForm, RequestResetForm, ResetPasswordForm from flaskblog import app, db, bcrypt, mail from flaskblog.models import User, Post from flask_login import login_user, current_user, logout_user, login_required from flask_mail import Message # posts = [ # { # 'author': 'Joseph Sowah', # 'title': 'Blog Post 1', # 'content': 'First post content', # 'date_posted': 'July 19, 2019' # }, # { # 'author': 'John Doe', # 'title': 'Blog Post 2', # 'content': 'Second post content', # 'date_posted': 'July 20, 2019' # } # ] @app.route('/') @app.route('/home') def home(): page = request.args.get('page', 1, type=int) posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5) return render_template('home.html', posts=posts) @app.route('/search') def search(): q = request.args.get('q') page = request.args.get('page', 1, type=int) posts = Post.query.filter(Post.content.contains(q)).paginate(page=page, per_page=5) return render_template('home.html', posts=posts) @app.route('/about') def about(): return render_template('about.html', title='About') @app.route("/register", methods=['GET', 'POST']) def register(): if current_user.is_authenticated: return redirect(url_for('home')) form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8') user = User(username=form.username.data, email=form.email.data, password=hashed_password) db.session.add(user) db.session.commit() flash('Your account has been created! You are now able to log in', 'success') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form) @app.route("/login", methods=['GET', 'POST']) def login(): if current_user.is_authenticated: return redirect(url_for('home')) form = LoginForm() if form.validate_on_submit(): user = User.get_by_email(email=form.email.data) print(user) if user and bcrypt.check_password_hash(user.password, form.password.data): login_user(user, remember=form.remember.data) next_page = request.args.get('next') return redirect(next_page) if next_page else redirect(url_for('home')) else: flash('Login Unsuccessful. Please check email and password', 'danger') return render_template('login.html', title='Login', form=form) @app.route('/logout') def logout(): logout_user() return redirect(url_for('home')) # in python if you want to throw # away a variable or you won't use the variable, # you need to use the underscore def save_picture(form_picture): random_hex = secrets.token_hex(8) _, f_ext = os.path.splitext(form_picture.filename) picture_fn = random_hex + f_ext picture_path = os.path.join(app.root_path, 'static/avatar', picture_fn) img = Image.open(form_picture) img.thumbnail((125, 125)) img.save(picture_path) return picture_fn @app.route("/account", methods=['GET', 'POST']) @login_required def account(): form = UpdateAccountForm() if form.validate_on_submit(): if form.picture.data: picture_file = save_picture(form.picture.data) current_user.image_file = picture_file current_user.username = form.username.data current_user.email = form.email.data db.session.commit() flash('Your account has been updated', 'success') return redirect(url_for('account')) elif request.method == 'GET': form.username.data = current_user.username form.email.data = current_user.email image_file = url_for('static', filename='avatar/' + current_user.image_file) return render_template("account.html", title="Account", image_file=image_file, form=form) @app.route("/post/new", methods=['GET', 'POST']) @login_required def new_post(): form = PostForm() if form.validate_on_submit(): post = Post(title=form.title.data, content=form.content.data, author=current_user) db.session.add(post) db.session.commit() flash('Your Post has been created!', 'success') return redirect(url_for('home')) return render_template('create_post.html', title='New Post', form=form, legend='New Post') @app.route("/post/<int:post_id>") def post(post_id): post = Post.query.get_or_404(post_id) return render_template('post.html', title=post.title, post=post) @app.route("/post/<int:post_id>/update", methods=['GET', 'POST']) @login_required def update_post(post_id): post = Post.query.get_or_404(post_id) if post.author != current_user: abort(403) form = PostForm() if form.validate_on_submit(): post.title = form.title.data post.content = form.content.data db.session.commit() flash('Your post has been updated!', 'success') return redirect(url_for('post', post_id=post.id)) elif request.method == 'GET': form.title.data = post.title form.content.data = post.content return render_template('create_post.html', title='Update Post', form=form, legend='Update Post') @app.route("/post/<int:post_id>/delete", methods=['POST']) @login_required def delete_post(post_id): post = Post.query.get_or_404(post_id) if post.author != current_user: abort(403) db.session.delete(post) db.session.commit() flash('Your post has been deleted!', 'success') return redirect(url_for('home')) @app.route("/user/<string:username>") def user_posts(username): page = request.args.get('page', 1, type=int) user = User.query.filter_by(username=username).first_or_404() posts = Post.query.filter_by(author=user)\ .order_by(Post.date_posted.desc()).paginate(page=page, per_page=2) return render_template('user_posts.html', posts=posts, user=user) def send_reset_email(user): token = user.get_reset_token() msg = Message('Password Reset Request', sender='adodey1@gmail.com', recipients=[user.email]) msg.body = f'''To reset your password, visit the following link: {url_for('reset_token', token=token, _external=True)} If you did not make this request then simply ignore this email and no changes will be made. ''' mail.send(msg) return "Message has been sent!" @app.route("/reset_password", methods=['GET', 'POST']) def reset_request(): if current_user.is_authenticated: return redirect(url_for('home')) form = RequestResetForm() if form.validate_on_submit(): user =User.query.filter_by(email=form.email.data).first() send_reset_email(user) flash("An email hs been sent with instructions to reset password") return redirect(url_for('login')) return render_template('reset_request.html', title='Reset Password', form=form) @app.route("/reset_password/<token>", methods=['GET', 'POST']) def reset_token(token): if current_user.is_authenticated: return redirect(url_for('home')) user = User.verify_reset_token(token) if user is None: flash("That is an invalid or expired token", 'warning') return redirect(url_for('reset_request')) form = ResetPasswordForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8') user.password = hashed_password db.session.commit() flash('Your password has been updated! You are now able to log in', 'success') return redirect(url_for('login')) return render_template('reset_token.html', title='Reset Password', form=form) # About 46% of contributors on tensorflow are based in africa # Google - Research # How machine Learning can help break language barrier in Africa.. Africa is about 2.4Billion # Census is really expensive some of the time the statics are outdated. # Analysis of satellite images # Ai enabled flood forcasting. The app sends a notification whenever there's a chance of flood occurrence # Daibetic retinopathy fastest growing cause of blindess in the continent # Regular screening is key to prevention about 45% suffer vision loss before diagnosis # Deep learning can help analysis images to help i dentify whether a person have diabetic retinopathy # Statistica # Web VR....is an open source web platform where you can expirement with VR. you can code webVR with # HTMl # Issues in VR Ecosystem # Gatekeepers # installs # closed # wrting VR code is complex so mozilla introduced A-frame to help minimze the codes we need to write
{"/flaskblog/routes.py": ["/flaskblog/__init__.py"], "/run.py": ["/flaskblog/__init__.py"]}
41,927
1Jayso/Flask_Blog
refs/heads/master
/run.py
from flaskblog import app # import secrets # secrets.token_hex(16) # The above code is use to generate a secret key(byte string) #! /usr/bin/env python from flask_script import Manager, prompt_bool from flaskblog.models import User, Post from flaskblog import app, db from flask_migrate import Migrate, MigrateCommand migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def insert_data(): joseph = User(username="Jokoto", email="jokoto@example.com", password="test") db.session.add(joseph) # 0241676578 Deborah def add_post(title, content): db.session.add(Post(title=title, content=content, author=joseph)) add_post("Programming Training", "Pluralsight. Hardcore developer training.") add_post("Why I love python", "Python - my favorite language") add_post("Building web apps with flask", "Flask: Web development one drop at a time.") add_post("Reddit", "Reddit. Frontpage of the internet") add_post("SqlAlchemy", "Nice ORM framework") arjen = User(username="arjen", email="arjen@robben.nl", password="test") db.session.add(arjen) db.session.commit() print('Initialized the database') @manager.command def dropdb(): if prompt_bool( "Are you sure you want to lose all your data"): db.drop_all() print('Dropped the database') if __name__ == '__main__': manager.run()
{"/flaskblog/routes.py": ["/flaskblog/__init__.py"], "/run.py": ["/flaskblog/__init__.py"]}
41,935
hackaugusto/django_minifier
refs/heads/master
/minifier/handlers/comment.py
from __future__ import absolute_import from minifier.handlers.base import MinifierBase from minifier.minifier import Minifier class ConditionalCommentMinifier(MinifierBase): def minify(self, elements, name): output = '' minifier = Minifier() for e in elements: conditional = e.get_inlinecontent() output += minifier.minify(conditional,'minifier.minifier.name_mangling') return output
{"/minifier/handlers/comment.py": ["/minifier/handlers/base.py", "/minifier/minifier.py"], "/minifier/handlers/plain.py": ["/minifier/handlers/base.py"], "/minifier/parser/lxml.py": ["/minifier/parser/base.py"], "/minifier/minifier.py": ["/minifier/conf.py"], "/minifier/templatetags/minify.py": ["/minifier/conf.py", "/minifier/minifier.py"], "/minifier/parser/base.py": ["/minifier/conf.py"], "/minifier/handlers/css.py": ["/minifier/handlers/base.py"]}
41,936
hackaugusto/django_minifier
refs/heads/master
/minifier/handlers/plain.py
from __future__ import absolute_import from minifier.handlers.base import MinifierBase class PlainMinifier(MinifierBase): def minify(self, elements, name): output = '' for e in elements: output += e.content() return output
{"/minifier/handlers/comment.py": ["/minifier/handlers/base.py", "/minifier/minifier.py"], "/minifier/handlers/plain.py": ["/minifier/handlers/base.py"], "/minifier/parser/lxml.py": ["/minifier/parser/base.py"], "/minifier/minifier.py": ["/minifier/conf.py"], "/minifier/templatetags/minify.py": ["/minifier/conf.py", "/minifier/minifier.py"], "/minifier/parser/base.py": ["/minifier/conf.py"], "/minifier/handlers/css.py": ["/minifier/handlers/base.py"]}
41,937
hackaugusto/django_minifier
refs/heads/master
/minifier/parser/lxml.py
from __future__ import absolute_import, with_statement import codecs import lxml from lxml import etree from lxml.etree import tostring from lxml.html import fromstring, soupparser from django.core.exceptions import ImproperlyConfigured from minifier.parser.base import ConditionalElementProxy, ElementProxy, ParserBase conditional_regex = ConditionalElementProxy.conditional_regex class CssElement(ElementProxy): def attributes(self): return dict(self._wrap.attrib) def whereis(self): if self._wrap.tag == 'link': return 'file' elif self._wrap.tag == 'style': return 'inline' def filename(self): if self._wrap.tag == 'link': return self.findfile(self._wrap.get('href')) def filecontent(self): if self._wrap.tag == 'link': filename = self.findfile(self._wrap.get('href')) with codecs.open(filename, 'rb', 'utf_8') as fd: return fd.read() def inlinecontent(self): return self._wrap.text class JsElement(ElementProxy): def attributes(self): return dict(self._wrap.attrib) def whereis(self): if self._wrap.get('src') is None: return 'inline' return 'file' def filename(self): return self.findfile(self._wrap.get('src')) def filecontent(self): filename = self.findfile(self._wrap.get('src')) with codecs.open(filename, 'rb', 'utf_8') as fs: return fs.read() def inlinecontent(self): return self._wrap.text class ConditionalCommentElement(ConditionalElementProxy): def attributes(self): match = conditional_regex.search(self._wrap.text) attrs = {} if match: attrs['condition'] = match.group() return attrs def inlinecontent(self): return '<!--' + self._wrap.text + '-->' class PlainElement(ElementProxy): def attributes(self): return {} def whereis(self): return 'inline' def inlinecontent(self): return etree.tostring(self._wrap) class LxmlParser(ParserBase): def parse(self, content): tree = fromstring('<root>%s</root>' % content) try: ignore = tostring(tree, encoding=unicode) except UnicodeDecodeError: tree = soupparser.fromstring(content) return tree def get_mimetypes(self, elements): ordered = [] for elem in elements: tag = elem.tag if elem.tag is etree.Comment: # str(elem) returns the comment start '<!--' and comment end '-->' # elem.text returns without print(str(elem)) if conditional_regex.match(str(elem)): print('conditional') ordered.append( ('application/x-conditional-comment', ConditionalCommentElement(elem)) ) # ignore another comments elif tag == 'style' or (tag == 'link' and elem.get('rel') == 'stylesheet'): ordered.append( ('text/css', CssElement(elem)) ) elif tag == 'script' and (elem.get('language') == None or elem.get('language') == '' or elem.get('language') == 'javascript'): ordered.append( ('application/javascript', JsElement(elem)) ) else: ordered.append( ('text/plain', PlainElement(elem)) ) return ordered def get_mimetypes_grouped(self, elements): mime_group = {} # cant find the comments that have conditionals with xpath for comm in elements.iterchildren(tag=etree.Comment): for conditional in conditional_regex.findall(comm.text): l = mime_group.get('application/x-conditional-comment') or [] l.append(conditional) mime_group['application/x-conditional-comment'] = l css = elements.xpath('/link[@rel="stylesheet"]|style') if len(css) != 0: mime_group['text/css'] = [ CssElement(e) for e in css ] js = elements.xpath('script[not(@language) or @language="" or @language="javascript"]') if len(js) != 0: mime_group['application/js'] = [ JsElement(e) for e in js ] return mime_group
{"/minifier/handlers/comment.py": ["/minifier/handlers/base.py", "/minifier/minifier.py"], "/minifier/handlers/plain.py": ["/minifier/handlers/base.py"], "/minifier/parser/lxml.py": ["/minifier/parser/base.py"], "/minifier/minifier.py": ["/minifier/conf.py"], "/minifier/templatetags/minify.py": ["/minifier/conf.py", "/minifier/minifier.py"], "/minifier/parser/base.py": ["/minifier/conf.py"], "/minifier/handlers/css.py": ["/minifier/handlers/base.py"]}
41,938
hackaugusto/django_minifier
refs/heads/master
/minifier/conf.py
import os from django.conf import settings from appconf import AppConf class CompressorConf(AppConf): DISABLED = settings.DEBUG PARSER = 'minifier.parser.lxml.LxmlParser' MINIFIER_MINIFIERS = ( ('application/javascript', 'minifier.handlers.js.JsMinifier'), ('text/css', 'minifier.handlers.css.CssMinifier'), ('text/plain','minifier.handlers.plain.PlainMinifier'), ('application/x-conditional-comment','minifier.handlers.comment.ConditionalCommentMinifier'), ) CLOSURE_COMPILER_BINARY = 'java -jar compiler.jar' CSSTIDY_BINARY = 'csstidy' CSSTIDY_ARGUMENTS = '--template=highest' YUI_BINARY = 'java -jar yuicompressor.jar' YUI_CSS_ARGUMENTS = '' YUI_JS_ARGUMENTS = '' DATA_URI_MAX_SIZE = 1024 class Meta: prefix = 'minifier'
{"/minifier/handlers/comment.py": ["/minifier/handlers/base.py", "/minifier/minifier.py"], "/minifier/handlers/plain.py": ["/minifier/handlers/base.py"], "/minifier/parser/lxml.py": ["/minifier/parser/base.py"], "/minifier/minifier.py": ["/minifier/conf.py"], "/minifier/templatetags/minify.py": ["/minifier/conf.py", "/minifier/minifier.py"], "/minifier/parser/base.py": ["/minifier/conf.py"], "/minifier/handlers/css.py": ["/minifier/handlers/base.py"]}
41,939
hackaugusto/django_minifier
refs/heads/master
/minifier/minifier.py
from __future__ import absolute_import import os import urllib from md5 import md5 import inspect from django.utils.encoding import smart_unicode from django.utils.importlib import import_module from django.core.exceptions import ImproperlyConfigured from minifier.conf import settings from minifier.utils.decorators import cached_property class Minifier(object): def get_mimetype_minifier(self, mimetype): cls = [ cls for mime, cls in settings.MINIFIER_MINIFIERS if mime == mimetype ][0] if len(cls) == 0: raise ImproperlyConfigured('Missing minifier for %s mimetype.' % mimetype) module, attr = cls.rsplit('.',1) mod = import_module(module) handler = getattr(mod, attr) if not inspect.isclass(handler): raise ImproperlyConfigured('Handler(%s) for "%s" is not a class object' % (cls, mimetype)) return handler() def handle_mimetype(self, mimetype, elements, name=None): minifier = self.get_mimetype_minifier(mimetype) return minifier.minify(elements, name) def get_parser(self): module, attr = settings.MINIFIER_PARSER.rsplit('.',1) mod = import_module(module) parser = getattr(mod, attr) if not inspect.isclass(parser): raise ImproperlyConfigured('Parser(%s) is not a class object' % settings.MINIFIER_PARSER) return parser() def minify(self, content, name): parser = self.get_parser() elements = parser.parse(content) # get all elements of the same mimetype ordered as seen mime_group = {} mime_order = [] for mimetype, element in parser.get_mimetypes(elements): try: mime_group[mimetype].append(element) except KeyError: l = [] l.append(element) mime_group[mimetype] = l if mimetype not in mime_order: if mimetype == 'text/css' and 'application/javascript' in mime_order: mime_order.insert(mime_order.index('application/javascript'),'text/css') # if js is after css, we are good, otherwise the rule above fix it else: mime_order.append(mimetype) # minify the elements minified = '' for mimetype in mime_order: minified += self.handle_mimetype(mimetype, mime_group[mimetype], name); return minified def name_mangling(string): return md5(string).hexdigest()
{"/minifier/handlers/comment.py": ["/minifier/handlers/base.py", "/minifier/minifier.py"], "/minifier/handlers/plain.py": ["/minifier/handlers/base.py"], "/minifier/parser/lxml.py": ["/minifier/parser/base.py"], "/minifier/minifier.py": ["/minifier/conf.py"], "/minifier/templatetags/minify.py": ["/minifier/conf.py", "/minifier/minifier.py"], "/minifier/parser/base.py": ["/minifier/conf.py"], "/minifier/handlers/css.py": ["/minifier/handlers/base.py"]}
41,940
hackaugusto/django_minifier
refs/heads/master
/minifier/minifier/js.py
from itertools import groupby from base import BaseMinifier from minifier.minifier.tool.jsmin import jsmin class Slimit(object): def minify(self, content): try: minify = self._minify except AttributeError: from slimit import minify self._minify = minify minify = self._minify return minify(content) class JsMinifier(MinifierBase): def __init__(sefl): self._minify = Slimit() def minify(self, elements, name=None): output = '' # the scripts tags are grouped with previous sibiling if all the following is met: # - both tags are both inline or in a file # Because if the file is inline it is not intended for reuse, and minifying it together # with the files that _are_ intended for reuse will lead to multiple download of this files # # - if the use of the attributes 'async' or 'defer' match # Because we need to preserve these attributes ... so they cannot be different for origin, el in [ {k,e} for k,e in self.js_group(elements)]: result = self._call_minify(el) #tag = '<script ' + ' '.join([ ''+ for k,v in el.attributes().iteritems() ]) tag = '<script ' # <script defer="defer" async for k,v in el.attributes.iteritems(): if v=='' or v is None: tag += '%s ' % k else: tag += '%s="%s" ' % k,v if origin == 'file': if callable(name): name = name(el) tag += 'src="%s"></script>' % self.save(result, name) else: tag += '>' + result + '</script>' output += tag return output
{"/minifier/handlers/comment.py": ["/minifier/handlers/base.py", "/minifier/minifier.py"], "/minifier/handlers/plain.py": ["/minifier/handlers/base.py"], "/minifier/parser/lxml.py": ["/minifier/parser/base.py"], "/minifier/minifier.py": ["/minifier/conf.py"], "/minifier/templatetags/minify.py": ["/minifier/conf.py", "/minifier/minifier.py"], "/minifier/parser/base.py": ["/minifier/conf.py"], "/minifier/handlers/css.py": ["/minifier/handlers/base.py"]}
41,941
hackaugusto/django_minifier
refs/heads/master
/minifier/parser/autoselect.py
from django.utils.functional import LazyObject from django.utils.importlib import import_module class AutoSelectParser(LazyObject): options = ('minifier.parser.lxml.LxmlParser', 'minifier.parser.htmlparser') def __init__(self): self._wrapped = None for parser in self.options: try: module, attr = parser.rsplit('.',1) mod = import_module(module) parser = getattr(mod, attr) self._wrapped = parser() break except ImportError: continue raise ImportError('Missing parser') def __getattr__(self, name): return getattr(self._wrapped, name)
{"/minifier/handlers/comment.py": ["/minifier/handlers/base.py", "/minifier/minifier.py"], "/minifier/handlers/plain.py": ["/minifier/handlers/base.py"], "/minifier/parser/lxml.py": ["/minifier/parser/base.py"], "/minifier/minifier.py": ["/minifier/conf.py"], "/minifier/templatetags/minify.py": ["/minifier/conf.py", "/minifier/minifier.py"], "/minifier/parser/base.py": ["/minifier/conf.py"], "/minifier/handlers/css.py": ["/minifier/handlers/base.py"]}
41,942
hackaugusto/django_minifier
refs/heads/master
/minifier/templatetags/minify.py
from django import template from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module from minifier.conf import settings from minifier.minifier import Minifier register = template.Library() class MinifierNode(template.Node): def __init__(self, nodelist, name=None): ''' This node parsers the html and compress what it can ''' self.nodelist = nodelist or template.NodeList() # probably dont need this if name is not None: module, attr = name.rsplit('.',1) mod = import_module(module) name= getattr(mod, attr) self.name = name # tries to compile now if there is no other tags # because there is no other tags we can safely give it a {} as context ''' if not self.nodelist.contains_nontext: minifier = Minifier() try: compressed_data = minifier.minify(nodelist.render({}), {}, self.name) except Exception, e: if settings.DEBUG: raise e ''' def render(self, context): rendered = self.nodelist.render(context) #if settings.DEBUG or setting.MINIFY_DISABLED: # return rendered return Minifier().minify(rendered, self.name) @register.tag def minify(parser, token): """ Minify the css and javascript between the tag. The tag groups css files before js, respecting the order that they appear in the document. The tag does not remove conditional comments used by IE Example: {% minify %} <script src="/media/js/one.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8">obj.value = "value";</script> <!--[if IE]> <script type="text/javascript" charset="utf-8">obj.value = "othervalue";</script> <![endif]--> <link rel="stylesheet" href="/media/css/one.css" type="text/css" charset="utf-8"> <link rel="stylesheet" href="/media/css/two.css" type="text/css" charset="utf-8"> <style type="text/css">p { border:5px solid green;}</style> {% minify %} Which would be rendered something like: <link rel="stylesheet" href="/media/CACHE/css/f7c661b7a124.css" type="text/css" media="all" charset="utf-8"> <style type="text/css">p { border:5px solid green;}</style> <script type="text/javascript" src="/media/CACHE/js/3f33b9146e12.js" charset="utf-8"></script> <!--[if IE]> <script type="text/javascript" charset="utf-8">obj.value = "othervalue";</script> <![endif]--> """ args = token.split_contents() if len(args) > 2: raise template.TemplateSyntaxError( "Too many arguments for %r." % args[0]) nodelist = parser.parse(('endminify',)) parser.delete_first_token() if len(args) == 2: name = args[1] else: name = 'minifier.minifier.name_mangling' return MinifierNode(nodelist, name=name)
{"/minifier/handlers/comment.py": ["/minifier/handlers/base.py", "/minifier/minifier.py"], "/minifier/handlers/plain.py": ["/minifier/handlers/base.py"], "/minifier/parser/lxml.py": ["/minifier/parser/base.py"], "/minifier/minifier.py": ["/minifier/conf.py"], "/minifier/templatetags/minify.py": ["/minifier/conf.py", "/minifier/minifier.py"], "/minifier/parser/base.py": ["/minifier/conf.py"], "/minifier/handlers/css.py": ["/minifier/handlers/base.py"]}
41,943
hackaugusto/django_minifier
refs/heads/master
/minifier/parser/base.py
from __future__ import absolute_import import os.path import urllib import re from django.core.files.storage import get_storage_class try: from staticfiles import finders except ImportError: from django.contrib.staticfiles import finders from minifier.conf import settings class ParserBase(object): """ Base parser to be subclassed when creating an own parser. """ def parse(self, content): """ Return an iterable containing the elements inside content """ raise NotImplementedError class ElementProxy(object): def __init__(self, wrap, parser=None): self._wrap = wrap self._parser = parser def attributes(sefl): ''' Must return a dictionary with the attributes and values set on the tag. ''' raise NotImplementedError def whereis(self): ''' Must return 'file' or 'inline' ''' raise NotImplementedError def filename(self): raise NotImplementedError def modified(self): return str(os.path.getmtime(self.filename())) def filecontent(self): ''' If the file is on a file should return its content ''' raise NotImplementedError def inlinecontent(self): ''' Must return the content inside the tag ''' raise NotImplementedError def content(self): ''' Returns the content of the file. This function calls self.inlinecontent() or self.filecontent() depending on self.whereis() ''' if self.whereis() == 'inline': return self.inlinecontent() if self.whereis() == 'file': return self.filecontent() return '' def findfile(self, url): url = urllib.unquote(url).split("?", 1)[0] url = os.path.normpath(url.lstrip('/')) prefix = [ settings.STATIC_URL, settings.MEDIA_URL ] if settings.STATIC_URL[0] == '/': prefix.append(settings.STATIC_URL[1:]) if settings.MEDIA_URL[0] == '/': prefix.append(settings.MEDIA_URL[1:]) path = None for p in prefix: if p in url: length = url.find(p) + len(p) path = url[length:] if path: path = url else: raise Exception('Could not open the file %s' % url) return finders.find(path) class ConditionalElementProxy(ElementProxy): conditional_regex = re.compile('<!--\[if\s+(?P<test>.*?)\s*\]>(?P<content>.*?)<!\[endif\]-->',re.DOTALL) def whereis(self): return 'inline' def get_test(self): return self.conditional_regex.match(self.content()).group('test') def get_inlinecontent(self): return self.conditional_regex.match(self.content()).group('content')
{"/minifier/handlers/comment.py": ["/minifier/handlers/base.py", "/minifier/minifier.py"], "/minifier/handlers/plain.py": ["/minifier/handlers/base.py"], "/minifier/parser/lxml.py": ["/minifier/parser/base.py"], "/minifier/minifier.py": ["/minifier/conf.py"], "/minifier/templatetags/minify.py": ["/minifier/conf.py", "/minifier/minifier.py"], "/minifier/parser/base.py": ["/minifier/conf.py"], "/minifier/handlers/css.py": ["/minifier/handlers/base.py"]}
41,944
hackaugusto/django_minifier
refs/heads/master
/minifier/handlers/base.py
import types import re from itertools import groupby from django.core.files.base import ContentFile from django.core.files.storage import get_storage_class class MinifierBase(object): def minify(self, elements): raise NotImplementedError def _call_minify(self, elements): content = '' for e in elements: content += e.content() return self._minify(content) def resolve_name(self, elements, name): if callable(name): data = '' for e in elements: data += e.filename() data += e.modified() name = name(data) if name is None: raise ValueError('Name was not given.') return name def compressed(self, name): storage = getattr(self,'storage',False) or get_storage_class()() self.storage = storage if storage.exists(name): return self.url_for_file(name) return False def url_for_file(self, name): storage = getattr(self,'storage',False) or get_storage_class()() self.storage = storage return storage.url(name) def save(self, content, name): storage = getattr(self,'storage',False) or get_storage_class()() self.storage = storage # this should never happend if storage.exists(name): raise RuntimeError('Name conflict, ' + name + ' already exists.') storage.save(name, ContentFile(content.encode('utf_8'))) return storage.url(name) def js_properties(self, element): ''' Return a string with the relevant attributes in the tag. The string is used to join the content of 'compatible' scripts, by compatible is meant that scripts with defer and/or async cannont be mixed with script that do not have defer or async. ''' # remove attributes that are not in this list attrs = element.attributes() keys = set() - set(['defer','async','src']) for k in keys: del attrs[k] return attrs def js_group(self, elements, key=None): ''' Return a iterator with the script tags that can be minified together. ''' if key is None: # self.js_properties(x): # js_properties filters the relevant properties from the tag # # .keys(): # for scripts only the propertie's name is relevant # # sorted(): # the order must be equal otherwise the grouping wont work # key = lambda x: ''.join(sorted(self.js_properties(x).keys())) return groupby(elements, key=key) def css_properties(self, element): ''' Return a string with the relevant attributes in the tag. The string is used to join the content of 'compatible' css files, by compatible is meant that css files with different media queries cannont be joined ''' # remove attributes that are not in this list attrs = element.attributes() keys = set() - set(['media','scoped','href']) for k in keys: del attrs[k] return attrs def css_group(self, elements, key=None): ''' Return a iterator with the script tags that can be minified together. ''' if key is None: def key(x): output = [] # using list because we sort the attributes # css_properties filters the relevant properties from the tag attrs = self.css_properties(x) # cant group different media queries for k,v in attrs.iteritems(): if k == 'media': output.append(re.sub('\s','',k+v)) else: output.append(k) # the order must be equal otherwise the grouping wont work return ''.join(sorted(output)) return groupby(elements, key=key)
{"/minifier/handlers/comment.py": ["/minifier/handlers/base.py", "/minifier/minifier.py"], "/minifier/handlers/plain.py": ["/minifier/handlers/base.py"], "/minifier/parser/lxml.py": ["/minifier/parser/base.py"], "/minifier/minifier.py": ["/minifier/conf.py"], "/minifier/templatetags/minify.py": ["/minifier/conf.py", "/minifier/minifier.py"], "/minifier/parser/base.py": ["/minifier/conf.py"], "/minifier/handlers/css.py": ["/minifier/handlers/base.py"]}
41,945
hackaugusto/django_minifier
refs/heads/master
/minifier/handlers/css.py
from __future__ import absolute_import from itertools import groupby from minifier.handlers.base import MinifierBase class Cssmin(object): def minify(self, content): try: minify = self._minify except AttributeError: from cssmin import cssmin self._minify = cssmin minify = self._minify return minify(content) class CssMinifier(MinifierBase): def __init__(self): self._minify = Cssmin().minify def minify(self, elements, name): output = '' # the scripts tags are grouped with previous sibiling if all the following is met: # - both tags are both inline or in a file # Because if the file is inline it is not intended for reuse, and minifying it together # with the files that _are_ intended for reuse will lead to multiple download of this files # # - if the use of the attributes 'async' or 'defer' match # Because we need to preserve these attributes ... so they cannot be different for group in [ list(v) for k,v in self.css_group(elements)]: name = self.resolve_name(elements, name) + '.css' if not self.compressed(name): result = self._call_minify(group) one = group[0] if one.whereis() == 'file': tag = '<link ' else: tag = '<style ' # <tag media="print" scoped properties = self.css_properties(one) if properties['href'] is not None: del properties['href'] for k,v in properties.iteritems(): if v=='' or v is None: tag += '%s ' % k else: tag += '%s="%s" ' % (k,v) if one.whereis() == 'file': url = self.compressed(name) if not url: tag += 'href="%s" />' % self.save(result, name) else: tag += 'href="%s" />' % url else: tag += '>' + result + '</style>' output += tag return output
{"/minifier/handlers/comment.py": ["/minifier/handlers/base.py", "/minifier/minifier.py"], "/minifier/handlers/plain.py": ["/minifier/handlers/base.py"], "/minifier/parser/lxml.py": ["/minifier/parser/base.py"], "/minifier/minifier.py": ["/minifier/conf.py"], "/minifier/templatetags/minify.py": ["/minifier/conf.py", "/minifier/minifier.py"], "/minifier/parser/base.py": ["/minifier/conf.py"], "/minifier/handlers/css.py": ["/minifier/handlers/base.py"]}
41,946
DMOON510/TreeHacks2020
refs/heads/master
/museum.py
import random import numpy as np def recommend(galleries, visitor): for i in range(len(visitor.preference)): visitor.score[i]= 0.5 * len(galleries[i].visitors) + visitor.preference[galleries[i].name] visitor.score_np[i] = np.asarray(visitor.score[i]) visitor.recommendation = visitor.score_np.argmax() def like(visitor): for i in range(len(visitor.preference)): visitor.preference[i] = random.randrange(1, 5, 1) class visitor(object): """A visitor who visits a museum. Receive a recommmedation of a gallery""" def __init__(self, gallery=None): self.preference = [0, 0, 0, 0, 0] self.has_visited = [] self.score = [0,0,0,0,0] self.score_np = np.asarray(self.score) self.recommendation = self.score_np.argmax() self.gallery = gallery def move_to(self, gallery): self.gallery.remove_visitor(self) gallery.add_visitor(self) self.has_visited += gallery def __repr__(self): return self class gallery(object): """there are five exhibit in total and each has indicator of crowdness""" def __init__(self, name, crowdness=1): self.name = name self.crowdness = crowdness self.visitors = [] def add_visitor(self, visitor): self.visitors.append(visitor) visitor.current_visiting = self def remove_visitor(self, visitor): self.vistiors.remove(visitor) visitor.gallery = None def __str__(self): return self
{"/museumcreate.py": ["/museum.py"]}
41,947
DMOON510/TreeHacks2020
refs/heads/master
/museumcreate.py
from museum import * import pandas as pd gallery1= gallery(0,100) gallery2 = gallery(1,50) gallery3 = gallery(2, 25) gallery4 = gallery(3, 80) gallery5 = gallery(4, 50) galleries = [gallery1, gallery2, gallery3, gallery4, gallery5] cols = ['preference','score','recommendation'] lst = [] visitors = {} for i in range(100): visitors[i] = visitor() like(visitors[i]) recommend(galleries, visitors[i]) pref = ",".join(visitors[i].preference) score = ",".join(visitors[i].score) rec = visitors[i].recommendation lst.append([pref,score,rec]) df = pd.DataFrame(lst, columns=cols)
{"/museumcreate.py": ["/museum.py"]}
41,958
rnaimehaom/deepmol
refs/heads/master
/model/mpnn.py
import tensorflow as tf import numpy as np from .message_passing import MatrixMessagePassing, VectorMessagePassing, ConvFilterGenerator from .update_function import GRUUpdate from .read_out import Set2Vec, ConcatReadOut from .fc_nn import FullyConnectedNN from .abstract_model import Model class MPNN(Model): """Message Passing Neural Network. Creates a vector embedding of the entire molecule and maps it to the molecule properties. Behaves mostly like the model described by Gilmer et al. :param hparams: hyperparameters, as a tf.contrib.training.HParams object :param output_dim: output dimension of the network. for prediction, the number of properties to be learned at once. If None, the output network will be omitted and the vector embedding of the molecule is returned. """ def __init__(self, hparams, output_dim=None): super(MPNN, self).__init__(hparams) self.output_dim = output_dim self.filter_gen = ConvFilterGenerator(hparams) if hparams.use_set2vec: self.read_out = Set2Vec(hparams) else: self.read_out = ConcatReadOut(hparams) # If weight tying is enabled, the message passing and update models are re-used throughout the forward pass. if hparams.weight_tying: self._message_passing = MatrixMessagePassing( hparams) if hparams.use_matrix_filters else VectorMessagePassing(hparams) self._update = GRUUpdate(hparams) @property def message_passing(self): """Return the message passing model. If weight tying is disabled, create a new one, else reuse.""" if self.hparams.weight_tying: return self._message_passing else: return MatrixMessagePassing(self.hparams) if self.hparams.use_matrix_filters else VectorMessagePassing( self.hparams) @property def update(self): """Return the update function model. If weight tying is disabled, create a new one, else reuse.""" if self.hparams.weight_tying: return self._update else: return GRUUpdate(self.hparams) def _forward(self, molecules): """Forward pass of the message passing neural network. :param molecules: batch of molecules as a TFMolBatch objects :return: tensor of predicted properties or molecule embedding vector, as specified by output_dim. """ # zero-pad up to hidden state dimension num_atom_features = molecules.atoms.get_shape()[2].value with tf.control_dependencies([tf.assert_less_equal(num_atom_features, self.hparams.hidden_state_dim)]): hidden_states = tf.pad(molecules.atoms, [[0, 0], [0, 0], [0, self.hparams.hidden_state_dim - num_atom_features]]) filters = self.filter_gen.forward(molecules.distance_matrix) # perform message passing for i in range(self.hparams.num_propagation_steps): messages = self.message_passing.forward(hidden_states, filters) hidden_states = self.update.forward(hidden_states, messages, molecules.mask) # read-out features_and_states = [molecules.atoms, hidden_states] features_and_states = tf.concat(features_and_states, axis=2, name="atoms_concat") mol_embedding = self.read_out.forward(features_and_states, mask=molecules.mask) if self.output_dim is None: return mol_embedding # map vector embedding of the entire molecule to the output layer_dims = np.ones(self.hparams.mpnn_out_hidden_layers + 1) * self.hparams.mpnn_out_hidden_dim layer_dims[-1] = self.output_dim # output dim activation = tf.nn.leaky_relu if self.hparams.use_leaky_relu else tf.nn.relu fc_nn = FullyConnectedNN(self.hparams, layer_dims=layer_dims, activation=activation, output_activation=None) output = fc_nn.forward(mol_embedding) return output @staticmethod def default_hparams(): """Return a tf.contrib.training.HParams with the default hyperparameter configuration.""" return tf.contrib.training.HParams( num_propagation_steps=3, mpnn_out_hidden_layers=1, mpnn_out_hidden_dim=200, filter_hidden_layers=4, filter_hidden_dim=50, use_matrix_filters=True, # otherwise use vector use_set2vec=True, set2vec_steps=6, set2vec_num_attention_heads=1, hidden_state_dim=70, use_leaky_relu=True, weight_tying=True, batch_size=30, learning_rate=2.8e-4, lr_decay_rate=0.945, lr_decay_steps=100000, )
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,959
rnaimehaom/deepmol
refs/heads/master
/model/molvae.py
from .mpnn import MPNN import numpy as np from scipy.special import comb import tensorflow as tf from .fc_nn import FullyConnectedNN from data.molecules import TFMolBatch class MolVAE: """A molecular geometry-based variational autoencoder. Also usable as autoencoder by setting the hyperparameter "variational" to False. The encoder is based on the message passing phase of an MPNN. The decoder is based on a fully-connected neural network. Atom types and geometry are each predicted by a separate output layer on top of multiple shared network layers. :param hparams: hyperparameters, as a tf.contrib.training.HParams object :param max_num_atoms: Maximum number of atoms in a molecule. (Smaller molecules are zero-padded.) :param num_atom_types: Number of atom types (including "none/padded"). """ def __init__(self, hparams, max_num_atoms, num_atom_types): self.prior = tf.contrib.distributions.MultivariateNormalDiag(tf.zeros(hparams.latent_dim)) self.encode = tf.make_template('Encoder', self._encode) self.decode = tf.make_template('Decoder', self._decode) self.reconstruct = tf.make_template('Reconstruct', self._reconstruct) self.num_atom_types = num_atom_types self.max_num_atoms = max_num_atoms self.atom_out_dim = max_num_atoms * num_atom_types self.distances_out_dim = int(max_num_atoms * (max_num_atoms - 1) / 2) # = 1+2+3+...+(num_nodes - 1) self.hparams = hparams def _encode(self, mols): """Encoder, applies a neural network to the concatenation of the hidden atom states after message passing. :param mols: batch of molecules as a TFMolBatch object :return: multivariate normal distribution in latent space. """ mpnn = MPNN(self.hparams, output_dim=None) h_concat = mpnn.forward(mols) # output network layer_dims = np.ones(self.hparams.encoder_out_hidden_layers) * self.hparams.encoder_out_hidden_dim activation = tf.nn.leaky_relu if self.hparams.use_leaky_relu else tf.nn.relu fc_nn = FullyConnectedNN(self.hparams, layer_dims, activation=activation, output_activation=activation) h_concat = fc_nn.forward(h_concat) loc = tf.layers.dense(h_concat, self.hparams.latent_dim, name='latent_mean') scale = tf.layers.dense(h_concat, self.hparams.latent_dim, tf.nn.softplus, # softplus -> positive values name='latent_variance', trainable=self.hparams.variational) + 1e-5 return tf.contrib.distributions.MultivariateNormalDiag(loc, scale) def _decode(self, z): """ Decode a batch of latent vectors back to molecules. :param z: batch of latent vectors of shape [batch_size, latent_dim] :return: TFMolBatch of decoded molecules """ # shared layers: layer_dims = np.ones(self.hparams.decoder_hidden_layers) * self.hparams.decoder_hidden_dim activation = tf.nn.leaky_relu if self.hparams.use_leaky_relu else tf.nn.relu fc_nn = FullyConnectedNN(self.hparams, layer_dims, activation=activation, output_activation=activation) z = fc_nn.forward(z) # output layer for atom reconstruction atom_logits = tf.layers.dense(z, self.atom_out_dim) batch_size = tf.shape(z)[0] atom_matrix_logits = tf.reshape(atom_logits, [batch_size, self.max_num_atoms, self.num_atom_types]) if self.hparams.coordinate_output: coordinates = tf.layers.dense(z, 3 * self.max_num_atoms) coordinates = tf.reshape(coordinates, [batch_size, self.max_num_atoms, 3], name='coordinates') decoded_mols = TFMolBatch(atoms_logits=atom_matrix_logits, coordinates=coordinates) else: edges = tf.layers.dense(z, self.distances_out_dim, tf.nn.softplus) # softplus ensures positivity decoded_mols = TFMolBatch(atoms_logits=atom_matrix_logits, distances=edges) return decoded_mols def calculate_loss(self, mols): """Perform forward pass and calculate the loss (negative ELBO) for the given molecule batch. If hparams.variational is False, only the reconstruction loss is accounted for. If hparams.coordinate_output is False (thus, distances are output): To penalize violations of the triangle inequality, an additional geometric penalty term is added, weighted by hparams.geometric_penalty_weight. :param mols: batch of molecules as a TFMolBatch object :return: loss tensor """ posterior = self.encode(mols) if self.hparams.variational: z = posterior.sample() else: z = posterior.mean() decoded_mols = self.decode(z) with tf.name_scope('loss'): loss = self.reconstruction_loss(mols, decoded_mols) if not self.hparams.coordinate_output: geom_penalty = self.geometric_penalty(decoded_mols) tf.summary.scalar('geom_penalty', geom_penalty) loss += geom_penalty * self.hparams.geometric_penalty_weight if self.hparams.variational: kl_divergence = tf.reduce_mean(tf.distributions.kl_divergence(posterior, self.prior)) tf.summary.scalar('kl_divergence', kl_divergence) loss += kl_divergence * self.hparams.beta return loss def _reconstruct(self, mols): """Forward pass through the (variational) autoencoder. :param mols: batch of molecules as a TFMolBatch object :return: TFMolBatch of reconstructed molecules """ posterior = self.encode(mols) if self.hparams.variational: z = posterior.sample() else: z = posterior.mean() decoded_mols = self.decode(z) return decoded_mols def _get_triangle_sets_and_weights(self, decoded_mols): """Extract triplets for triangle inequality and the respective existence probabilities of all involved atoms. To calculate the geometric penalty, the triangle inequality needs to be checked for all sets of three atoms. Additionally, the penalty is weighted by the existence probability of the involved atoms since violations by zero-padded atoms are irrelevant. :param decoded_mols: TFMolBatch of decoded molecules :return: - triangle_sets: distance values [d_ij, d_ik, d_jk] for all i<j<k, shaped [batch_size, num_sets, 3] - weights: joint existence probability of each set, shaped [batch_size, num_sets] """ decoded_mask = 1 - decoded_mols.atoms[:, :, -1] # existence probability of atom = 1 - p(type=None) # compile indices to extract/collect num_sets = comb(self.max_num_atoms, 3, exact=True) # number of sets of three atoms weight_indices = np.zeros([num_sets, 3, 1]) set_indices = np.zeros([num_sets, 3, 2]) # num_sets, elements per set, indices in matrix set_counter = 0 for i in range(self.max_num_atoms): # iterate over all relevant sets of three atoms for j in range(i + 1, self.max_num_atoms): for k in range(j + 1, self.max_num_atoms): set_indices[set_counter] = [[i, j], [i, k], [j, k]] weight_indices[set_counter, :] = [[i], [j], [k]] set_counter += 1 with tf.name_scope('triangle_sets'): # add batch dimension batch_size = tf.shape(decoded_mols.distances)[0] batch_indices = tf.range(batch_size, dtype=tf.int32) batch_indices = tf.tile(tf.reshape(batch_indices, [batch_size, 1, 1, 1]), [1, num_sets, 3, 1]) set_indices = tf.tile(set_indices, [batch_size, 1, 1]) set_indices = tf.reshape(set_indices, [batch_size, num_sets, 3, 2]) set_indices = tf.to_int32(set_indices) set_indices = tf.concat([batch_indices, set_indices], axis=-1) weight_indices = tf.tile(weight_indices, [batch_size, 1, 1]) weight_indices = tf.reshape(weight_indices, [batch_size, num_sets, 3, 1]) weight_indices = tf.to_int32(weight_indices) weight_indices = tf.concat([batch_indices, weight_indices], axis=-1) # collect relevant elements triangle_sets = tf.gather_nd(params=decoded_mols.distance_matrix, indices=set_indices) weights = tf.gather_nd(params=decoded_mask, indices=weight_indices) weights = tf.reduce_prod(weights, axis=-1) # joint probability return triangle_sets, weights def geometric_penalty(self, decoded_mols): """Calculate a penalty term for violations of the triangle inequality. :param decoded_mols: TFMolBatch of decoded molecules :return: tensor specifying the geometric penalty, summed over atoms, averaged over the batch """ with tf.name_scope('geom_penalty'): sets, weights = self._get_triangle_sets_and_weights(decoded_mols) violations = 2 * tf.reduce_max(sets, axis=-1) - tf.reduce_sum(sets, axis=-1) violations = tf.maximum(violations, 0) weighted_violations = violations * weights geom_penalty = tf.reduce_sum(weighted_violations, axis=1) # sum over atoms in each molecule geom_penalty = tf.reduce_mean(geom_penalty) # average over batch return geom_penalty def reconstruction_loss(self, mols, decoded_mols): """Compute the reconstruction loss between original and decoded molecule. Atoms are compared using softmax cross entropy, distances using mean squared error. Distances are weighted by the probability that both involved atoms exist in both reconstruction and original. :param mols: TFMolBatch of original molecules :param decoded_mols: TFMolBatch of decoded molecules :return: Reconstruction loss tensor """ with tf.name_scope('rec_loss'): atom_loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=mols.atoms, logits=decoded_mols.atoms_logits) atom_loss = tf.reduce_sum(atom_loss, axis=1) # sum over atoms in each molecule atom_loss = tf.reduce_mean(atom_loss) # average over batch dist_weights = self._generate_dist_weights(mols, decoded_mols) reduction = tf.losses.Reduction.MEAN # sum over batch and atoms and divide by sum of weights distance_loss = tf.losses.mean_squared_error(mols.distances, decoded_mols.distances, weights=dist_weights, reduction=reduction) tf.summary.scalar('atom_loss', atom_loss) tf.summary.scalar('mask_sum', tf.reduce_mean(tf.reduce_sum(dist_weights, axis=1))) tf.summary.scalar('distance_loss', distance_loss) reconstruction_loss = self.hparams.gamma * tf.cast(atom_loss, tf.float32) reconstruction_loss += (2 - self.hparams.gamma) * distance_loss return reconstruction_loss def sample(self, num_samples): """Sample molecules from the latent prior. :param num_samples: The number of molecules to sample. :return: TFMolBatch of sampled molecules """ z_values = self.prior.sample(num_samples) mols = self.decode(z_values) return mols def _generate_dist_weights(self, mols, decoded_mols, extract_upper_triangle=True): """Generate weights for all distance values, based on the existence probability of the involved atoms. When comparing molecules, it is meaningless to compare distances between atoms that only exist in one of them. Therefore, each distance between two atoms is weighted by the existence probability of the involved atoms. :param mols: TFMolBatch of original molecules :param decoded_mols: TFMolBatch of decoded molecules :param extract_upper_triangle: If True, the relevant entries of the distance matrix (upper triangle) are extracted and flattened. Else, the weights have the shape of the distance matrix. :return: Weights, in the form specified by extract_upper_triangle. """ with tf.name_scope('distance_weights'): decoded_dist_weights = tf.reshape(decoded_mols.mask, [-1, self.max_num_atoms, 1]) * tf.reshape( decoded_mols.mask, [-1, 1, self.max_num_atoms]) label_dist_weights = tf.reshape(mols.mask, [-1, self.max_num_atoms, 1]) label_dist_weights *= tf.reshape(mols.mask, [-1, 1, self.max_num_atoms]) combined_dist_weights = decoded_dist_weights * tf.cast(label_dist_weights, tf.float32) if extract_upper_triangle: # create TFMolBatch for the conversion between distance matrix -> distances dummy_atoms = mols.atoms # irrelevant, but required parameter dummy_mols = TFMolBatch(atoms=dummy_atoms, distance_matrix=combined_dist_weights) flattened_dist_weights = dummy_mols.distances return flattened_dist_weights return combined_dist_weights @staticmethod def default_hparams(): """Return a tf.contrib.training.HParams with the default hyperparameter configuration.""" hparams = MPNN.default_hparams() hparams.set_hparam('learning_rate', 6.25e-4) hparams.set_hparam('use_set2vec', False) hparams.set_hparam('hidden_state_dim', 110) hparams.add_hparam('latent_dim', 64) # dimension of latent space hparams.add_hparam('encoder_out_hidden_dim', 100) # of the network mapping to hidden states to latent space hparams.add_hparam('encoder_out_hidden_layers', 2) # of the network mapping to hidden states to latent space hparams.add_hparam('decoder_hidden_dim', 200) # for shared layers of decoder network hparams.add_hparam('decoder_hidden_layers', 5) # for shared layers of decoder network hparams.add_hparam('variational', True) # use as VAE as opposed to a regular autoencoder hparams.add_hparam('coordinate_output', False) # output coordinates instead of distances hparams.add_hparam('geometric_penalty_weight', 0.0) # penalize violations of the triangle inequality hparams.add_hparam('gamma', 8e-3) # relative weight on distance vs atom reconstruction hparams.add_hparam('beta', 1e-3) # weight on kl_div term, as in a beta-VAE return hparams
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,960
rnaimehaom/deepmol
refs/heads/master
/data/molecules.py
import numpy as np import tensorflow as tf import logging import pybel from sklearn.manifold import MDS class AbstractMol: """Abstract class for geometry-encoded molecules that offer internal format conversion. The geometry can be represented by coordinates, distance matrix or a flattened vector of the relevant distances. If only one representation is provided, but another one is called, conversion is done internally, as defined in the concrete subclass. If multiple representations are provided at construction, no cross-validation is performed. Exact requirements for parameters are specified in the subclasses. :param atoms: An encoding of the atom types in the molecule. :param distances: the n(n-1)/2 relevant entries of the distance matrix as a flattened tensor :param distance_matrix: matrix specifying the interatomic distances :param coordinates: cartesian coordinates of the atoms :param labels: ndarray of training labels for property prediction :raises ValueError: If distances, distance matrix and coordinates are all missing. """ def __init__(self, atoms, distances=None, distance_matrix=None, coordinates=None, labels=None): if all([distances is None, distance_matrix is None, coordinates is None]): raise ValueError('Either distances, distance_matrix or coordinates need to be specified.') self.atoms = atoms self._distances = distances self._distance_matrix = distance_matrix self._coordinates = coordinates self._labels = labels @property def distance_matrix(self): """If necessary and possible, it will be generated from distances or coordinates.""" if self._distance_matrix is None: self._generate_distance_matrix() return self._distance_matrix @property def distances(self): """If necessary and possible, it will be generated from distance matrix or coordinates.""" if self._distances is None: self._generate_distances() return self._distances @property def coordinates(self): """If necessary and possible, they will be generated from the distance matrix.""" if self._coordinates is None: self._generate_coordinates() return self._coordinates @property def labels(self): """Return labels if provided at construction. :raises AttributeError: If labels have not been provided at construction. """ if self._labels is None: raise AttributeError('Labels have not been provided and can not be generated.') return self._labels def _generate_distance_matrix(self): raise NotImplementedError('Must be implemented in child class') def _generate_distances(self): raise NotImplementedError('Must be implemented in child class') def _generate_coordinates(self): raise NotImplementedError('Must be implemented in child class') class TFMolBatch(AbstractMol): """Holds TensorFlow tensors representing an entire batch of molecules. Different representations of the geometry of the molecule (distance matrix, flattened distances, coordinates) are available and internally converted on request. All operations are performed on the whole batch. At least one representation is required for atoms and geometry each. :param atoms: tensor holding atom features, shaped [batch_size, num_atoms, num_atom_features] :param atoms_logits: tensor holding logits of the atom features, shaped [batch_size, num_atoms, num_atom_features]. atoms are generated from atoms_logits, but not the other way round. :param mask: indicates whether an atom is actually present (1) or zero-padded (0), shaped [batch_size, num_atoms] :param distances: tensor of relevant entries in the distance matrix [batch_size, n(n-1)/2] :param distance_matrix: distance matrices of all molecules in the batch, shaped [batch_size, n, n] :param coordinates: coordinates of all atoms in each molecule in the batch, shaped [batch_size, n, 3] :param labels: ndarray of training labels, shaped [batch_size, num_properties] :raises ValueError: If no representation for atoms or geometry is provided. """ def __init__(self, atoms=None, atoms_logits=None, mask=None, distances=None, distance_matrix=None, coordinates=None, labels=None): if atoms is None: if atoms_logits is None: raise ValueError('Either atoms or atoms_logits need to be provided.') else: atoms = tf.nn.softmax(atoms_logits) self.atoms_logits = atoms_logits self._mask = mask super(TFMolBatch, self).__init__(atoms, distances, distance_matrix, coordinates, labels) @property def mask(self): """ Return the mask. If necessary, it will be generated from the values for atom type NONE. """ if self._mask is None: self._generate_mask() return self._mask def _generate_mask(self): self._mask = 1 - self.atoms[:, :, -1] def _generate_coordinates(self): """Coordinates can not be generated from distance matrix or distances.""" raise AttributeError('Coordinates have not been provided and can not be generated.') def _generate_distances(self): """Generate the flattened distances from either distance matrix or coordinates. :raises AttributeError: if neither distance matrix nor coordinates are given. """ if self._distance_matrix is not None: self._distance_matrix_to_distances() elif self._coordinates is not None: self._coordinates_to_distances() else: raise AttributeError('Could not generate distances: Neither distance matrix nor coordinates are given.') def _distance_matrix_to_distances(self): """Generate flattened distance vector from distance matrix using tf.gather_nd""" # To use tf.gather_nd, we need to specify indices we want to extract from the input matrix. # Numpy provides us with the indices of the upper triangle of a 2D matrix. -> [row, column] num_atoms = self.atoms.get_shape()[1].value upper_triangle_indices = np.dstack(np.triu_indices(num_atoms, 1)).reshape([-1, 2]) num_matrix_elements = upper_triangle_indices.shape[0] with tf.name_scope('dist_matrix_to_dist'): # Due to the additional batch dimension, the input matrix is a 3D matrix. Thus, the specified indices need # to be of the form [batch_element, row, column]. # At first, we provide one set of upper triangle indices for each element in the batch. batch_size = tf.shape(self.distance_matrix)[0] tiled_indices = tf.tile(upper_triangle_indices, [batch_size, 1]) tiled_indices = tf.reshape(tiled_indices, [batch_size, num_matrix_elements, 2]) tiled_indices = tf.to_int32(tiled_indices) # Then, we add the batch index everywhere batch_indices = tf.range(batch_size, dtype=tf.int32) batch_indices = tf.tile(tf.reshape(batch_indices, [batch_size, 1]), [1, num_matrix_elements]) batch_indices = tf.expand_dims(batch_indices, 2) all_indices = tf.concat([batch_indices, tiled_indices], axis=2) self._distances = tf.gather_nd(params=self.distance_matrix, indices=all_indices) def _generate_distance_matrix(self): """Generate distance matrix from flattened vector of interatomic distances using tf.gather_nd.""" distances = self.distances # property call ensures that distances has been generated num_atoms = self.atoms.get_shape()[1].value upper_triangle_indices = np.dstack(np.triu_indices(num_atoms, 1)).reshape([-1, 2]) inverse_indices = np.zeros([num_atoms, num_atoms]) for i, indices in enumerate(upper_triangle_indices): inverse_indices[indices[0], indices[1]] = i inverse_indices[indices[1], indices[0]] = i with tf.name_scope('dist_to_dist_matrix'): batch_size = tf.shape(distances)[0] tiled_indices = tf.tile(inverse_indices, [batch_size, 1]) tiled_indices = tf.reshape(tiled_indices, [batch_size, num_atoms, num_atoms, 1]) tiled_indices = tf.to_int32(tiled_indices) batch_indices = tf.range(batch_size, dtype=tf.int32) batch_indices = tf.reshape(batch_indices, [batch_size, 1]) batch_indices = tf.tile(batch_indices, [1, num_atoms ** 2]) batch_indices = tf.reshape(batch_indices, [batch_size, num_atoms, num_atoms, 1]) all_indices = tf.concat([batch_indices, tiled_indices], axis=-1) distance_matrix = tf.gather_nd(params=distances, indices=all_indices) # set diagonal to zero mask = tf.ones([num_atoms, num_atoms]) - tf.eye(num_atoms) self._distance_matrix = distance_matrix * mask def _coordinates_to_distances(self): """Generate flattened distance vector from coordinates.""" # first gather all pairs of points using tf.gather_nd() with tf.name_scope('coord_to_dist'): batch_size = tf.shape(self.coordinates)[0] num_atoms = self.atoms.get_shape()[1].value num_distances = int(num_atoms * (num_atoms - 1) / 2) indices = np.zeros([num_distances, 2, 3, 2]) # dist, 2 points to compare, xyz, indices in coordinates counter = 0 for i in range(num_atoms): for j in range(i + 1, num_atoms): indices[counter, 0, 0, :] = [i, 0] indices[counter, 0, 1, :] = [i, 1] indices[counter, 0, 2, :] = [i, 2] indices[counter, 1, 0, :] = [j, 0] indices[counter, 1, 1, :] = [j, 1] indices[counter, 1, 2, :] = [j, 2] counter += 1 batch_indices = tf.range(batch_size, dtype=tf.int32) batch_indices = tf.tile(tf.reshape(batch_indices, [batch_size, 1, 1, 1, 1]), [1, num_distances, 2, 3, 1]) coordinate_indices = tf.tile(indices, [batch_size, 1, 1, 1]) coordinate_indices = tf.reshape(coordinate_indices, [batch_size, num_distances, 2, 3, 2]) coordinate_indices = tf.to_int32(coordinate_indices) coordinate_indices = tf.concat([batch_indices, coordinate_indices], axis=-1) point_pairs = tf.gather_nd(params=self.coordinates, indices=coordinate_indices) # calculate Euclidian distances distances = (point_pairs[:, :, 0, :] - point_pairs[:, :, 1, :]) ** 2 distances = tf.reduce_sum(distances, axis=-1) distances = tf.sqrt(distances) self._distances = distances class NPMol(AbstractMol): """Holds np.ndarrays representing a single molecule, provided in different useful formats. At construction, converts from a zero-padded, stochastic reconstruction to a molecule with definite values. Moreover, provides internal conversion between different formats: distance matrix, flattened distances, coordinates, smiles, xyz file format For construction, atoms and [distances|distance_matrix|coordinates] are necessary. :param atoms: one-hot vector or probability distribution over atom types, will be converted to a list of atom symbols at construction. :param distances: flattened ndarray of n(n-1)/2 relevant entries in the distance matrix :param distance_matrix: The distance matrix of the molecule. :param coordinates: The 3D coordinates for all atoms in the molecule. :param smiles: Optionally, provide the SMILES string of the molecule. """ def __init__(self, atoms, distances=None, distance_matrix=None, coordinates=None, smiles=None): super(NPMol, self).__init__(atoms, distances=distances, distance_matrix=distance_matrix, coordinates=coordinates) self._smiles = smiles self._xyz = None self._valid_distances = None self._discretize() def _discretize(self): """Remove padding and convert the probabilistic description of atom types to a concrete list of atom symbols.""" atom_types, mask = self._get_atom_types_and_mask() self.atoms = atom_types # overwrite atom one-hot-matrix with list of type symbols self._remove_zero_padding(mask) def _remove_zero_padding(self, mask): """Remove zero-padding on the basis of the provided boolean mask which specifies which atoms are present.""" padded_atom_count = len(mask) actual_atom_count = sum(mask) mask_matrix = mask * mask.reshape([padded_atom_count, 1]) # remove coordinates of non-existent atoms if self._coordinates is not None: self._coordinates = self._coordinates[mask] if self._distance_matrix is not None: unpadded_distance_matrix = np.reshape(self._distance_matrix[mask_matrix], [actual_atom_count, actual_atom_count]) self._distance_matrix = unpadded_distance_matrix if self._distances is not None: flattened_mask_matrix = mask_matrix[np.triu_indices(padded_atom_count, 1)] self._distances = self._distances[flattened_mask_matrix] def _get_atom_types_and_mask(self): """Generate list of unambiguous atom symbols and a boolean mask from a (possibly) stochastic atom type matrix. The most probable atom type is chosen and converted to its string symbol. If atom type NONE is most probable, the atom is not included in the list of symbols, and the respective mask value is set to False. """ most_probable_indices = np.argmax(self.atoms, axis=-1) mask = most_probable_indices < 4 # 4 = none_index atom_count = mask.sum() if atom_count == 0: logging.warning('Molecule does not contain any atoms.') # atom types to strings/symbols available_types = ['C', 'N', 'O', 'F'] filtered_indices: np.core.multiarray.ndarray = most_probable_indices[mask] atom_types = [available_types[type_index] for type_index in filtered_indices] return atom_types, mask @property def xyz(self): """Atom types and coordinates in the xyz data format, generated from distances or coordinates.""" if self._xyz is None: self._generate_xyz() return self._xyz @property def smiles(self): """Canonical SMILES string, generated if necessary.""" if self._smiles is None: self._generate_smiles() return self._smiles def invert_coordinates(self): """Mirror the molecule by flipping the sign of the x coordinates. Coordinates are generated if necessary. If the xyz representation had previously been generated, it will be reset. Distance matrix, distances and smiles are invariant with respect to this transformation and remain unchanged. """ if self._coordinates is None: self._generate_coordinates() self._coordinates[:, 0] *= -1 self._xyz = None def _generate_xyz(self): """XYZ format, generated if necessary.""" # write in xyz format xyz = '{}\n\n'.format(len(self.atoms)) for i, point in enumerate(self.coordinates): xyz += self.atoms[i] + '\t{}\t{}\t{}\n'.format(point[0], point[1], point[2]) self._xyz = xyz def _generate_smiles(self): """Generate canonical SMILES strings from atoms and coordinates.""" if len(self.atoms) == 0: self._smiles = '' return parsed_mol = pybel.readstring('xyz', self.xyz) self._smiles = parsed_mol.write('can', opt={'n': None, 'i': None}) # remove mol name and stereochemistry def _generate_coordinates(self): """Generate atomic coordinates from distance matrix using multi-dimensional scaling.""" atom_count = self.distance_matrix.shape[0] if atom_count > 1: mds = MDS(n_components=3, metric=True, dissimilarity='precomputed', eps=1e-7, n_init=1) self._coordinates = mds.fit_transform(self.distance_matrix) else: self._coordinates = np.zeros([atom_count, 3]) def _generate_distance_matrix(self): """Generate distance matrix from coordinates or distances.""" atom_count = len(self.atoms) distance_matrix = np.zeros([atom_count, atom_count]) if self._distances is not None: distance_matrix[np.triu_indices(atom_count, 1)] = self.distances distance_matrix += np.transpose(distance_matrix) self._distance_matrix = distance_matrix elif self._coordinates is not None: for i in range(atom_count): for j in range(atom_count): difference = self._coordinates[i] - self._coordinates[j] distance = np.sqrt(np.sum(difference * difference)) distance_matrix[i, j] = distance distance_matrix[j, i] = distance self._distance_matrix = distance_matrix else: raise AttributeError('Could not generate distance matrix, neither distances nor coordinates are given.') def _generate_distances(self): """Generate distances from distance matrix.""" atom_count = self.distance_matrix.shape[0] self._distances = self.distance_matrix[np.triu_indices(atom_count, 1)] @classmethod def create_from_batch(cls, batch_atoms, batch_distances=None, batch_distance_matrix=None, batch_coordinates=None): """Create a list of DiscreteMols from data where the first dimension is the batch dimension.""" if batch_atoms is None: raise ValueError('Atoms must be provided.') if all([batch_distances is None, batch_distance_matrix is None, batch_coordinates is None]): raise ValueError('Either distances, distance_matrix or coordinates need to be specified.') batch_size = batch_atoms.shape[0] # replace params with value None by a list of Nones, so we can iterate over them and pass on None for each mol. none_list = [None for _ in range(batch_size)] batch_coordinates = none_list if batch_coordinates is None else batch_coordinates batch_distances = none_list if batch_distances is None else batch_distances batch_distance_matrix = none_list if batch_distance_matrix is None else batch_distance_matrix batch_mols = [cls(atoms, distances=distances, distance_matrix=distance_matrix, coordinates=coordinates) for atoms, coordinates, distances, distance_matrix in zip(batch_atoms, batch_coordinates, batch_distances, batch_distance_matrix)] return batch_mols
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,961
rnaimehaom/deepmol
refs/heads/master
/model/read_out.py
import tensorflow as tf from .abstract_model import Model from .fc_nn import FullyConnectedNN class Set2Vec(Model): """Implements the Set2Vec read-out, mapping the hidden states to a vector embedding of the entire molecule. Additionally, multi-head attention is possible by setting hparams.set2vec_num_attention_heads > 1. :param hparams: hyperparameters, as a tf.contrib.training.HParams object """ def __init__(self, hparams): super(Set2Vec, self).__init__(hparams) @staticmethod def _lstm(m, c, hidden_state_dim, name=""): """Create a special LSTM cell with no inputs. Usually, an LSTM cell produces its output based on its previous output, previous cell state and new input. In this model however, the LSTM does not receive any input. Moreover, only the cell state is directly handed on to the next time step while the output is transformed by an attention block before being passed on. :param m: the previous output of the cell :param c: the previous cell state :param hidden_state_dim: dimension of the hidden states :param name: prefix for variable names :return: new cell state and output """ # Input Gate m_dim = 2 * hidden_state_dim w_im = tf.get_variable(name + "w_im", [m_dim, hidden_state_dim]) b_i = tf.get_variable(name + "b_i", [1, hidden_state_dim], initializer=tf.zeros_initializer) i_t = tf.sigmoid(m @ w_im + b_i, name="i_t") # Forget Gate w_fm = tf.get_variable(name + "w_fm", [m_dim, hidden_state_dim]) b_f = tf.get_variable(name + "b_f", [1, hidden_state_dim], initializer=tf.zeros_initializer) f_t = tf.sigmoid(m @ w_fm + b_f, name="f_t") # Cell State w_cm = tf.get_variable(name + "w_cm", [m_dim, hidden_state_dim]) b_c = tf.get_variable(name + "b_c", [1, hidden_state_dim], initializer=tf.zeros_initializer) # Output Gate w_om = tf.get_variable(name + "w_om", [m_dim, hidden_state_dim]) b_o = tf.get_variable(name + "b_o", [1, hidden_state_dim], initializer=tf.zeros_initializer) o_t = tf.sigmoid(m @ w_om + b_o, name="o_t") c_new = f_t * c + i_t * tf.tanh(m @ w_cm + b_c) m_new = o_t * tf.tanh(c_new) return m_new, c_new def _forward(self, hidden_states, mask): """Forward pass of Set2Vec which maps the hidden states to a vector embedding of the entire molecule. :param hidden_states: Hidden states of all atoms, shaped [batch_size, num_atoms, hidden_state_dim] :param mask: indicates whether an atom is actually present (1) or zero-padded (0). [batch_size, num_atoms] :return: Vector embedding of the entire molecule. [batch_size, 2 * hidden_state_dim] :raises ValueError: If the hidden state dimension is not divisible by the number of attention heads. """ # embed hidden states using a neural network as initial step hidden_state_dim = hidden_states.get_shape()[2].value fc_nn = FullyConnectedNN(self.hparams, layer_dims=[hidden_state_dim], activation=None, output_activation=None) hidden_states = fc_nn.forward(hidden_states) # prepare multi-head attention batch_size = tf.shape(hidden_states)[0] num_attention_heads = self.hparams.set2vec_num_attention_heads if hidden_state_dim % num_attention_heads != 0: raise ValueError( 'The hidden state dimension (%d) is not divisible by the number of attention heads (%d).' % ( hidden_state_dim, num_attention_heads)) attention_head_dim = int(hidden_state_dim / num_attention_heads) hidden_states = tf.reshape(hidden_states, [batch_size, -1, num_attention_heads, attention_head_dim]) m = tf.zeros([batch_size, 2 * hidden_state_dim]) c = tf.zeros([batch_size, hidden_state_dim]) m_to_query = tf.get_variable("m_to_query", [hidden_state_dim, hidden_state_dim]) attention_v = tf.get_variable("att_v", [num_attention_heads, attention_head_dim]) large_negative_value = -1e10 # must not be too large either, otherwise NaNs will occur mask = tf.cast(mask, tf.float32) mask = (1 - mask) * large_negative_value # masked terms will turn zero in attention softmax mask = tf.reshape(mask, [batch_size, -1, 1]) # variable names in the following comments: n = num_atoms, d = hidden_state_dim, d/k = attention_head_dim for i in range(self.hparams.set2vec_steps): with tf.variable_scope(tf.get_variable_scope(), reuse=True if i > 0 else None): with tf.name_scope("set2vec_%d" % i): m, c = self._lstm(m, c, hidden_state_dim, name='lstm') query = m @ m_to_query # [batch, d] @ [d, d] = [batch, d] query = tf.reshape(query, [batch_size, 1, num_attention_heads, attention_head_dim], name='query') # add query to all nodes in batch: [batch, n, k, d/k] + [batch, 1, k, d/k] = [batch, n, k, d/k] tanh_term = tf.tanh(query + hidden_states) # for every node, perform dot product with attention vector v [batch, n, k, d/k] * [k, d/k] energies = tf.reduce_sum(tanh_term * attention_v, axis=3, name='energies') # Apply mask if mask is not None: energies += mask # [batch_size, n, k] + [batch_size, n, 1] attention = tf.nn.softmax(energies, 1, name='attention') # [batch_size, n, k] # Attend attention = tf.reshape(attention, [batch_size, -1, num_attention_heads, 1]) read = tf.reduce_sum(attention * hidden_states, 1) # sum_n [batch, n, k, 1] * [batch, n, k, d/k] read = tf.reshape(read, [batch_size, hidden_state_dim]) # reshape back to [batch, d] m = tf.concat([m, read], axis=1, name='m') return m class ConcatReadOut(Model): """Simply concatenates the hidden states of all atoms. (Useful if atom order should be preserved.) :param hparams: hyperparameters, as a tf.contrib.training.HParams object """ def __init__(self, hparams): super().__init__(hparams) def _forward(self, hidden_states, mask=None): """Concatenate hidden states. :param hidden_states: Hidden states of all atoms, shaped [batch_size, num_atoms, hidden_state_dim] :param mask: indicates whether an atom is actually present (1) or zero-padded (0). [batch_size, num_atoms] :return: concatenated tensor of dimension [batch_size, num_atoms * num_atom_features]. """ # set hidden states of all padded atoms to zero if mask is not None: mask = tf.cast(mask, tf.float32) mask = tf.expand_dims(mask, axis=2) hidden_states = hidden_states * mask hidden_state_dim = hidden_states.get_shape()[2].value batch_size = tf.shape(hidden_states)[0] num_atoms = hidden_states.get_shape()[1] concatenated_nodes = tf.reshape(hidden_states, [batch_size, num_atoms * hidden_state_dim]) return concatenated_nodes
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,962
rnaimehaom/deepmol
refs/heads/master
/train_mpnn.py
import logging import tensorflow as tf import argparse from train_util import QM9Trainer, read_configs_and_train from model.mpnn import MPNN from data.featurizer import DistanceNumHFeaturizer logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.INFO) class MPNNTrainer(QM9Trainer): """Extend QM9Trainer to train and evaluate a message passing neural network for property prediction. :param data_dir: directory containing the QM9 files *.sdf, *_labels.csv (*=[training|validation|test]) :param train_log_interval: Write training log after this many steps. :param val_log_interval: Write validation log after this many steps. :param name: Name of the experiment/training that is performed. :param implicit_hydrogen: If True, hydrogen atoms will be treated implicitly. :param patience: Stop training early if the (smoothed) validation loss has not improved for this many steps. :param loss_smoothing: Early stopping is decided based on a running average of the validation loss. This parameter controls the amount of smoothing and corresponds to the TensorBoard smoothing slider. :param property_names: List of QM9 properties that should be used for training. """ def __init__(self, data_dir, train_log_interval, val_log_interval, name='', implicit_hydrogen=True, patience=float('inf'), loss_smoothing=0.8, property_names=None): super(MPNNTrainer, self).__init__(data_dir, train_log_interval, val_log_interval, name, implicit_hydrogen, patience, loss_smoothing, property_names) max_num_atoms = 9 if implicit_hydrogen else 29 # relevant for zero padding self.featurizer = DistanceNumHFeaturizer(max_num_atoms, implicit_hydrogen) # initialized by _build_model self._train_summary = None self._val_loss = None self._val_mae_actual_scale = None self._test_loss = None self._test_mae_actual_scale = None def _write_train_log(self): """Perform training step and and write training log. Overrides superclass method.""" summary, _ = self._sess.run([self._train_summary, self._train_op]) self._summary_writer.add_summary(summary, self._step) def _write_val_log(self): """Perform validation, write validation log and return validation loss. Overrides superclass method. :return: validation loss """ averages = self._average_over_dataset(self._val_iterator, [self._val_loss, self._val_mae_actual_scale]) val_loss, val_mae = averages[0], averages[1] summary = tf.Summary() summary.value.add(tag='avg_val_loss', simple_value=val_loss) summary.value.add(tag='avg_val_mae', simple_value=val_mae) self._summary_writer.add_summary(summary, self._step) self._summary_writer.flush() return val_loss def _eval_results(self): """Compute loss and mean absolute error on validation and test set and write to results file.""" results = {} results['eval_step'] = self._step val_averages = self._average_over_dataset(self._val_iterator, [self._val_loss, self._val_mae_actual_scale]) results['val_loss'] = val_averages[0] results['val_mae'] = val_averages[1] test_averages = self._average_over_dataset(self._test_iterator, [self._test_loss, self._test_mae_actual_scale]) results['test_loss'] = test_averages[0] results['test_mae'] = test_averages[1] self._write_eval_results_to_file(results) def _build_model(self, hparams): """Build the model given the hyperparameter configuration. Overrides superclass method. :param hparams: tf.contrib.training.HParams object """ mpnn = MPNN(hparams, output_dim=len(self.property_names)) train_output = mpnn.forward(self._train_mols) train_loss = tf.losses.mean_squared_error(labels=self._train_mols.labels, predictions=train_output) self._global_step = tf.Variable(0, name='global_step', trainable=False) learning_rate = tf.train.exponential_decay(hparams.learning_rate, self._global_step, hparams.lr_decay_steps, hparams.lr_decay_rate) optimizer = tf.train.AdamOptimizer(learning_rate) self._train_op = optimizer.minimize(train_loss, global_step=self._global_step) train_labels_actual_scale = self._standardization.undo(self._train_mols.labels) train_output_actual_scale = self._standardization.undo(train_output) train_mae_actual_scale = tf.losses.absolute_difference(train_labels_actual_scale, train_output_actual_scale) self._train_summary = tf.summary.merge([tf.summary.scalar('train_loss', train_loss), tf.summary.scalar('train_mae_actual_scale', train_mae_actual_scale)]) # validation summary val_output = mpnn.forward(self._val_mols) self._val_loss = tf.losses.mean_squared_error(labels=self._val_mols.labels, predictions=val_output) val_labels_actual_scale = self._standardization.undo(self._val_mols.labels) val_output_actual_scale = self._standardization.undo(val_output) self._val_mae_actual_scale = tf.losses.absolute_difference(val_labels_actual_scale, val_output_actual_scale) # test summary test_output = mpnn.forward(self._test_mols) self._test_loss = tf.losses.mean_squared_error(labels=self._test_mols.labels, predictions=test_output) test_labels_actual_scale = self._standardization.undo(self._test_mols.labels) test_output_actual_scale = self._standardization.undo(test_output) self._test_mae_actual_scale = tf.losses.absolute_difference(test_labels_actual_scale, test_output_actual_scale) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('data_dir', help='directory containing data and labels for training, validation and test') parser.add_argument('--config_dir', help='directory containing json files with HParams') parser.add_argument('--steps', type=int, default=5000000, help='number of steps/batches to train', ) parser.add_argument('--name', default='', help='prefix of results directory') parser.add_argument('--train_log_interval', type=int, default=250, help='write train log after this many steps') parser.add_argument('--val_log_interval', type=int, default=10000, help='write validation log after this many steps') parser.add_argument('--patience', type=float, default=float('inf'), help='early stopping: stop if validation loss has not improved for this number of steps') parser.add_argument('--smoothing_factor', type=float, default=0.8, help='smoothing factor for early stopping') parser.add_argument('--explicit_hydrogen', help='treat hydrogen atoms explicitly', action='store_true') parser.add_argument('--property', default='energy_U0_atom', help='QM9 property to use for training') args = parser.parse_args() trainer = MPNNTrainer(args.data_dir, args.train_log_interval, args.val_log_interval, args.name, not args.explicit_hydrogen, args.patience, args.smoothing_factor, [args.property]) read_configs_and_train(trainer, MPNN.default_hparams(), args.steps, args.config_dir)
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,963
rnaimehaom/deepmol
refs/heads/master
/tests/test_read_out.py
import tensorflow as tf import numpy as np from model.read_out import Set2Vec HParams = tf.contrib.training.HParams class TestSet2Vec(tf.test.TestCase): def test_permutation_invariance(self): """Test whether the set2vec output is invariant to permutation of the input mols""" num_atoms, batch_size, hidden_state_dim = 4, 3, 5 hparams = HParams(hidden_state_dim=hidden_state_dim, set2vec_steps=10, set2vec_num_attention_heads=1) tf.reset_default_graph() input_ph = tf.placeholder(tf.float32, [batch_size, num_atoms, hidden_state_dim]) mask_ph = tf.placeholder(tf.float32, [batch_size, num_atoms]) output_vector = Set2Vec(hparams).forward(input_ph, mask_ph) input_np = np.random.randn(batch_size, num_atoms, hidden_state_dim) input_np_perm = input_np[:, np.random.permutation(num_atoms), :] mask_np = np.ones([batch_size, num_atoms]) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) out = sess.run(output_vector, feed_dict={input_ph: input_np, mask_ph: mask_np}) out_perm = sess.run(output_vector, feed_dict={input_ph: input_np_perm, mask_ph: mask_np}) self.assertAllClose(out, out_perm) def test_pad_invariance(self): """Test whether the set2vec output is invariant to padding of the input mols.""" num_atoms, batch_size, hidden_state_dim, padding = 4, 3, 5, 2 hparams = HParams(node_dim=hidden_state_dim, set2vec_steps=12, set2vec_num_attention_heads=1) tf.reset_default_graph() input_ph = tf.placeholder(tf.float32, [None, None, hidden_state_dim]) mask = tf.placeholder(tf.bool, [None, None]) output_vector = Set2Vec(hparams).forward(input_ph, mask=mask) input_np = np.random.randn(batch_size, num_atoms, hidden_state_dim) input_np_pad = np.pad(input_np, ((0, 0), (0, padding), (0, 0)), mode='constant') mask_np = np.ones((batch_size, num_atoms)) mask_np_pad = np.pad(mask_np, ((0, 0), (0, padding)), mode='constant') # Permute the masks and inputs for each element in the batch. # We create separate permutation for each element in order to make the # test more general. for i in range(batch_size): perm = np.random.permutation(mask_np_pad.shape[1]) mask_np_pad[i, :] = mask_np_pad[i, perm] input_np_pad[i, :] = input_np_pad[i, perm] with self.test_session() as sess: sess.run(tf.global_variables_initializer()) out_original = sess.run(output_vector, feed_dict={input_ph: input_np, mask: mask_np}) out_pad = sess.run(output_vector, feed_dict={input_ph: input_np_pad, mask: mask_np_pad}) self.assertAllClose(out_original, out_pad) def test_multi_head_attention(self): """Test error handling and permutation invariance for multi-head attention""" num_atoms, batch_size, hidden_state_dim = 4, 3, 8 with self.assertRaises(ValueError): tf.reset_default_graph() input_ph = tf.placeholder(tf.float32, [batch_size, num_atoms, hidden_state_dim]) mask_ph = tf.placeholder(tf.float32, [batch_size, num_atoms]) hparams = HParams(node_dim=hidden_state_dim, set2vec_steps=12, set2vec_num_attention_heads=3) Set2Vec(hparams).forward(input_ph, mask_ph) hparams = HParams(node_dim=hidden_state_dim, set2vec_steps=12, set2vec_num_attention_heads=2) tf.reset_default_graph() input_ph = tf.placeholder(tf.float32, [batch_size, num_atoms, hidden_state_dim]) mask_ph = tf.placeholder(tf.float32, [batch_size, num_atoms]) output_vector = Set2Vec(hparams).forward(input_ph, mask_ph) input_np = np.random.randn(batch_size, num_atoms, hidden_state_dim) input_np_perm = input_np[:, np.random.permutation(num_atoms), :] mask_np = np.ones([batch_size, num_atoms]) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) out = sess.run(output_vector, feed_dict={input_ph: input_np, mask_ph: mask_np}) out_perm = sess.run(output_vector, feed_dict={input_ph: input_np_perm, mask_ph: mask_np}) self.assertAllClose(out, out_perm) if __name__ == '__main__': tf.test.main()
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,964
rnaimehaom/deepmol
refs/heads/master
/tests/test_qm9_loader.py
import os from data.qm9_loader import QM9Loader import tensorflow as tf import numpy as np from data.featurizer import DistanceNumHFeaturizer import numpy.testing as npt class TestQM9Loader(tf.test.TestCase): def test_data_set_generation(self): properties = ['mu', 'alpha', 'Cv'] implicit_hydrogen = True n = 9 if implicit_hydrogen else 29 featurizer = DistanceNumHFeaturizer(n, implicit_hydrogen) data_dir = os.path.join(os.path.dirname(__file__), 'sample_data') qm9_loader = QM9Loader(data_dir, featurizer, property_names=properties, standardize_labels=True) batch_size = 16 data_set = qm9_loader.train_data.batch(batch_size) mol_batch = data_set.make_one_shot_iterator().get_next() with self.test_session() as sess: for i in range(4): data = sess.run(mol_batch) npt.assert_equal(data['atoms'].shape, np.array([batch_size, n, featurizer.num_atom_features])) npt.assert_equal(data['interactions'].shape, np.array([batch_size, n, n, featurizer.num_interaction_features])) npt.assert_equal(data['labels'].shape, np.array([batch_size, len(properties)])) if __name__ == '__main__': tf.test.main()
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,965
rnaimehaom/deepmol
refs/heads/master
/data/featurizer.py
import numpy as np import rdkit.Chem as Chem class FeaturizedMolecule: """Molecule object holding all the relevant features. :param atom_features: atom representations of dimension [num_atoms, num_atom_features] :param interaction_matrix: matrix of atomic interactions shaped [num_atoms, num_atoms, num_interaction_features] :param coordinates: xyz-coordinates of the atoms, shaped [num_atoms, 3] """ def __init__(self, atom_features, interaction_matrix, coordinates=None): self.atom_features = atom_features self.interaction_matrix = interaction_matrix self.coordinates = coordinates class Featurizer: """Base class for featurizers that convert an rdkit molecule into a FeaturizedMolecule. :param max_num_atoms: Maximum number of atoms in a molecule. Smaller molecules are zero-padded. :param implicit_hydrogen: True if hydrogen atoms should be treated implicitly. :param shuffle_atoms: If True, the order of atoms is shuffled. """ def __init__(self, max_num_atoms, implicit_hydrogen=True, shuffle_atoms=False): self.max_num_atoms = max_num_atoms self.implicit_hydrogen = implicit_hydrogen self.shuffle_atoms = shuffle_atoms # defined in the sub class: self._num_atom_features = None self._num_interaction_features = None @property def num_atom_features(self): """Number of features encoding each atom.""" return self._num_atom_features @property def num_interaction_features(self): """Number of features encoding the interactions between atoms.""" return self._num_interaction_features def featurize(self, rdkit_mol): """Convert an rdkit_mol to a FeaturizedMolecule. :param rdkit_mol: Molecule to be featurized. :return: FeaturizedMolecule with the respective representations specified in the subclasses. :raises ValueError: If the number of atoms exceeds max_num_atoms. """ num_atoms = rdkit_mol.GetNumAtoms() if num_atoms > self.max_num_atoms: raise ValueError('max_num_atoms is %d, but molecule has %d atoms.' % (self.max_num_atoms, num_atoms)) if self.shuffle_atoms: order = list(range(num_atoms)) np.random.shuffle(order) rdkit_mol = Chem.RenumberAtoms(rdkit_mol, newOrder=order) atom_features = self._generate_atom_features(rdkit_mol) interaction_matrix = self._generate_interaction_matrix(rdkit_mol) coordinates = self._generate_coordinates(rdkit_mol) return FeaturizedMolecule(atom_features, interaction_matrix, coordinates) def _generate_atom_features(self, rdkit_mol): raise NotImplementedError('Featurizer must be implemented in child class') def _generate_interaction_matrix(self, rdkit_mol): raise NotImplementedError('Featurizer must be implemented in child class') def _generate_coordinates(self, rdkit_mol): """Read the atomic coordinates (shape: [num_atoms, 3]) saved in the rdkit_mol. """ try: conformer = rdkit_mol.GetConformer() # necessary to access position information except ValueError: return None # no coordinates provided in the mol num_atoms = rdkit_mol.GetNumAtoms() coordinates = np.zeros([self.max_num_atoms, 3]) for i in range(num_atoms): position = conformer.GetAtomPosition(i) coordinates[i, :] = position.x, position.y, position.z return coordinates class DistanceFeaturizer(Featurizer): """Featurizer based on interatomic distance. Atom features: one-hot-encoded types [H, C, O, N, F, none/padded], H is only present if implicit_hydrogen=False Interaction features: Euclidian distance matrix """ def __init__(self, max_num_atoms, implicit_hydrogen=True, shuffle_atoms=False): super().__init__(max_num_atoms, implicit_hydrogen, shuffle_atoms) self._num_atom_features = 5 if implicit_hydrogen else 6 self._num_interaction_features = 1 def _generate_interaction_matrix(self, rdkit_mol): """Generate interaction matrix using the real-valued Euclidian distance as interaction feature.""" num_atoms = rdkit_mol.GetNumAtoms() interaction_matrix = np.zeros((num_atoms, num_atoms, self.num_interaction_features)) interaction_matrix[:, :, 0] = Chem.Get3DDistanceMatrix(rdkit_mol) # add zero padding padding_size = self.max_num_atoms - num_atoms interaction_matrix = np.pad(interaction_matrix, ((0, padding_size), (0, padding_size), (0, 0)), mode='constant') return interaction_matrix def _generate_atom_features(self, rdkit_mol): """Generate atom features by one-hot encoding the atom types.""" atoms = rdkit_mol.GetAtoms() if self.implicit_hydrogen: atomic_numbers = np.array([6, 7, 8, 9]) # QM9 data set with implicit hydrogen only contains CNOF else: atomic_numbers = np.array([1, 6, 7, 8, 9]) # QM9 data set only contains HCNOF atom_features = np.zeros((len(atoms), len(atomic_numbers) + 1)) for i, atom in enumerate(atoms): atomic_num = atom.GetAtomicNum() atom_type_one_hot = (atomic_numbers == atomic_num).astype(int) atom_features[i, 0:len(atomic_numbers)] = atom_type_one_hot # add zero padding padding_size = self.max_num_atoms - len(atoms) atom_features = np.pad(atom_features, ((0, padding_size), (0, 0)), mode='constant') # set none-type for padded atoms is_padded = 1 - np.sum(atom_features, axis=1) atom_features[:, len(atomic_numbers)] = is_padded return atom_features class DistanceNumHFeaturizer(DistanceFeaturizer): """Same as DistanceFeaturizer, but adds information about the number of implicit hydrogens at each atom. If hydrogen is implicit, the entry for hydrogen in the one-hot vector is replaced by the number of implicit hydrogens at the atom. """ def __init__(self, max_num_atoms, implicit_hydrogen=True, shuffle_atoms=False): super().__init__(max_num_atoms, implicit_hydrogen, shuffle_atoms) self._num_atom_features = 6 self._num_interaction_features = 1 def _generate_atom_features(self, rdkit_mol): """Generate atom features by one-hot encoding the atom types. If hydrogen is implicit, the entry for hydrogen is replaced by the number of implicit hydrogens. """ atom_features = super()._generate_atom_features(rdkit_mol) if self.implicit_hydrogen: # add implicit hydrogens to existent atoms implicit_hydrogens = np.zeros(self.max_num_atoms) for i, atom in enumerate(rdkit_mol.GetAtoms()): implicit_hydrogens[i] = atom.GetNumImplicitHs() atom_features = np.concatenate((implicit_hydrogens[:, np.newaxis], atom_features), axis=1) return atom_features
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,966
rnaimehaom/deepmol
refs/heads/master
/train_vae.py
import logging import os import tensorflow as tf import numpy as np import argparse from train_util import QM9Trainer, read_configs_and_train from model.molvae import MolVAE from data.featurizer import DistanceFeaturizer from data.molecules import NPMol import pybel import openbabel logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.INFO) class VAETrainer(QM9Trainer): """Extend QM9Trainer to train and evaluate a geometry-based variational autoencoder for molecules. :param data_dir: directory containing the QM9 files *.sdf, *_labels.csv (*=[training|validation|test]) :param train_log_interval: Write training log after this many steps. :param val_log_interval: Write validation log after this many steps. :param name: Name of the experiment/training that is performed. :param implicit_hydrogen: If True, hydrogen atoms will be treated implicitly. :param patience: Stop training early if the (smoothed) validation loss has not improved for this many steps. :param loss_smoothing: Early stopping is decided based on a running average of the validation loss. This parameter controls the amount of smoothing and corresponds to the TensorBoard smoothing slider. """ def __init__(self, data_dir, train_log_interval, val_log_interval, name='', implicit_hydrogen=True, patience=float('inf'), loss_smoothing=0.8): super().__init__(data_dir, train_log_interval, val_log_interval, name, implicit_hydrogen, patience, loss_smoothing, property_names=None) max_num_atoms = 9 if implicit_hydrogen else 29 # relevant for zero padding self.featurizer = DistanceFeaturizer(max_num_atoms, implicit_hydrogen) # initialized by _build_model self._train_summary = None self._val_loss = None self._test_loss = None def _write_train_log(self): """Perform training step and and write training log. Overrides superclass method.""" summary, _ = self._sess.run([self._train_summary, self._train_op]) self._summary_writer.add_summary(summary, self._step) def _write_val_log(self): """Perform validation, write validation log and return validation loss. Overrides superclass method. :return: validation loss """ val_loss = self._average_over_dataset(self._val_iterator, self._val_loss) summary = tf.Summary() summary.value.add(tag='avg_val_loss', simple_value=val_loss) self._summary_writer.add_summary(summary, self._step) self._summary_writer.flush() return val_loss def _eval_results(self): """Compute scores on validation and test set and write to results file.""" results = {} results['eval_step'] = self._step results['val_loss'] = self._average_over_dataset(self._val_iterator, self._val_loss) results['test_loss'] = self._average_over_dataset(self._test_iterator, self._test_loss) logging.info('Computing validation accuracies...') val_accuracies = self._compute_accuracies(self._val_iterator, self._val_mols, self._val_mols_rec) results['val_atom_acc'], results['val_smiles_acc'], results['val_pos_rmse'], results[ 'val_pos_mae'] = val_accuracies logging.info('Computing test accuracies...') test_accuracies = self._compute_accuracies(self._test_iterator, self._test_mols, self._test_mols_rec) results['test_atom_acc'], results['test_smiles_acc'], results['test_pos_rmse'], results[ 'test_pos_mae'] = test_accuracies if self._variational: logging.info('Sampling molecules...') self.sample_mols(num_batches=1) self._write_eval_results_to_file(results) def sample_mols(self, num_batches): """Sample molecules from the latent prior and write them to disk. :param num_batches: Number of batches to sample. """ xyz_list = [] for _ in range(num_batches): if self._coordinate_output: sampled_atoms, sampled_coords = self._sess.run( [self._sampled_mols.atoms, self._sampled_mols.coordinates]) sampled_mols = NPMol.create_from_batch(batch_atoms=sampled_atoms, batch_coordinates=sampled_coords) else: sampled_atoms, sampled_dist = self._sess.run([self._sampled_mols.atoms, self._sampled_mols.distances]) sampled_mols = NPMol.create_from_batch(batch_atoms=sampled_atoms, batch_distances=sampled_dist) batch_xyz = [mol.xyz for mol in sampled_mols] xyz_list.extend(batch_xyz) xyz_dir = os.path.join(self.results_dir, 'sampled') os.makedirs(xyz_dir, exist_ok=True) max_num_digits = len(str(len(xyz_list))) for i, xyz in enumerate(xyz_list): path = os.path.join(xyz_dir, str(i).zfill(max_num_digits) + '.xyz') with open(path, 'w') as f: f.write(xyz) def _compute_accuracies(self, data_iterator, mols, mols_rec): """Iterate over the given set to evaluate scores. :param data_iterator: The initializable_iterator of the relevant data set. :param mols: TFMolBatch of the original molecules from the data set. :param mols_rec: TFMolBatch of the reconstructed molecules. :return: - smiles_accuracy: The ratio of molecules where the SMILES string was correctly reconstructed. - atom_accuracy: The ratio of molecules where all atom types were correctly reconstructed. - rmse: The root-mean-square error of atom positions for molecules with correctly reconstructed atoms. - mae: The mean absolute error of atom positions for molecules with correctly reconstructed atoms. """ self._sess.run(data_iterator.initializer) correct_smiles_counter, correct_atoms_counter, total_counter = 0, 0, 0 mse_sum, mae_sum = 0, 0 while True: try: if self._coordinate_output: atoms, coords, atoms_rec, coords_rec = self._sess.run( [mols.atoms, mols.coordinates, mols_rec.atoms, mols_rec.coordinates]) mols_np = NPMol.create_from_batch(atoms, batch_coordinates=coords) rec_mols_np = NPMol.create_from_batch(atoms_rec, batch_coordinates=coords_rec) else: atoms, dist, atoms_rec, dist_rec = self._sess.run( [mols.atoms, mols.distances, mols_rec.atoms, mols_rec.distances]) mols_np = NPMol.create_from_batch(atoms, batch_distances=dist) rec_mols_np = NPMol.create_from_batch(atoms_rec, batch_distances=dist_rec) for mol, rec_mol in zip(mols_np, rec_mols_np): if mol.smiles == rec_mol.smiles: correct_smiles_counter += 1 if mol.atoms == rec_mol.atoms: correct_atoms_counter += 1 mse, mae = self._compute_position_accuracy(mol, rec_mol) mse_sum += mse mae_sum += mae total_counter += 1 except tf.errors.OutOfRangeError: break smiles_accuracy = 0 atom_accuracy = 0 rmse, mae = -1, -1 if total_counter != 0: smiles_accuracy = correct_smiles_counter / total_counter if correct_atoms_counter != 0: atom_accuracy = correct_atoms_counter / total_counter rmse = np.sqrt(mse_sum / correct_atoms_counter) mae = mae_sum / correct_atoms_counter return atom_accuracy, smiles_accuracy, rmse, mae @staticmethod def _compute_position_accuracy(mol, rec_mol): """Compute the scores comparing the atom positions in two molecules. The mean squared error and mean absolute error of their atom positions is calculated. To do this, rec_mol is aligned with mol using openbabel. A mirrored version of rec_mol is used if this leads to a lower MSE. :param mol: NPMol :param rec_mol: NPMol :return: - mean squared error of atom positions - mean absolute error of atom positions """ py_mol = pybel.readstring('xyz', mol.xyz) py_rec_mol = pybel.readstring('xyz', rec_mol.xyz) rec_mol.invert_coordinates() # change chirality py_rec_mol_inverted = pybel.readstring('xyz', rec_mol.xyz) def align_mols(ref, to_be_aligned): """Align a pybel.Molecule (in place) to a reference one. :param ref: the reference pybel.Molecule :param to_be_aligned: the pybel.Molecule that will be aligned to ref """ ref, to_be_aligned = ref.OBMol, to_be_aligned.OBMol align = openbabel.OBAlign(False, False) align.SetRefMol(ref) align.SetTargetMol(to_be_aligned) align.Align() align.UpdateCoords(to_be_aligned) align_mols(py_mol, py_rec_mol) align_mols(py_mol, py_rec_mol_inverted) def mse_mae(mol_1, mol_2): """Calculate mean squared distance and mean absolute distance between the atoms in mol_1 and mol_2. Each atom in mol_1 is compared with its counterpart in mol_2. Thus, the number of atoms must be equal. :param mol_1: pybel.Molecule :param mol_2: pybel.Molecule :return: - mean squared error of atom positions - mean absolute error of atom positions """ mse_sum, mae_sum, num_atoms = 0, 0, 0 for atom_1, atom_2 in zip(mol_1.atoms, mol_2.atoms): x1, y1, z1 = atom_1.coords x2, y2, z2 = atom_2.coords squared_dist = (x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2 mse_sum += squared_dist mae_sum += np.sqrt(squared_dist) num_atoms += 1 return mse_sum / num_atoms, mae_sum / num_atoms mse, mae = mse_mae(py_mol, py_rec_mol) mse_inverted, mae_inverted = mse_mae(py_mol, py_rec_mol_inverted) if mse < mse_inverted: return mse, mae else: return mse_inverted, mae_inverted def _build_model(self, hparams): """Build the VAE model given the hyperparameter configuration. Overrides superclass method. :param hparams: tf.contrib.training.HParams object """ vae = MolVAE(hparams, self.featurizer.max_num_atoms, self.featurizer.num_atom_features) train_loss = vae.calculate_loss(self._train_mols) # TensorBoard Summaries tf.summary.scalar('training_loss', train_loss) self._train_summary = tf.summary.merge_all() self._global_step = tf.Variable(0, name='global_step', trainable=False) learning_rate = tf.train.exponential_decay(hparams.learning_rate, self._global_step, hparams.lr_decay_steps, hparams.lr_decay_rate) optimizer = tf.train.AdamOptimizer(learning_rate) self._train_op = optimizer.minimize(train_loss, global_step=self._global_step) self._val_loss = vae.calculate_loss(self._val_mols) self._test_loss = vae.calculate_loss(self._test_mols) self._val_mols_rec = vae.reconstruct(self._val_mols) self._test_mols_rec = vae.reconstruct(self._test_mols) self._coordinate_output = hparams.coordinate_output self._variational = hparams.variational self._sampled_mols = vae.sample(hparams.batch_size) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('data_dir', help='directory containing data and labels for training, validation and test') parser.add_argument('--config_dir', help='directory containing json files with HParams') parser.add_argument('--steps', type=int, default=7500000, help='number of steps/batches to train', ) parser.add_argument('--name', default='', help='prefix of results directory') parser.add_argument('--train_log_interval', type=int, default=250, help='write train log after this many steps') parser.add_argument('--val_log_interval', type=int, default=10000, help='write validation log after this many steps') parser.add_argument('--patience', type=float, default=float('inf'), help='early stopping: stop if validation loss has not improved for this number of steps') parser.add_argument('--smoothing_factor', type=float, default=0.8, help='smoothing factor for early stopping') parser.add_argument('--explicit_hydrogen', help='treat hydrogen atoms explicitly', action='store_true') args = parser.parse_args() trainer = VAETrainer(args.data_dir, args.train_log_interval, args.val_log_interval, args.name, not args.explicit_hydrogen, args.patience, args.smoothing_factor) read_configs_and_train(trainer, MolVAE.default_hparams(), args.steps, args.config_dir)
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,967
rnaimehaom/deepmol
refs/heads/master
/data/qm9_loader.py
import numpy as np import os import rdkit.Chem as Chem import tensorflow as tf from .standardization import Standardization class QM9Loader: """Provide the QM9 data set as a tf.data.Dataset, given an sdf file for molecules and csv file for labels. :param data_dir: The directory containing the QM9 files *.sdf, *_labels.csv (*=[training|validation|test]) :param property_names: List of names of the properties/labels that should be used. If None, all are used. :param featurizer: Instance of a subclass of Featurizer that specifies how the mols should be featurized. :param standardize_labels: If True, labels will be standardized to zero mean and unit variance. """ all_property_names = ['rcA', 'rcB', 'rcC', 'mu', 'alpha', 'homo', 'lumo', 'gap', 'r2', 'zpve', 'energy_U0', 'energy_U', 'enthalpy_H', 'free_G', 'Cv', 'energy_U0_atom', 'energy_U_atom', 'enthalpy_H_atom', 'free_G_atom'] def __init__(self, data_dir, featurizer, property_names=None, standardize_labels=True): max_num_atoms = featurizer.max_num_atoms self.featurizer = featurizer self._train_mols, self._train_labels = self._load_data_for_partition(data_dir, 'training', property_names) self._val_mols, self._val_labels = self._load_data_for_partition(data_dir, 'validation', property_names) self._test_mols, self._test_labels = self._load_data_for_partition(data_dir, 'test', property_names) self._standardization = None if standardize_labels: self._standardization = Standardization() self._train_labels = self.standardization.apply(self._train_labels) self._val_labels = self.standardization.apply(self._val_labels) self._test_labels = self.standardization.apply(self._test_labels) self.shapes = {'atoms': [max_num_atoms, featurizer.num_atom_features], 'interactions': [max_num_atoms, max_num_atoms, featurizer.num_interaction_features], 'coordinates': [max_num_atoms, 3], 'labels': [self._train_labels.shape[1]]} @property def train_data(self): """Create a tf.data.Dataset of the training set.""" return self._create_tf_dataset(self._train_mols, self._train_labels) @property def val_data(self): """Create a tf.data.Dataset of the validation set.""" return self._create_tf_dataset(self._val_mols, self._val_labels) @property def test_data(self): """Create a tf.data.Dataset of the test set.""" return self._create_tf_dataset(self._test_mols, self._test_labels) @property def standardization(self): """Return the Standardization that was used to standardize the data. :raises AttributeError: in case the labels have not been standardized """ if self._standardization is None: raise AttributeError('Labels have not been standardized.') return self._standardization def _load_data_for_partition(self, data_dir, partition='training', property_names=None): """Load rdkit molecules and labels for the specified partition of the data set. :param data_dir: The directory containing the QM9 files *.sdf, *_labels.csv (*=[training|validation|test]) :param partition: [training|validation|test] :param property_names: List of names of the properties/labels that should be used. If None, all are used. :return: - rdkit molecules as a SDMolSupplier (generator reading from sdf file) - ndarray of labels, shaped [num_molecules, labels] """ mol_path = os.path.join(data_dir, partition + '.sdf') label_path = os.path.join(data_dir, partition + '_labels.csv') mols = Chem.SDMolSupplier(mol_path, removeHs=self.featurizer.implicit_hydrogen) labels = self._import_labels(label_path, property_names) return mols, labels def _import_labels(self, label_path, property_names=None): """Load labels from a csv file. :param label_path: path to csv file with labels. :param property_names: If provided, only the specified properties will be included. :return: ndarray of labels, shaped [num_molecules, labels] """ if property_names is None: columns_to_use = np.arange(1, 20) # all columns except ID else: label_indices = np.array([self.all_property_names.index(name) for name in property_names]) columns_to_use = label_indices + 1 # add one since column 0 is id labels = np.loadtxt(label_path, delimiter=',', skiprows=1, usecols=columns_to_use) # ensure that labels is 2D even if only one property is requested labels = labels.reshape([-1, len(columns_to_use)]) return labels def _create_tf_dataset(self, mols, labels): """Create a tf.data.Dataset from the given rdkit mols and labels. :param mols: rdkit molecules :param labels: ndarray of labels :return: tf.data.Dataset """ featurizer = self.featurizer def generator(): for mol, label in zip(mols, labels): featurized_mol = featurizer.featurize(mol) yield {'atoms': featurized_mol.atom_features, 'interactions': featurized_mol.interaction_matrix, 'coordinates': featurized_mol.coordinates, 'labels': label} return tf.data.Dataset.from_generator(generator, output_types=({'atoms': tf.float32, 'interactions': tf.float32, 'coordinates': tf.float32, 'labels': tf.float32}), output_shapes=self.shapes)
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,968
rnaimehaom/deepmol
refs/heads/master
/tests/test_featurizer.py
import numpy.testing as npt import unittest import rdkit.Chem as Chem import os import numpy as np from data.featurizer import DistanceFeaturizer, DistanceNumHFeaturizer max_num_atoms, max_num_atoms_h = 9, 29 # implicit hydrogen, explicit hydrogen class TestDistanceFeaturizer(unittest.TestCase): def setUp(self): data_import_directory = os.path.dirname(__file__) sdf_path = os.path.join(data_import_directory, 'sample_mol.sdf') mol_supplier = Chem.SDMolSupplier(sdf_path, removeHs=True) # import molecules from sdf file self.rdkit_mol = mol_supplier[0] self.featurizer = DistanceFeaturizer(max_num_atoms, implicit_hydrogen=True) self.feat_mol = self.featurizer.featurize(self.rdkit_mol) mol_supplier = Chem.SDMolSupplier(sdf_path, removeHs=False) # explicit hydrogen rdkit_mol_h = mol_supplier[0] self.featurizer_h = DistanceFeaturizer(max_num_atoms_h, implicit_hydrogen=False) self.feat_mol_h = self.featurizer_h.featurize(rdkit_mol_h) def test_max_num_atoms(self): distance_featurizer_fail = DistanceFeaturizer(max_num_atoms=1, implicit_hydrogen=True) with self.assertRaises(ValueError): distance_featurizer_fail.featurize(self.rdkit_mol) def test_atom_features(self): desired = np.zeros([max_num_atoms, self.featurizer.num_atom_features]) desired[0:2, 0] = [1, 1] # CC desired[2, 1] = 1 # N desired[3:, -1] = 1 # none/padded npt.assert_equal(self.feat_mol.atom_features, desired) desired_h = np.zeros([max_num_atoms_h, self.featurizer_h.num_atom_features]) desired_h[0:2, 1] = 1 # CC desired_h[2, 2] = 1 # N desired_h[3:6, 0] = 1 # H desired_h[6:, -1] = 1 # none/padded npt.assert_equal(self.feat_mol_h.atom_features, desired_h) def test_interaction_features(self): desired = np.zeros([max_num_atoms, max_num_atoms, self.featurizer.num_interaction_features]) desired[0, 1:3, 0] = 1.45685382, 2.61188178 desired[1, 0:3, 0] = 1.45685382, 0, 1.15502801 desired[2, 0:2, 0] = 2.61188178, 1.15502801 npt.assert_allclose(self.feat_mol.interaction_matrix, desired) desired_shape_h = [max_num_atoms_h, max_num_atoms_h, self.featurizer_h.num_interaction_features] npt.assert_equal(self.feat_mol_h.interaction_matrix.shape, desired_shape_h) class TestDistanceNumHFeaturizer(unittest.TestCase): def setUp(self): data_import_directory = os.path.dirname(__file__) sdf_path = os.path.join(data_import_directory, 'sample_mol.sdf') mol_supplier = Chem.SDMolSupplier(sdf_path, removeHs=True) # import molecules from sdf file self.rdkit_mol = mol_supplier[0] self.featurizer = DistanceNumHFeaturizer(max_num_atoms, implicit_hydrogen=True) self.feat_mol = self.featurizer.featurize(self.rdkit_mol) mol_supplier = Chem.SDMolSupplier(sdf_path, removeHs=False) # explicit hydrogen rdkit_mol_h = mol_supplier[0] self.featurizer_h = DistanceNumHFeaturizer(max_num_atoms_h, implicit_hydrogen=False) self.feat_mol_h = self.featurizer_h.featurize(rdkit_mol_h) def test_max_num_atoms(self): distance_featurizer_fail = DistanceNumHFeaturizer(max_num_atoms=1, implicit_hydrogen=True) with self.assertRaises(ValueError): distance_featurizer_fail.featurize(self.rdkit_mol) def test_atom_features(self): desired = np.zeros([max_num_atoms, self.featurizer.num_atom_features]) desired[0, 0] = 3 # implicit H desired[0:2, 1] = 1 # CC desired[2, 2] = 1 # N desired[3:, -1] = 1 # none/padded npt.assert_equal(self.feat_mol.atom_features, desired) desired_h = np.zeros([max_num_atoms_h, self.featurizer_h.num_atom_features]) desired_h[0:2, 1] = 1 # CC desired_h[2, 2] = 1 # N desired_h[3:6, 0] = 1 # H desired_h[6:, -1] = 1 # none/padded npt.assert_equal(self.feat_mol_h.atom_features, desired_h) def test_interaction_features(self): desired = np.zeros([max_num_atoms, max_num_atoms, self.featurizer.num_interaction_features]) desired[0, 1:3, 0] = 1.45685382, 2.61188178 desired[1, 0:3, 0] = 1.45685382, 0, 1.15502801 desired[2, 0:2, 0] = 2.61188178, 1.15502801 npt.assert_allclose(self.feat_mol.interaction_matrix, desired) desired_shape_h = [max_num_atoms_h, max_num_atoms_h, self.featurizer_h.num_interaction_features] npt.assert_equal(self.feat_mol_h.interaction_matrix.shape, desired_shape_h) if __name__ == '__main__': unittest.main()
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,969
rnaimehaom/deepmol
refs/heads/master
/model/update_function.py
import tensorflow as tf from .abstract_model import Model class GRUUpdate(Model): """Implements the GRU Update function to update the hidden states based on their incoming messages. :param hparams: hyperparameters, as a tf.contrib.training.HParams object """ def __init__(self, hparams): super(GRUUpdate, self).__init__(hparams) def _forward(self, hidden_states, messages, mask): """Forward pass updating each hidden state using its incoming messages. In contrast to the original definition, we only use one message per graph edge. :param hidden_states: Hidden states of all atoms, shaped [batch_size, num_atoms, hidden_state_dim] :param messages: sum of incoming messages for each atom, shaped [batch_size, num_atoms, hidden_state_dim] :param mask: indicates whether an atom is actually present (1) or zero-padded (0). [batch_size, num_atoms] :return: updated states shaped [batch_size, num_atoms, hidden_state_dim] """ batch_size = tf.shape(hidden_states)[0] num_atoms = tf.shape(hidden_states)[1] hidden_state_dim = hidden_states.get_shape()[2] w_z = tf.get_variable("w_z", shape=[hidden_state_dim, hidden_state_dim]) u_z = tf.get_variable("u_z", shape=[hidden_state_dim, hidden_state_dim]) w_r = tf.get_variable("w_r", shape=[hidden_state_dim, hidden_state_dim]) u_r = tf.get_variable("u_r", shape=[hidden_state_dim, hidden_state_dim]) w = tf.get_variable("w", shape=[hidden_state_dim, hidden_state_dim]) u = tf.get_variable("u", shape=[hidden_state_dim, hidden_state_dim]) # reshape hidden states, messages and mask so that each row = one atom hidden_states = tf.reshape(hidden_states, [batch_size * num_atoms, hidden_state_dim]) messages = tf.reshape(messages, [batch_size * num_atoms, hidden_state_dim]) mask = tf.cast(tf.reshape(mask, [batch_size * num_atoms, 1]), tf.float32) # calculate values for update gate z_t and reset gate r_t z_t = tf.sigmoid(messages @ w_z + hidden_states @ u_z, name="z_t") r_t = tf.sigmoid(messages @ w_r + hidden_states @ u_r, name="r_t") # combine message with previous state update = tf.tanh(messages @ w + (r_t * hidden_states) @ u, name="update") # update state with update, but keep previous state according to values of update gate z_t updated_states = (1 - z_t) * hidden_states + z_t * update # zero out masked nodes updated_states = updated_states * mask # reshape back to original shape updated_states = tf.reshape(updated_states, [batch_size, num_atoms, hidden_state_dim], name="updated_states") return updated_states
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,970
rnaimehaom/deepmol
refs/heads/master
/train_util.py
import os import logging import tensorflow as tf import numpy as np import time import copy from datetime import timedelta from data.qm9_loader import QM9Loader from data.molecules import TFMolBatch class CurveSmoother: """This class imitates the behavior of the TensorBoard smoothing slider by performing a running average. For instance, to smooth a loss curve, instantiate the class and pass the values to the smooth function one by one. :param smoothing_factor: controls the amount of smoothing. 0 = no smoothing, 1 = stuck at initial value. :raises ValueError: If the smoothing factor is outside the valid range [0, 1]. """ def __init__(self, smoothing_factor): if not 0 <= smoothing_factor <= 1: raise ValueError('Smoothing factor must lie between 0 and 1.') self._smoothing_factor = smoothing_factor self._last_smoothed_value = None def smooth(self, new_value): """Smooth the value based on all previous values passed to this function. :param new_value: The latest value of the curve that is to be smoothed. :return: smoothed value """ if self._last_smoothed_value is None: smoothed_value = new_value else: smoothed_value = self._last_smoothed_value * self._smoothing_factor + \ (1 - self._smoothing_factor) * new_value self._last_smoothed_value = smoothed_value return smoothed_value class QM9Trainer: """Abstract base class for training and evaluating models on the QM9 data set. All the logic for loading data and performing training is defined here, while the model and the evaluation is to be defined in the concrete sub class. :param data_dir: directory containing the QM9 files *.sdf, *_labels.csv (*=[training|validation|test]) :param train_log_interval: Write training log after this many steps. :param val_log_interval: Write validation log after this many steps. :param name: Name of the experiment/training that is performed. :param implicit_hydrogen: If True, hydrogen atoms will be treated implicitly. :param patience: Stop training early if the (smoothed) validation loss has not improved for this many steps. :param loss_smoothing: Early stopping is decided based on a running average of the validation loss. This parameter controls the amount of smoothing and corresponds to the TensorBoard smoothing slider. :param property_names: List of QM9 properties that should be used for training. """ def __init__(self, data_dir, train_log_interval=250, val_log_interval=10000, name='', implicit_hydrogen=True, patience=float('inf'), loss_smoothing=0.8, property_names=None): self.data_dir = data_dir self.name = name self.results_dir = os.path.join(os.path.dirname(__file__), name + '_results') os.makedirs(self.results_dir, exist_ok=True) self.train_log_interval = train_log_interval self.val_log_interval = val_log_interval self.patience = patience self.loss_smoothing = loss_smoothing self.property_names = QM9Loader.all_property_names if property_names is None else property_names self.implicit_hydrogen = implicit_hydrogen # initialized in subclass constructor self.featurizer = None # updated by run_trainings self._config_name = None # name of currently trained hyperparameter configuration self._current_config_number = 0 self._num_configs = 0 # initialized by _prepare_data self._standardization = None self._train_iterator, self._val_iterator, self._test_iterator = None, None, None self._train_mols, self._val_mols, self._test_mols = None, None, None # initialized by _build_model self._global_step = None # tf.Variable for controlling learning rate decay self._train_op = None # initialized by _train self._sess = None self._summary_writer = None # initialized by _init_saver and _restore_saved_model self._step = 0 self._saver = None self._checkpoint_dir = None def run_trainings(self, hparam_configs, num_steps): """Run training and evaluation for different hyperparameter configurations. If a configuration with the same name has been trained before, its weights are restored from the checkpoint and training is started from the step saved in the checkpoint. If that step is higher than num_steps, training is skipped. To only run evaluation, e.g. use num_steps=0. :param hparam_configs: dict of tf.contrib.training.HParams objects :param num_steps: Number of steps (=batches) to train. """ self._num_configs += len(hparam_configs) self._save_hparam_configs(hparam_configs) for config_name, hparam_config in hparam_configs.items(): self._current_config_number += 1 self._config_name = config_name logging.info('==== Configuration %d / %d: ' + config_name + ' ====', self._current_config_number, self._num_configs) tf.reset_default_graph() self._sess = tf.Session() logging.info('Preparing data.') self._prepare_data(hparam_config.batch_size) logging.info('Building model.') self._build_model(hparam_config) self._sess.run(tf.global_variables_initializer()) # run before restoring model, otherwise it will overwrite self._init_saver() self._restore_saved_model() # restore previously trained model from disk if num_steps > self._step: logging.info('Starting training.') self._train(num_steps) logging.info('Training complete.') self._restore_saved_model() # restore model with best validation loss during current training logging.info('Starting evaluation.') self._eval_results() self._sess.close() logging.info('All trainings complete.') def _save_hparam_configs(self, hparam_configs): """Save the hyperparameter configurations to json files in the results folder. It is very useful to store the the hyperparameter configurations along with the results they produced. :param hparam_configs: dict of tf.contrib.training.HParams objects """ config_save_dir = os.path.join(self.results_dir, 'configs') os.makedirs(config_save_dir, exist_ok=True) for config_name, hparam_config in hparam_configs.items(): with open(os.path.join(config_save_dir, config_name + '.json'), 'w') as f: f.write(hparam_config.to_json(2)) def _prepare_data(self, batch_size): """Create data iterators and TFMolBatches for the QM9 data. :param batch_size: Number of molecules per batch. """ qm9_loader = QM9Loader(self.data_dir, self.featurizer, self.property_names, standardize_labels=True) self._standardization = qm9_loader.standardization def create_iterator(data_set, training=True): """Create a data iterator from the given tf.data.Dataset.""" data_set = data_set.cache() if training: data_set = data_set.shuffle(buffer_size=10000, reshuffle_each_iteration=True) data_set = data_set.repeat() data_set = data_set.batch(batch_size) data_set = data_set.prefetch(buffer_size=1) if training: return data_set.make_one_shot_iterator() return data_set.make_initializable_iterator() self._train_iterator = create_iterator(qm9_loader.train_data, training=True) self._val_iterator = create_iterator(qm9_loader.val_data, training=False) self._test_iterator = create_iterator(qm9_loader.test_data, training=False) with tf.name_scope('train_data'): train_data = self._train_iterator.get_next() self._train_mols = TFMolBatch(train_data['atoms'], labels=train_data['labels'], distance_matrix=train_data['interactions'][..., 0], # squeeze interaction dim coordinates=train_data['coordinates']) with tf.name_scope('val_data'): val_data = self._val_iterator.get_next() self._val_mols = TFMolBatch(val_data['atoms'], labels=val_data['labels'], distance_matrix=val_data['interactions'][..., 0], coordinates=val_data['coordinates']) with tf.name_scope('test_data'): test_data = self._test_iterator.get_next() self._test_mols = TFMolBatch(test_data['atoms'], labels=test_data['labels'], distance_matrix=test_data['interactions'][..., 0], coordinates=test_data['coordinates']) def _init_saver(self): """Initialize the tf.train.Saver to save and restore the model to/from disk.""" self._saver = tf.train.Saver(max_to_keep=1, save_relative_paths=True) self._checkpoint_dir = os.path.join(self.results_dir, 'checkpoints', 'checkpoints_' + self._config_name) if not os.path.exists(self._checkpoint_dir): os.makedirs(self._checkpoint_dir) def _restore_saved_model(self): """Restore the model from checkpoint (if available) and set the current training step accordingly. """ latest_checkpoint = tf.train.latest_checkpoint(self._checkpoint_dir) if latest_checkpoint is None: self._step = 0 else: self._saver.restore(self._sess, latest_checkpoint) self._step = int(latest_checkpoint.split('-')[-1]) def _train(self, num_steps): """Perform training until num_steps is reached or the validation loss stops improving (early stopping). Training starts at self._step with an initial validation via self._write_val_log(). At each step, self._train_op is run. Every self.train_log_interval steps, self._write_train_log() is called. Every self.val_log_interval steps, self._write_val_log() is called. If the validation loss has improved, the model is saved to disk. Early stopping is done when the smoothed validation loss curve has not improved for self.patience steps. :param num_steps: Training step at which training stops. """ sess = self._sess self._summary_writer = tf.summary.FileWriter( os.path.join(self.results_dir, 'logs', 'logs_' + self._config_name), sess.graph) start_step = self._step sess.run(self._global_step.assign(start_step)) sess.graph.finalize() early_stopping_smoother = CurveSmoother(smoothing_factor=self.loss_smoothing) best_val_loss = self._write_val_log() best_val_loss_smoothed = early_stopping_smoother.smooth(best_val_loss) best_step_smoothed = start_step logging.info('%d / %d: Initial validation yields loss %f', self._step, num_steps, best_val_loss) start_time = time.time() for self._step in range(start_step + 1, num_steps + 1): # check early stopping if (self._step - best_step_smoothed) > self.patience: logging.info('Out of patience.') break # validate if self._step % self.val_log_interval == 0: val_loss = self._write_val_log() best_log = '' if val_loss < best_val_loss: self._saver.save(sess, os.path.join(self._checkpoint_dir, 'checkpoint'), self._step) best_val_loss = val_loss best_log = ' (BEST so far)' logging.info('%d / %d: Validation yields loss %f' + best_log, self._step, num_steps, val_loss) # smooth validation loss for early stopping val_loss_smoothed = early_stopping_smoother.smooth(val_loss) if val_loss_smoothed < best_val_loss_smoothed: best_val_loss_smoothed = val_loss_smoothed best_step_smoothed = self._step # train if self._step % self.train_log_interval == 0: self._write_train_log() logging.info('%d / %d: Training summary written', self._step, num_steps) else: sess.run(self._train_op) # estimate remaining time num_steps_since_start = self._step - start_step if self._step % (10 * self.train_log_interval) == 0 and num_steps_since_start >= self.val_log_interval: seconds_since_start = time.time() - start_time num_steps_to_train = num_steps - start_step remaining_seconds = seconds_since_start * (num_steps_to_train / num_steps_since_start - 1) formatted_remaining_time = str(timedelta(seconds=int(remaining_seconds))) logging.info(formatted_remaining_time + ' remaining for configuration %d / %d', self._current_config_number, self._num_configs) def _build_model(self, hparams): """Build the model given the hyperparameter configuration. Needs to be implemented in subclass and initialize self._train_op and self._global_step. :param hparams: tf.contrib.training.HParams object """ raise NotImplementedError('Model must be defined in child class.') def _write_train_log(self): """Perform training step and and write training log. Needs to be implemented in subclass.""" raise NotImplementedError('Must be implemented in child class.') def _write_val_log(self): """Perform validation, write validation log and return validation loss. Needs to be implemented in subclass.""" raise NotImplementedError('Must be implemented in child class.') def _eval_results(self): """Evaluate results after training is complete. Needs to be implemented in subclass.""" raise NotImplementedError('Must be implemented in child class.') def _write_eval_results_to_file(self, result_dict): """Write results of post-training evaluation into one central results file. :param result_dict: Dictionary containing evaluation results. """ results_filename = os.path.join(self.results_dir, 'results.txt') if not os.path.isfile(results_filename): # file does not exist yet with open(results_filename, 'w') as f: header = 'config' + '\t' + '\t'.join(result_dict.keys()) + '\n' f.write(header) with open(results_filename, 'a') as f: data = self._config_name + '\t' + '\t'.join([str(v) for v in result_dict.values()]) + '\n' f.write(data) logging.info('Evaluation results for config ' + self._config_name + ' written to ' + results_filename) def _average_over_dataset(self, data_iterator, eval_tensors): """Calculate the average values of eval_tensors across the specified data set. :param data_iterator: The initializable_iterator of the relevant data set. :param eval_tensors: The one-dimensional tensors to be evaluated and averaged. :return: The average values of eval_tensors. """ self._sess.run(data_iterator.initializer) values = [] while True: try: value = self._sess.run(eval_tensors) values.append(value) except tf.errors.OutOfRangeError: break values_np = np.array(values) avg_values = np.mean(values_np, axis=0) return avg_values class ConfigReader: """Read hyperparameter configurations from json files. Keeps track of whether new files have been added since the last read, such that after training completion, training can continue directly with new configurations that have been added in the meantime. :param config_dir: All files in this directory ending with .json will be read. :param default_hparams: The tf.contrib.training.HParams object with the default hyperparameter values. """ def __init__(self, config_dir, default_hparams): self.config_dir = config_dir self.previous_config_files = set() self.default_hparams = default_hparams def _get_new_config_files(self): """List all json files in config_dir that have not been there at the previous call to this method. :return: List of file paths. """ config_files = {os.path.join(self.config_dir, f) for f in os.listdir(self.config_dir) if f.endswith('.json')} new_config_files = config_files - self.previous_config_files self.previous_config_files |= new_config_files return new_config_files def get_new_hparam_configs(self): """Get all hyperparameter configs in config_dir that have not been there at the previous call to this method. :return: dict of hyperparameter configs; config_name => tf.contrib.training.HParams object :raises KeyError: If a hyperparameter in the config file does not match any of the default hyperparameters. """ new_config_files = self._get_new_config_files() hparam_configs = {} for config_file in new_config_files: with open(config_file, 'r') as f: hparams = copy.deepcopy(self.default_hparams) filename = os.path.basename(config_file) config_name = os.path.splitext(filename)[0] try: hparam_configs[config_name] = hparams.parse_json(f.read()) except KeyError as e: raise KeyError('There is a parameter in the configuration ' + config_name + ' which does not match any of the default parameters: ' + str(e)) from None return hparam_configs def read_configs_and_train(trainer, default_hparams, num_steps, config_dir=None): """Read hyperparameter configurations from config_dir and run the respective trainings. If config_dir is specified, the directory is checked for hyperparameter configurations and the respective trainings are started. If new configurations have been added in the meantime, training will continue with these. If config_dir is None, training will be just be run with the default configuration default_hparams. :param trainer: Subclass of QM9Trainer to perform the training. :param default_hparams: tf.contrib.training.HParams with the default hyperparameter configuration. :param num_steps: Number of steps/batches to train :param config_dir: Directory containing json files with HParams. """ if config_dir is not None: config_reader = ConfigReader(config_dir, default_hparams) new_hparam_configs = config_reader.get_new_hparam_configs() while len(new_hparam_configs) > 0: logging.info('Found %d new hyperparameter configurations.', len(new_hparam_configs)) trainer.run_trainings(new_hparam_configs, num_steps) logging.info('Checking for new hyperparameter configurations that have been added during training.') new_hparam_configs = config_reader.get_new_hparam_configs() logging.info('No new hyperparameter configurations found.') else: logging.info('No directory with hyperparameter configurations specified. Using default values.') trainer.run_trainings({'default': default_hparams}, num_steps) logging.info('Done.')
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,971
rnaimehaom/deepmol
refs/heads/master
/tests/test_standardization.py
import unittest import numpy as np import numpy.testing as npt from data.standardization import Standardization class TestStandardization(unittest.TestCase): example_data = np.arange(12).reshape(3, 4) ** 2 example_data_2 = np.arange(1, 13).reshape(3, 4) ** 2 def test_initialization(self): standardization = Standardization() self.assertFalse(standardization.is_defined()) with self.assertRaises(TypeError): standardization.undo(self.example_data) def test_apply(self): standardization = Standardization() standardized_data = standardization.apply(self.example_data) actual_variance = np.var(standardized_data, axis=0) desired_variance = np.ones_like(actual_variance) npt.assert_allclose(actual_variance, desired_variance) actual_mean = np.mean(standardized_data, axis=0) desired_mean = np.zeros_like(actual_mean) npt.assert_allclose(actual_mean, desired_mean, atol=1e-8) def test_undo(self): standardization = Standardization() standardized_data = standardization.apply(self.example_data) retrieved_data = standardization.undo(standardized_data) npt.assert_allclose(retrieved_data, self.example_data) def test_repeated_application(self): standardization = Standardization() standardization.apply(self.example_data) standardized_data_2 = standardization.apply(self.example_data_2) desired = (self.example_data_2 - np.mean(self.example_data, axis=0)) / np.std(self.example_data, axis=0) npt.assert_allclose(standardized_data_2, desired) if __name__ == '__main__': unittest.main()
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,972
rnaimehaom/deepmol
refs/heads/master
/model/abstract_model.py
import tensorflow as tf class Model: """Abstract superclass for reusable models using weight sharing with tf.make_template. Subclasses implementing the _forward() method can then be called using .forward(). :param hparams: hyperparameters, as a tf.contrib.training.HParams object """ def __init__(self, hparams): scope_name = self.__class__.__name__ self.hparams = hparams self.forward = tf.make_template(scope_name, self._forward) def _forward(self, *args, **kwargs): raise NotImplementedError("Model subclasses must define _forward() method")
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,973
rnaimehaom/deepmol
refs/heads/master
/model/message_passing.py
import tensorflow as tf from .abstract_model import Model import numpy as np from .fc_nn import FullyConnectedNN class ConvFilterGenerator(Model): """A model mapping each interatomic distance value to a matrix or vector as the basis for message generation. Message generation works similar to regular convolutions for images with a discrete pixel grid. Here however, distance values are continuous which makes such a filter generator necessary. Depending on the method (the continuous convolutions in SchNet or EdgeNet in the MPNN paper), either a vector or a matrix are output for each distance value. :param hparams: hyperparameters, as a tf.contrib.training.HParams object """ def __init__(self, hparams): super(ConvFilterGenerator, self).__init__(hparams) def _forward(self, distance_matrix): """Forward pass of filter generator. :param distance_matrix: distance matrix shaped [batch_size, num_atoms, num_atoms] :return: generated convolution filters. If hparams.use_matrix_filters is True, the shape is [batch_size, num_atoms, num_atoms, hidden_state_dim, hidden_state_dim], else we have a vector for each atom pair: [batch_size, num_atoms, num_atoms, hidden_state_dim] """ batch_size = tf.shape(distance_matrix)[0] num_atoms = tf.shape(distance_matrix)[1] hidden_state_dim = self.hparams.hidden_state_dim use_matrix_filters = self.hparams.use_matrix_filters # map every distance value in the whole batch separately: dist_mat_reshaped = tf.reshape(distance_matrix, [batch_size, num_atoms, num_atoms, 1], name="dist_mat_reshaped") layer_dims = np.ones(self.hparams.filter_hidden_layers + 1) * self.hparams.filter_hidden_dim layer_dims[-1] = hidden_state_dim ** 2 if use_matrix_filters else hidden_state_dim # output dim activation = tf.nn.leaky_relu if self.hparams.use_leaky_relu else tf.nn.relu fc_nn = FullyConnectedNN(self.hparams, layer_dims, activation, output_activation=None) conv_filter = fc_nn.forward(dist_mat_reshaped) if use_matrix_filters: conv_filter = tf.reshape(conv_filter, [batch_size, num_atoms, num_atoms, hidden_state_dim, hidden_state_dim], name='matrix_filters') else: conv_filter = tf.reshape(conv_filter, [batch_size, num_atoms, num_atoms, hidden_state_dim], name='vector_filters') return conv_filter class MatrixMessagePassing(Model): """Implements EdgeNetwork message function from MPNN paper. To generate the message from atom j to atom i, the filter matrix belonging to the distance between i and j is multiplied with the hidden state of j. All messages to atom i are summed and a bias is added. :param hparams: hyperparameters, as a tf.contrib.training.HParams object """ def __init__(self, hparams): super(MatrixMessagePassing, self).__init__(hparams) def _forward(self, hidden_states, matrix_filters): """Forward pass for generating messages using matrix filters. :param hidden_states: Hidden states of all atoms, shaped [batch_size, num_atoms, hidden_state_dim] :param matrix_filters: generated convolution filters, shaped [batch_size, num_atoms, num_atoms, hidden_state_dim, hidden_state_dim] :return: sum of incoming messages to each atom, shaped [batch_size, num_atoms, hidden_state_dim] """ batch_size = tf.shape(hidden_states)[0] num_atoms = tf.shape(hidden_states)[1] hidden_state_dim = self.hparams.hidden_state_dim # multiply matrix with hidden states and add bias to generate messages hidden_states_flat = tf.reshape(hidden_states, [batch_size, num_atoms * hidden_state_dim, 1], name='hidden_states_flat') matrix_filters = tf.transpose(matrix_filters, [0, 1, 3, 2, 4]) matrix_filters = tf.reshape(matrix_filters, [batch_size, num_atoms * hidden_state_dim, num_atoms * hidden_state_dim], name='matrix_filters_flat') messages = matrix_filters @ hidden_states_flat # (b, n*d, n*d) x (b, n*d, 1) -> (b, n*d, 1) messages = tf.reshape(messages, [batch_size * num_atoms, hidden_state_dim], name='messages_unbiased') messages += tf.get_variable("message_bias", shape=hidden_state_dim) messages = tf.reshape(messages, [batch_size, num_atoms, hidden_state_dim], name='messages') return messages class VectorMessagePassing(Model): """Messages are generated by elementwise product with a vector instead of a product with a matrix, as in SchNet. To generate the message from atom j to atom i, the filter vector belonging to the distance between i and j is multiplied elementwise with the hidden state of j. The total message to atom i is the sum of all incoming ones. :param hparams: hyperparameters, as a tf.contrib.training.HParams object """ def __init__(self, hparams): super(VectorMessagePassing, self).__init__(hparams) def _forward(self, hidden_states, vector_filters): """Forward pass for generating messages using vector filters. :param hidden_states: Hidden states of all atoms, shaped [batch_size, num_atoms, hidden_state_dim] :param vector_filters: generated convolution filters shaped [batch_size, num_atoms, num_atoms, hidden_state_dim] :return: sum of incoming messages to each atom, shaped [batch_size, num_atoms, hidden_state_dim] """ hidden_states = tf.expand_dims(hidden_states, axis=1) messages = hidden_states * vector_filters messages = tf.reduce_sum(messages, axis=2) # total message to atom i = sum over messages from atoms j return messages
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,974
rnaimehaom/deepmol
refs/heads/master
/data/standardization.py
import numpy as np class Standardization: """Define a standardization operation that can be applied to different data sets. We would like to standardize our training data to zero mean and unit variance. This transformation defines the scales of our data. After standardizing the training set, every further call of apply() will scale the data accordingly by applying the same transformation as the first time. The "data" must be an ndarray where the first dimension runs over the different data points. """ def __init__(self): self._means = None self._standard_deviations = None def is_defined(self): """Has the standardization operation been defined yet?""" return (self._means is not None) and (self._standard_deviations is not None) def define(self, reference_data): """Define the standardization such that reference_data would be transformed to zero mean, unit variance.""" self._means = np.mean(reference_data, axis=0) self._standard_deviations = np.std(reference_data, axis=0) def apply(self, input_data): """Apply standardization using previous definition or, if undefined, the input_data.""" if not self.is_defined(): self.define(input_data) return (input_data - self._means) / self._standard_deviations def undo(self, standardized_data): """Convert data back to its original scales.""" if not self.is_defined(): raise TypeError('This Standardizer has not been initialized yet.') return standardized_data * self._standard_deviations + self._means
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,975
rnaimehaom/deepmol
refs/heads/master
/model/fc_nn.py
import tensorflow as tf from .abstract_model import Model class FullyConnectedNN(Model): """A simple fully connected neural network :param hparams: hyperparameters, as a tf.contrib.training.HParams object :param layer_dims: list specifying the dimensions of hidden layers and output :param activation: activation function to apply after each hidden layer :param output_activation: activation function to apply to the output """ def __init__(self, hparams, layer_dims, activation=tf.nn.leaky_relu, output_activation=None): super(FullyConnectedNN, self).__init__(hparams) self.layer_dims = layer_dims self.activation = activation self.output_activation = output_activation def _forward(self, x): """Forward pass of the neural network. :param x: input tensor :returns: output tensor of the neural network """ for hidden_dim in self.layer_dims[:-1]: x = tf.layers.dense(x, hidden_dim, self.activation) output_tensor = tf.layers.dense(x, self.layer_dims[-1], self.output_activation) return output_tensor
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,976
rnaimehaom/deepmol
refs/heads/master
/tests/test_pos_acc.py
import unittest import os import numpy as np from train_vae import VAETrainer import rdkit.Chem as Chem from data.featurizer import DistanceFeaturizer from data.molecules import NPMol class TestPositionAccuracy(unittest.TestCase): def test_atom_features(self): data_dir = os.path.join(os.path.dirname(__file__), 'sample_data') trainer = VAETrainer(data_dir, 10, 10) sdf_path = os.path.join(os.path.dirname(__file__), 'sample_mol.sdf') mol_supplier = Chem.SDMolSupplier(sdf_path, removeHs=True) # import molecules from sdf file rdkit_mol = mol_supplier[0] featurizer = DistanceFeaturizer(9, implicit_hydrogen=True) feat_mol = featurizer.featurize(rdkit_mol) coordinates = np.copy(feat_mol.coordinates) coordinates *= -1 # invert coordinates[:, 0] *= -1 # mirror mol = NPMol(atoms=feat_mol.atom_features, coordinates=feat_mol.coordinates) rec_mol = NPMol(atoms=feat_mol.atom_features, coordinates=coordinates) mse, mae = trainer._compute_position_accuracy(mol, rec_mol) np.testing.assert_allclose([mse, mae], [0, 0], atol=1e-5) if __name__ == '__main__': unittest.main()
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,977
rnaimehaom/deepmol
refs/heads/master
/tests/test_molecules.py
import tensorflow as tf import numpy as np import numpy.testing as npt from data.molecules import TFMolBatch, NPMol # sample molecules coordinates = np.array([[[0, 0, 0], [1, 0, 0], [-1, 0, 0]], [[0, 0, 0], [1, 1, 1], [1, 0, 0]]]) distance_matrix = np.array([[[0, 1, 1], [1, 0, 2], [1, 2, 0]], [[0, np.sqrt(3), 1], [np.sqrt(3), 0, np.sqrt(2)], [1, np.sqrt(2), 0]]]) distances = np.array([[1, 1, 2], [np.sqrt(3), 1, np.sqrt(2)]]) num_atoms = 3 num_distances = int(num_atoms * (num_atoms - 1) / 2) batch_size = 2 num_atom_types = 5 atom_types = [['C', 'C', 'C'], ['C', 'C', 'C']] atoms = np.zeros([batch_size, num_atoms, num_atom_types]) atoms[:, :, -1] = [0.3, 0.2, 0.1] atoms[:, :, 0] = 1 - atoms[:, :, -1] mask = np.ones([batch_size, num_atoms]) mask[:, :] = [0.7, 0.8, 0.9] num_labels = 2 labels = np.random.randn(batch_size, num_labels) class TestTFMolBatch(tf.test.TestCase): def test_distances_provided(self): atoms_ph = tf.placeholder(tf.float32, shape=[None, num_atoms, num_atom_types]) distances_ph = tf.placeholder(tf.float32, shape=[None, num_distances]) mols = TFMolBatch(atoms=atoms_ph, distances=distances_ph) with self.assertRaises(AttributeError): _ = mols.coordinates distance_matrix_tf = mols.distance_matrix with self.test_session() as sess: sess.run(tf.global_variables_initializer()) distance_matrix_np = sess.run(distance_matrix_tf, feed_dict={distances_ph: distances, atoms_ph: atoms}) self.assertAllClose(distance_matrix_np, distance_matrix) def test_distance_matrix_provided(self): atoms_ph = tf.placeholder(tf.float32, shape=[None, num_atoms, num_atom_types]) distance_matrix_ph = tf.placeholder(tf.float32, shape=[None, num_atoms, num_atoms]) mols = TFMolBatch(atoms=atoms_ph, distance_matrix=distance_matrix_ph) with self.assertRaises(AttributeError): _ = mols.coordinates distances_tf = mols.distances with self.test_session() as sess: sess.run(tf.global_variables_initializer()) distances_np = sess.run(distances_tf, feed_dict={distance_matrix_ph: distance_matrix, atoms_ph: atoms}) self.assertAllClose(distances_np, distances) def test_coordinates_provided(self): atoms_ph = tf.placeholder(tf.float32, shape=[None, num_atoms, num_atom_types]) coordinates_ph = tf.placeholder(tf.float32, shape=[None, num_atoms, 3]) mols_1 = TFMolBatch(atoms=atoms_ph, coordinates=coordinates_ph) mols_2 = TFMolBatch(atoms=atoms_ph, coordinates=coordinates_ph) distance_matrix_1_tf = mols_1.distance_matrix distances_1_tf = mols_1.distances distances_2_tf = mols_2.distances distance_matrix_2_tf = mols_2.distance_matrix with self.test_session() as sess: sess.run(tf.global_variables_initializer()) dist_1_np, dist_2_np, dist_mat_1_np, dist_mat_2_np = sess.run( [distances_1_tf, distances_2_tf, distance_matrix_1_tf, distance_matrix_2_tf], feed_dict={coordinates_ph: coordinates, atoms_ph: atoms}) self.assertAllClose(dist_1_np, distances) self.assertAllClose(dist_2_np, distances) self.assertAllClose(dist_mat_1_np, distance_matrix) self.assertAllClose(dist_mat_2_np, distance_matrix) def test_none_provided(self): atoms_ph = tf.placeholder(tf.float32, shape=[None, num_atoms, num_atom_types]) with self.assertRaises(ValueError): _ = TFMolBatch(atoms=atoms_ph) def test_labels(self): atoms_ph = tf.placeholder(tf.float32, shape=[None, num_atoms, num_atom_types]) coordinates_ph = tf.placeholder(tf.float32, shape=[None, num_atoms, 3]) labels_ph = tf.placeholder(tf.float32, shape=[None, num_labels]) mols = TFMolBatch(atoms=atoms_ph, coordinates=coordinates_ph) with self.assertRaises(AttributeError): _ = mols.labels mols = TFMolBatch(atoms=atoms_ph, coordinates=coordinates_ph, labels=labels_ph) labels_tf = mols.labels with self.test_session() as sess: sess.run(tf.global_variables_initializer()) labels_np = sess.run(labels_tf, feed_dict={coordinates_ph: coordinates, atoms_ph: atoms, labels_ph: labels}) self.assertAllClose(labels_np, labels) class TestNPMol(npt.TestCase): def test_none_provided(self): with self.assertRaises(ValueError): _ = NPMol(atoms=atoms) def test_distances_provided(self): mol = NPMol(atoms=atoms[0], distances=distances[0]) self.assertTrue(isinstance(mol.smiles, str)) npt.assert_allclose(mol.distance_matrix, distance_matrix[0]) npt.assert_equal(mol.coordinates.shape, coordinates[0].shape) def test_distance_matrix_provided(self): mol = NPMol(atoms=atoms[0], distance_matrix=distance_matrix[0]) npt.assert_allclose(mol.distances, distances[0]) self.assertTrue(isinstance(mol.smiles, str)) npt.assert_equal(mol.coordinates.shape, coordinates[0].shape) def test_coordinates_provided(self): mol = NPMol(atoms=atoms[0], coordinates=coordinates[0]) npt.assert_allclose(mol.distances, distances[0]) npt.assert_allclose(mol.distance_matrix, distance_matrix[0]) self.assertTrue(isinstance(mol.smiles, str)) def test_atom_types(self): mol = NPMol(atoms=atoms[0], coordinates=coordinates[0]) npt.assert_equal(mol.atoms, atom_types[0]) def test_padding_removal(self): p_coordinates = np.concatenate((coordinates[0], [[0, 0, 0]])) p_distance_matrix = np.pad(distance_matrix[0], ((0, 1), (0, 1)), mode='constant') p_distances = p_distance_matrix[np.triu_indices(4, 1)] p_atoms = np.concatenate((atoms[0], [[0, 0, 0, 0, 1]])) mol = NPMol(atoms=p_atoms, coordinates=p_coordinates, distance_matrix=p_distance_matrix, distances=p_distances) npt.assert_allclose(mol.distances, distances[0]) npt.assert_allclose(mol.distance_matrix, distance_matrix[0]) npt.assert_allclose(mol.coordinates, coordinates[0]) npt.assert_equal(mol.atoms, atom_types[0]) def test_batch_construction(self): mol_batch = NPMol.create_from_batch(batch_atoms=atoms, batch_distances=distances) for i in range(len(distances)): npt.assert_allclose(mol_batch[i].distances, distances[i]) npt.assert_allclose(mol_batch[i].distance_matrix, distance_matrix[i]) npt.assert_equal(mol_batch[i].atoms, atom_types[i]) self.assertTrue(isinstance(mol_batch[i].smiles, str)) def test_empty(self): atoms_empty = np.zeros([batch_size, num_atoms, num_atom_types]) atoms_empty[:, :, -1] = 1 mol_batch = NPMol.create_from_batch(batch_atoms=atoms_empty, batch_distances=distances) for mol in mol_batch: npt.assert_equal(mol.distance_matrix, np.zeros([0, 0])) npt.assert_equal(mol.coordinates, np.zeros([0, 3])) npt.assert_equal(mol.smiles, '') npt.assert_equal(mol.atoms, [])
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,978
rnaimehaom/deepmol
refs/heads/master
/tests/test_train_util.py
import unittest import numpy.testing as npt import os from train_util import CurveSmoother, ConfigReader import tensorflow as tf class TestCurveSmoother(unittest.TestCase): def test_smoothing_factor_range(self): with self.assertRaises(ValueError): CurveSmoother(-12) with self.assertRaises(ValueError): CurveSmoother(1.1) CurveSmoother(0.4) def test_smoothing(self): data = [-1, 2, 4, 10] smoothed_data_ref = [-1, 0.2, 1.72, 5.032] smoother = CurveSmoother(0.6) smoothed_data = [smoother.smooth(val) for val in data] npt.assert_allclose(smoothed_data, smoothed_data_ref) smoother = CurveSmoother(0) smoothed_data = [smoother.smooth(val) for val in data] npt.assert_allclose(smoothed_data, data) smoother = CurveSmoother(1) smoothed_data = [smoother.smooth(val) for val in data] npt.assert_allclose(smoothed_data, [data[0] for _ in data]) class TestConfigReader(unittest.TestCase): def test_reader(self): hparams_1 = tf.contrib.training.HParams(x=2, y=3, z=True) hparams_2 = tf.contrib.training.HParams(x=2.3, y=3, z=True) hparams_3 = tf.contrib.training.HParams(x=3.14, y=42, z=False) hparams_default = tf.contrib.training.HParams(x=1.8, y=2.9, z=False) tmpdir = 'unittest_configs' tmpfile_1 = os.path.join(tmpdir, '1.json') tmpfile_2 = os.path.join(tmpdir, '2.json') tmpfile_3 = os.path.join(tmpdir, '3.json') try: os.makedirs(tmpdir, exist_ok=True) with open(tmpfile_1, 'w') as f: f.write(hparams_1.to_json()) with open(tmpfile_2, 'w') as f: f.write(hparams_2.to_json()) config_reader = ConfigReader(tmpdir, hparams_default) new_configs = config_reader.get_new_hparam_configs() self.assertEqual(len(new_configs), 2) self.assertDictEqual(hparams_1.values(), new_configs['1'].values()) self.assertDictEqual(hparams_2.values(), new_configs['2'].values()) new_configs = config_reader.get_new_hparam_configs() self.assertEqual(len(new_configs), 0) os.remove(tmpfile_1) with open(tmpfile_3, 'w') as f: f.write(hparams_3.to_json()) new_configs = config_reader.get_new_hparam_configs() self.assertEqual(len(new_configs), 1) self.assertDictEqual(hparams_3.values(), new_configs['3'].values()) finally: os.remove(tmpfile_2) os.remove(tmpfile_3) os.rmdir(tmpdir) if __name__ == '__main__': unittest.main()
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,979
rnaimehaom/deepmol
refs/heads/master
/tests/test_molvae.py
import tensorflow as tf from model.molvae import MolVAE import numpy as np from data.molecules import TFMolBatch hparams = MolVAE.default_hparams() hparams.set_hparam('batch_size', 1) hparams.set_hparam('geometric_penalty_weight', 0.0) class TestGeometricPenalty(tf.test.TestCase): def test_geometric_penalty(self): """Create a three-atomic molecule where the interatomic distances violate the triangle inequality.""" batch_atom_decoded = np.zeros([1, 9, 5]) batch_atom_decoded[0, 0:3, 0] = 1 # three C atoms batch_atom_decoded[0, 3:9, -1] = 1 # rest is set to none/padded batch_dist_decoded = np.zeros([1, 36]) batch_dist_decoded[0, 0:2] = 1 # set two distances values to 1 batch_dist_decoded[0, 8] = 5 # and the third to 5 -> violation 5 - (1 + 1) = 3 decoded_atoms_ph = tf.placeholder(tf.float32, [1, 9, 5]) decoded_dist_ph = tf.placeholder(tf.float32, [1, 36]) decoded_mols = TFMolBatch(atoms=decoded_atoms_ph, distances=decoded_dist_ph) geom_pen = MolVAE(hparams, 9, 5).geometric_penalty(decoded_mols) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) loss_val = sess.run(geom_pen, feed_dict={decoded_dist_ph: batch_dist_decoded, decoded_atoms_ph: batch_atom_decoded}) self.assertAllClose(loss_val, 3.0) class TestReconstructionLoss(tf.test.TestCase): def test_reconstruction_loss(self): num_atoms, num_types = 5, 5 atoms = np.eye(num_types)[np.newaxis, :] coords = np.zeros([1, num_atoms, 3]) coords[0, :, 0] = np.arange(num_atoms) p1 = 0.6 p2 = (1 - p1) / (num_atoms - 1) l1, l2 = np.log(p1), np.log(p2) rec_atom_logits = (np.ones_like(atoms) - np.eye(num_types)) * l2 + np.eye(num_types) * l1 rec_coords = np.zeros_like(coords) rec_coords[0, :, 0] = np.linspace(0.1, 4.5, num=num_atoms) coord_ph = tf.placeholder_with_default(coords.astype(np.float32), coords.shape) atom_ph = tf.placeholder_with_default(atoms.astype(np.float32), atoms.shape) mols = TFMolBatch(atoms=atom_ph, coordinates=coord_ph) rec_coord_ph = tf.placeholder_with_default(rec_coords.astype(np.float32), rec_coords.shape) rec_atom_logits_ph = tf.placeholder_with_default(rec_atom_logits.astype(np.float32), rec_atom_logits.shape) rec_mols = TFMolBatch(atoms_logits=rec_atom_logits_ph, coordinates=rec_coord_ph) atom_loss = - l1 * num_atoms dist_loss = 0.2 / 6.0 gamma = 0.5 hparams.set_hparam('gamma', gamma) reconstruction_loss = MolVAE(hparams, num_atoms, num_types).reconstruction_loss(mols, rec_mols) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) loss_val = sess.run(reconstruction_loss) np.testing.assert_allclose(loss_val, gamma * atom_loss + (2 - gamma) * dist_loss, rtol=1e-4)
{"/model/mpnn.py": ["/model/message_passing.py", "/model/update_function.py", "/model/read_out.py", "/model/fc_nn.py", "/model/abstract_model.py"], "/model/molvae.py": ["/model/mpnn.py", "/model/fc_nn.py", "/data/molecules.py"], "/model/read_out.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/train_mpnn.py": ["/train_util.py", "/model/mpnn.py", "/data/featurizer.py"], "/tests/test_read_out.py": ["/model/read_out.py"], "/tests/test_qm9_loader.py": ["/data/qm9_loader.py", "/data/featurizer.py"], "/train_vae.py": ["/train_util.py", "/model/molvae.py", "/data/featurizer.py", "/data/molecules.py"], "/data/qm9_loader.py": ["/data/standardization.py"], "/tests/test_featurizer.py": ["/data/featurizer.py"], "/model/update_function.py": ["/model/abstract_model.py"], "/train_util.py": ["/data/qm9_loader.py", "/data/molecules.py"], "/tests/test_standardization.py": ["/data/standardization.py"], "/model/message_passing.py": ["/model/abstract_model.py", "/model/fc_nn.py"], "/model/fc_nn.py": ["/model/abstract_model.py"], "/tests/test_pos_acc.py": ["/train_vae.py", "/data/featurizer.py", "/data/molecules.py"], "/tests/test_molecules.py": ["/data/molecules.py"], "/tests/test_train_util.py": ["/train_util.py"], "/tests/test_molvae.py": ["/model/molvae.py", "/data/molecules.py"]}
41,980
shuohan/espreso
refs/heads/master
/tests/test_loss.py
#!/usr/bin/env python import numpy as np import torch from ssp.loss import GANLoss, SmoothnessLoss, CenterLoss, BoundaryLoss def test_loss(): x = np.ones([10, 1, 1]) * (-1) gan_loss_func = GANLoss().cuda() gan_loss = gan_loss_func(torch.tensor(x).cuda(), False) ref = -np.log(1 - 1 / (1 + np.exp(-x))).mean() assert np.allclose(ref, gan_loss.cpu().detach().numpy()) gan_loss = gan_loss_func(torch.tensor(x).cuda(), True) ref = -np.log(1 / (1 + np.exp(-x))).mean() assert np.allclose(ref, gan_loss.cpu().detach().numpy()) kernel = torch.tensor([1, 0, 2, -1, 4, 3], dtype=torch.float32) kernel = kernel[None, None, ..., None] smoothness_loss_func = SmoothnessLoss() smoothness_loss = smoothness_loss_func(kernel) norm = 1 ** 2 + 2 ** 2 +3 ** 2 + 5 ** 2 + 1 ** 2 assert smoothness_loss == norm kernel = torch.tensor([0.6, 0.1, 0.3], dtype=torch.float32) center_loss_func = CenterLoss(len(kernel)) center_loss = center_loss_func(kernel) assert np.allclose(center_loss.item(), 0.09) kernel = -torch.arange(15)[None, None, ..., None] boundary_loss_func = BoundaryLoss(len(kernel.squeeze())) boundary_loss = boundary_loss_func(kernel) ref = 0 * 0.10316994 + 1 * 0.07688365 + 14 * 0.10316994 + 13 * 0.07688365 assert np.round(boundary_loss, 4) == np.round(ref, 4) if __name__ == '__main__': test_loss()
{"/tests/test_loss.py": ["/ssp/loss.py"], "/ssp/train.py": ["/ssp/config.py", "/ssp/loss.py", "/ssp/utils.py"], "/tests/test_networks.py": ["/ssp/network.py"], "/scripts/compare_kernel.py": ["/ssp/utils.py"], "/ssp/network.py": ["/ssp/config.py"], "/tests/test_fwhm.py": ["/ssp/utils.py"], "/tests/test_kernel.py": ["/ssp/network.py"], "/scripts/train2d.py": ["/ssp/config.py", "/ssp/train.py", "/ssp/network.py", "/ssp/utils.py"]}
41,981
shuohan/espreso
refs/heads/master
/ssp/train.py
"""Functions and classes to train the algorithm. """ import numpy as np import torch import torch.nn.functional as F from collections.abc import Iterable import matplotlib.pyplot as plt from pathlib import Path from enum import Enum from pytorch_trainer.observer import SubjectObserver from pytorch_trainer.train import Trainer from pytorch_trainer.utils import NamedData from pytorch_trainer.save import ThreadedSaver, ImageThread, SavePlot from .config import Config from .loss import GANLoss, SmoothnessLoss, CenterLoss, BoundaryLoss from .utils import calc_fwhm class SaveKernel(SavePlot): """Saves the kernel to a .png and a .npy files. """ def save(self, filename, kernel): kernel = kernel.squeeze().numpy() self._save_plot(filename, kernel) self._save_npy(filename, kernel) def _save_npy(self, filename, kernel): filename = str(filename) + '.npy' np.save(filename, kernel) def _save_plot(self, filename, kernel): filename = str(filename) + '.png' fwhm, left, right = calc_fwhm(kernel) max_val = np.max(kernel) plt.cla() plt.plot(kernel, '-o') plt.plot([left, left], [0, max_val], 'k--') plt.plot([right, right], [0, max_val], 'k--') plt.text((left + right) / 2, max_val / 2, fwhm, ha='center') plt.grid(True) plt.tight_layout() plt.gcf().savefig(filename) class KernelSaver(ThreadedSaver): """Saves the kernel after each epoch. """ def __init__(self, dirname, step=100, save_init=False): super().__init__(dirname, save_init=save_init) self.step = step Path(self.dirname).mkdir(parents=True, exist_ok=True) def _init_thread(self): save_kernel = SaveKernel() return ImageThread(save_kernel, self.queue) def _check_subject_type(self, subject): assert isinstance(subject, TrainerHRtoLR) def update_on_epoch_end(self): if self.subject.epoch_ind % self.step == 0: self._save() def _save(self): kernel = self.subject.kernel_net.kernel pattern = 'epoch-%%0%dd' % len(str(self.subject.num_epochs)) pattern = str(Path(self.dirname, pattern)) filename = pattern % self.subject.epoch_ind self.queue.put(NamedData(filename, kernel)) avg_kernel = self.subject.kernel_net.avg_kernel.cpu() pattern = 'avg_epoch-%%0%dd' % len(str(self.subject.num_epochs)) pattern = str(Path(self.dirname, pattern)) filename = pattern % self.subject.epoch_ind self.queue.put(NamedData(filename, avg_kernel)) class KernelEvaluator(SubjectObserver): """Evaluates the difference between the esitmated and the true kernels. """ def __init__(self, true_kernel, kernel_length): super().__init__() self.kernel_length = kernel_length true_kernel = true_kernel.squeeze() left_pad = (self.kernel_length - len(true_kernel)) // 2 right_pad = self.kernel_length - len(true_kernel) - left_pad true_kernel = np.pad(true_kernel, (left_pad, right_pad)) self.true_kernel = torch.tensor(true_kernel) self.mse = np.nan def cuda(self): self.true_kernel = self.true_kernel.cuda() return self def update_on_batch_end(self): if self.epoch_ind % Config().eval_step == 0: self._calc_mae() self.notify_observers_on_batch_end() def update_on_epoch_end(self): if self.epoch_ind % Config().eval_step == 0: self.notify_observers_on_epoch_end() def _calc_mae(self): est_kernel = self.subject.kernel_net.avg_kernel.squeeze() with torch.no_grad(): self.mae = F.l1_loss(self.true_kernel, est_kernel) @property def batch_size(self): return self.subject.batch_size @property def num_batches(self): return self.subject.num_batches @property def num_epochs(self): return self.subject.num_epochs @property def epoch_ind(self): return self.subject.epoch_ind @property def batch_ind(self): return self.subject.batch_ind class TrainerHRtoLR(Trainer): """Trains GAN from high-resolution to low-resolution. Attributes: kernel_net (psf_est.network.KernelNet1d): The kernel estimation network. lr_disc (psf_est.network.LowResDiscriminator1d): The low-resolution patches discriminator. kn_optim (torch.optim.Optimizer): The :attr:`kernel_net` optimizer. lrd_optim (torch.optim.Optimizer): The :attr:`lr_dics` optimizer. hr_loader (torch.nn.data.DataLoader): Yields high-resolution patches. lr_loader (torch.nn.data.DataLoader): Yields low-resolution patches. scale_factor (iterable[float]): The upsampling scaling factor. It should be greater than 1. kn_gan_loss (torch.Tensor): The GAN loss for :attr:`kernel_net`. kn_tot_loss (torch.Tensor): The total loss for :attr:`kernel_net`. smoothness_loss (torch.Tensor): The kernel smoothness regularization. center_loss (torch.Tensor): The kernel center regularization. boundary_loss (torch.Tensor): The kernel boundary regularization. lrd_tot_loss (torch.Tensor): The total loss for :attr:`lr_disc`. """ def __init__(self, kernel_net, lr_disc, kn_optim, lrd_optim, hr_loader, lr_loader): super().__init__(Config().num_epochs) self.kernel_net = kernel_net self.lr_disc = lr_disc self.kn_optim = kn_optim self.lrd_optim = lrd_optim self.hr_loader = hr_loader self.lr_loader = lr_loader self._check_data_loader_shapes() self.scale_factor = Config().scale_factor self._gan_loss_func = GANLoss().cuda() self._smoothness_loss_func = SmoothnessLoss().cuda() self._center_loss_func = CenterLoss(Config().kernel_length).cuda() self._boundary_loss_func = BoundaryLoss(Config().kernel_length).cuda() self.kn_gan_loss = np.nan self.kn_tot_loss = np.nan self.smoothness_loss = np.nan self.center_loss = np.nan self.boundary_loss = np.nan self.lrd_tot_loss = np.nan self._batch_ind = -1 self._hr = None self._hr_cuda = None self._hr_names = None self._lr = None self._lr_cuda = None self._lr_names = None self._blur_cuda = None self._alias_cuda = None def _check_data_loader_shapes(self): """Checks the shapes of :attr:`hr_loader` and :attr:`lr_loader`.""" assert len(self.hr_loader) == len(self.lr_loader) assert self.hr_loader.batch_size == self.lr_loader.batch_size def get_model_state_dict(self): return {'kernel_net': self.kernel_net.state_dict(), 'lr_disc': self.lr_disc.state_dict()} def get_optim_state_dict(self): return {'kn_optim': self.kn_optim.state_dict(), 'lrd_optim': self.lrd_optim.state_dict()} def train(self): """Trains the algorithm.""" self.notify_observers_on_train_start() for self._epoch_ind in range(self.num_epochs): self.notify_observers_on_epoch_start() for self._batch_ind, batch \ in enumerate(zip(self.hr_loader, self.lr_loader)): self.notify_observers_on_batch_start() self._parse_batch(batch) self._train_on_batch() self.notify_observers_on_batch_end() self.notify_observers_on_epoch_end() self.notify_observers_on_train_end() def _parse_batch(self, batch): self._hr_names = batch[0].name self._hr = batch[0].data self._hr_cuda = self._hr.cuda() self._lr_names = batch[1].name self._lr = batch[1].data self._lr_cuda = self._lr.cuda() def _train_on_batch(self): """Trains the networks using a pair of HR and LR data.""" if self.epoch_ind % Config().lrd_update_step == 0: self._train_lr_disc() if self.epoch_ind % Config().kn_update_step == 0: self._train_kernel_net() self.kernel_net.update_kernel() def _train_kernel_net(self): """Trains the generator :attr:`kernel_net`.""" self.kn_optim.zero_grad() self._blur_cuda = self.kernel_net(self._hr_cuda) self._alias_cuda = self._create_aliasing(self._blur_cuda) self._lrd_pred_kn = self.lr_disc(self._alias_cuda) self.kn_gan_loss = self._gan_loss_func(self._lrd_pred_kn, True) self.kn_tot_loss = self.kn_gan_loss + self._calc_reg() self.kn_tot_loss.backward() self.kn_optim.step() def _create_aliasing(self, patches): """Creates aliasing on patches.""" down_scale = [1 / self.scale_factor, 1] mode = Config().interp_mode results = F.interpolate(patches, scale_factor=down_scale, mode=mode) # up_scale = [self.scale_factor, 1] # results = F.interpolate(results, scale_factor=up_scale, mode=mode) return results def _calc_reg(self): """Calculates kernel regularization.""" kernel = self.kernel_net.kernel_cuda self.smoothness_loss = self._smoothness_loss_func(kernel) self.center_loss = self._center_loss_func(kernel) self.boundary_loss = self._boundary_loss_func(kernel) center_weight = Config().center_loss_weight # step = center_weight / 2000 # center_weight = max(0, (2000 - self.epoch_ind) * step) loss = Config().smoothness_loss_weight * self.smoothness_loss \ + center_weight * self.center_loss \ + Config().boundary_loss_weight * self.boundary_loss return loss def _train_lr_disc(self): """Trains the low-resolution discriminator :attr:`lr_disc`.""" self.lrd_optim.zero_grad() self._lrd_pred_real = self.lr_disc(self._lr_cuda) with torch.no_grad(): alias = self._create_aliasing(self.kernel_net(self._hr_cuda)) self._lrd_pred_fake = self.lr_disc(alias.detach()) self._lrd_real_loss = self._gan_loss_func(self._lrd_pred_real, True) self._lrd_fake_loss = self._gan_loss_func(self._lrd_pred_fake, False) self.lrd_tot_loss = self._lrd_real_loss + self._lrd_fake_loss self.lrd_tot_loss.backward() self.lrd_optim.step() @property def num_batches(self): return len(self.hr_loader) @property def batch_size(self): return self.hr_loader.batch_size @property def batch_ind(self): return self._batch_ind + 1 @property def lr(self): """Returns the current named low-resolution patches on CPU.""" return NamedData(name=self._lr_names, data=self._lr.cpu()) @property def hr(self): """Returns the current named high-resolution patches on CPU.""" return NamedData(name=self._hr_names, data=self._hr.cpu()) @property def blur(self): """Returns the current estimated blurred patches on CPU.""" return self._blur_cuda.detach().cpu() @property def alias(self): """Returns the current estimated aliased patches on CPU.""" return self._alias_cuda.detach().cpu() @property def lrd_pred_kn(self): """Returns the :attr:`lr_disc` output to update :attr:`kernel_net.""" return self._lrd_pred_kn.detach().cpu() @property def lrd_pred_real(self): """Returns the :attr:`lr_disc` output of a true LR patch.""" return self._lrd_pred_real.detach().cpu() @property def lrd_pred_fake(self): """Returns the :attr:`lr_disc` output of a generated patch.""" return self._lrd_pred_fake.detach().cpu() class InitKernelType(str, Enum): """The type of kernel to initialize to. Attributes: IMPULSE (str): Initialize to an impulse function. GAUSSIAN (str): Initialize to a Gaussian function. RECT (str): Initialize to a rect function. NONE (str): Do not initialize the kernel, i.e. the kernel is random. """ IMPULSE = 'impulse' GAUSSIAN = 'guassian' RECT = 'rect' NONE = 'none' def create_init_kernel(init_kernel_type, scale_factor, shape): """Creates the kernel to initialize. Args: init_kernel_type (str or InitKernelType): The type of the initialization. scale_factor (float): The scale factor (greater than 1). shape (iterable[int]): The shape of the kernel. """ init_kernel_type = InitKernelType(init_kernel_type) if init_kernel_type is InitKernelType.IMPULSE: kernel = torch.zeros(*shape, dtype=torch.float32) kernel[:, :, shape[2]//2, ...] = 1 else: raise NotImplementedError return kernel class TrainerKernelInit(Trainer): """Initializes the kernel using simulated HR and LR pairs. """ def __init__(self, kernel_net, optim, dataloader, init_type='impulse'): super().__init__(Config().num_init_epochs) self.kernel_net = kernel_net self.optim = optim self.dataloader = dataloader self.init_type = init_type raise NotImplementedError def _init_kernel(self): """Initializes the kernel.""" ref_kernel = self._create_init_kernel() self.init_optim.zero_grad() self._blur_cuda = self.kernel_net(self._hr_cuda) self._ref_cuda = F.conv2d(self._hr_cuda, ref_kernel) self.init_loss = self._init_loss_func(self._blur_cuda, self._ref_cuda) self.init_loss.backward() self.init_optim.step() def _create_init_kernel(self): """Creates the kernel to initialize to.""" shape = list(self.kernel_net.impulse.shape) shape[2] = self.kernel_net.kernel_size kernel_type = self.init_kernel_type kernel = create_init_kernel(kernel_type, self.scale_factor, shape) return kernel.cuda() @property def ref(self): """Returns the blurred patches with a reference kernel on CPU.""" return self._ref_cuda.detach().cpu()
{"/tests/test_loss.py": ["/ssp/loss.py"], "/ssp/train.py": ["/ssp/config.py", "/ssp/loss.py", "/ssp/utils.py"], "/tests/test_networks.py": ["/ssp/network.py"], "/scripts/compare_kernel.py": ["/ssp/utils.py"], "/ssp/network.py": ["/ssp/config.py"], "/tests/test_fwhm.py": ["/ssp/utils.py"], "/tests/test_kernel.py": ["/ssp/network.py"], "/scripts/train2d.py": ["/ssp/config.py", "/ssp/train.py", "/ssp/network.py", "/ssp/utils.py"]}
41,982
shuohan/espreso
refs/heads/master
/isbi/get_phantom_pics.py
#!/usr/bin/env python import nibabel as nib import numpy as np from pathlib import Path from PIL import Image from image_processing_3d import quantile_scale from scipy.ndimage import zoom dirname = '/data/phantom/data' basename = 'SUPERRES-ADNIPHANTOM_20200830_PHANTOM-T2-TSE-2D-CORONAL-PRE-ACQ1-4mm-gapn2mm_resampled.nii' filename = Path(dirname, basename) obj = nib.load(filename) data = obj.get_fdata(dtype=np.float32) data = quantile_scale(data, upper_pct=0.99, upper_th=1) * 255 th_slice_ind = 130 in_slice_ind = 30 factor = 2 ysize = 119 xsize = 60 xstart = 60 ystart = 40 in_im = data[:, :, in_slice_ind].astype(np.uint8).T in_im = in_im[xstart : xstart + xsize, ystart : ystart + ysize] xstart = 90 ystart = 40 th_im = data[th_slice_ind, :, :].astype(np.uint8).T th_im = zoom(th_im, (factor, 1), order=0, prefilter=False) th_im = th_im[xstart : xstart + xsize, ystart : ystart + ysize] in_im = Image.fromarray(in_im) in_im.save('phantom_4_2_in.png') th_im = Image.fromarray(th_im) th_im.save('phantom_4_2_th.png') basename = 'SUPERRES-ADNIPHANTOM_20200830_PHANTOM-T2-TSE-2D-CORONAL-PRE-ACQ1-4mm-gap1mm_resampled.nii' filename = Path(dirname, basename) obj = nib.load(filename) data = obj.get_fdata(dtype=np.float32) data = quantile_scale(data, upper_pct=0.99, upper_th=1) * 255 factor = 5 in_slice_ind = 12 xstart = 60 ystart = 40 in_im = data[:, :, in_slice_ind].astype(np.uint8).T in_im = in_im[xstart : xstart + xsize, ystart : ystart + ysize] xstart = 90 ystart = 40 th_im = data[th_slice_ind, :, :].astype(np.uint8).T th_im = zoom(th_im, (factor, 1), order=0, prefilter=False) th_im = th_im[xstart : xstart + xsize, ystart : ystart + ysize] in_im = Image.fromarray(in_im) in_im.save('phantom_4_5_in.png') th_im = Image.fromarray(th_im) th_im.save('phantom_4_5_th.png')
{"/tests/test_loss.py": ["/ssp/loss.py"], "/ssp/train.py": ["/ssp/config.py", "/ssp/loss.py", "/ssp/utils.py"], "/tests/test_networks.py": ["/ssp/network.py"], "/scripts/compare_kernel.py": ["/ssp/utils.py"], "/ssp/network.py": ["/ssp/config.py"], "/tests/test_fwhm.py": ["/ssp/utils.py"], "/tests/test_kernel.py": ["/ssp/network.py"], "/scripts/train2d.py": ["/ssp/config.py", "/ssp/train.py", "/ssp/network.py", "/ssp/utils.py"]}
41,983
shuohan/espreso
refs/heads/master
/isbi/calc_simu_error.py
#!/usr/bin/env python import numpy as np import pandas as pd import nibabel as nib from pathlib import Path from skimage.metrics import peak_signal_noise_ratio as calc_psnr from skimage.metrics import structural_similarity as calc_ssim import matplotlib.pyplot as plt from collections import OrderedDict from psf_est.utils import calc_fwhm from lr_simu.simu import ThroughPlaneSimulatorCPU est_dirname = '../tests/results_isbi2021_simu_final' ref_dirname = '/data/phantom/simu' est_pattern = 'simu_type-%s_fwhm-%s_scale-%s_len-13_smooth-1.0/kernel/avg_epoch-30000.npy' ref_pattern = 'SUPERRES-ADNIPHANTOM_20200711_PHANTOM-T2-TSE-3D-CORONAL-PRE-ACQ1-01mm_resampled_type-%s_fwhm-%s_scale-%s_len-13_kernel.npy' orig_filename = '/data/phantom/data/SUPERRES-ADNIPHANTOM_20200711_PHANTOM-T2-TSE-3D-CORONAL-PRE-ACQ1-01mm_resampled.nii' orig_image = nib.load(orig_filename).get_fdata(dtype=np.float32) data_range = np.max(orig_image) - np.min(orig_image) types = ['gauss', 'rect'] fwhm = {'gauss': ['2p0', '4p0', '8p0'], 'rect': ['3p0', '5p0', '9p0']} scale = ['0p5', '0p25', '0p125'] df = list() for t in types: for f in fwhm[t]: for s in scale: est_filename = Path(est_dirname, est_pattern % (t, f, s)) ref_filename = Path(ref_dirname, ref_pattern % (t, f, s)) est = np.load(est_filename).squeeze() ref = np.load(ref_filename).squeeze() left = (len(est) - len(ref)) // 2 right = len(est) - len(ref) - left ref = np.pad(ref, (left, right)) est_fwhm = calc_fwhm(est)[0] ref_fwhm = calc_fwhm(ref)[0] ss = float(s.replace('p', '.')) est_simulator = ThroughPlaneSimulatorCPU(est, scale_factor=ss) ref_simulator = ThroughPlaneSimulatorCPU(ref, scale_factor=ss) est_im = est_simulator.simulate(orig_image) ref_im = ref_simulator.simulate(orig_image) fwhm_error = np.abs(est_fwhm - ref_fwhm) prof_error = np.sum(np.abs(est - ref)) # data_range = np.max(ref_im) - np.min(ref_im) psnr = calc_psnr(ref_im, est_im, data_range=data_range) ssim = calc_ssim(ref_im, est_im) # plt.subplot(2, 3, 1) # plt.imshow(est_im[:, :, est_im.shape[2]//2], cmap='gray') # plt.subplot(2, 3, 2) # plt.imshow(est_im[:, est_im.shape[1]//2, :], cmap='gray') # plt.subplot(2, 3, 3) # plt.imshow(est_im[est_im.shape[0]//2, :, :], cmap='gray') # # plt.subplot(2, 3, 4) # plt.imshow(ref_im[:, :, ref_im.shape[2]//2], cmap='gray') # plt.subplot(2, 3, 5) # plt.imshow(ref_im[:, ref_im.shape[1]//2, :], cmap='gray') # plt.subplot(2, 3, 6) # plt.imshow(ref_im[ref_im.shape[0]//2, :, :], cmap='gray') # plt.gcf().savefig('%s_%s_%s_error.png' % (t, s, f)) tab = OrderedDict([('type', t), ('fwhm', f.replace('p', '.')), ('scale', s.replace('p', '.')), ('fwhm error', '%.2f' % fwhm_error), ('profile error', '%.2f' % prof_error), ('psnr', '%.1f' % psnr), ('ssim', '%.2f' % ssim)]) df.append(tab) df = pd.DataFrame(df).T print(df)
{"/tests/test_loss.py": ["/ssp/loss.py"], "/ssp/train.py": ["/ssp/config.py", "/ssp/loss.py", "/ssp/utils.py"], "/tests/test_networks.py": ["/ssp/network.py"], "/scripts/compare_kernel.py": ["/ssp/utils.py"], "/ssp/network.py": ["/ssp/config.py"], "/tests/test_fwhm.py": ["/ssp/utils.py"], "/tests/test_kernel.py": ["/ssp/network.py"], "/scripts/train2d.py": ["/ssp/config.py", "/ssp/train.py", "/ssp/network.py", "/ssp/utils.py"]}
41,984
shuohan/espreso
refs/heads/master
/isbi/get_simu_profiles.py
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from pathlib import Path import matplotlib from psf_est.utils import calc_fwhm def plot(est, ref, filename): left = (len(est) - len(ref)) // 2 right = len(est) - len(ref) - left ref = np.pad(ref, (left, right)) font = {'size': 8} matplotlib.rc('font', **font) est_hm = np.max(est) / 2 est_fwhm, est_left, est_right = calc_fwhm(est) ref_hm = np.max(ref) / 2 ref_fwhm, ref_left, ref_right = calc_fwhm(ref) dpi = 100 figx = 168 figy = 120 figl = 0.24 figr = 0.01 figb = 0.20 figt = 0.05 position = [figl, figb, 1 - figl - figr, 1 - figb - figt] fig = plt.figure(figsize=(figx/dpi, figy/dpi), dpi=dpi) ax = fig.add_subplot(111, position=position) plt.plot(ref, '-', color='tab:red') plt.plot([ref_left, ref_right], [ref_hm] * 2, '--o', color='tab:red', markersize=5) plt.plot(est, '-', color='tab:blue') plt.plot([est_left, est_right], [est_hm] * 2, '--o', color='tab:blue', markersize=5) ylim = ax.get_ylim() print(np.diff(ylim)[0] / ((1 - figt - figb) * figy)) offset = np.diff(ylim)[0] / ((1 - figt - figb) * figy) * 12 print(offset) tl = np.max((est_right, ref_right)) + 1.5 est_tv = (est_hm + ref_hm) * 0.5 + offset / 2 ref_tv = (est_hm + ref_hm) * 0.5 - offset / 2 plt.text(tl, ref_tv, '%.2f' % ref_fwhm, color='tab:red', va='center') plt.text(tl, est_tv, '%.2f' % est_fwhm, color='tab:blue', va='center') plt.xticks(np.arange(0, len(est), 4)) plt.yticks([0, 0.05, 0.10]) plt.ylim([-0.01, 0.15]) plt.savefig(filename) if __name__ == '__main__': est_dirname = '../tests/results_isbi2021_simu_final' est_basename = 'simu_type-gauss_fwhm-8p0_scale-0p25_len-13_smooth-1.0/kernel/avg_epoch-30000.npy' est_filename = Path(est_dirname, est_basename) est = np.load(est_filename).squeeze() ref_dirname = '/data/phantom/simu' ref_basename = 'SUPERRES-ADNIPHANTOM_20200711_PHANTOM-T2-TSE-3D-CORONAL-PRE-ACQ1-01mm_resampled_type-gauss_fwhm-8p0_scale-0p25_len-13_kernel.npy' ref_filename = Path(ref_dirname, ref_basename) ref = np.load(ref_filename).squeeze() plot(est, ref, 'gauss_kernel.pdf') est_basename = 'simu_type-rect_fwhm-9p0_scale-0p5_len-13_smooth-1.0/kernel/avg_epoch-30000.npy' est_filename = Path(est_dirname, est_basename) est = np.load(est_filename).squeeze() ref_dirname = '/data/phantom/simu' ref_basename = 'SUPERRES-ADNIPHANTOM_20200711_PHANTOM-T2-TSE-3D-CORONAL-PRE-ACQ1-01mm_resampled_type-rect_fwhm-9p0_scale-0p5_len-13_kernel.npy' ref_filename = Path(ref_dirname, ref_basename) ref = np.load(ref_filename).squeeze() plot(est, ref, 'rect_kernel.pdf')
{"/tests/test_loss.py": ["/ssp/loss.py"], "/ssp/train.py": ["/ssp/config.py", "/ssp/loss.py", "/ssp/utils.py"], "/tests/test_networks.py": ["/ssp/network.py"], "/scripts/compare_kernel.py": ["/ssp/utils.py"], "/ssp/network.py": ["/ssp/config.py"], "/tests/test_fwhm.py": ["/ssp/utils.py"], "/tests/test_kernel.py": ["/ssp/network.py"], "/scripts/train2d.py": ["/ssp/config.py", "/ssp/train.py", "/ssp/network.py", "/ssp/utils.py"]}
41,985
shuohan/espreso
refs/heads/master
/tests/compare_conv1d_conv2d.py
#!/usr/bin/env python import torch class PermConv(torch.nn.Module): def __init__(self): super().__init__() self.conv = torch.nn.Conv1d(64, 256, 3, bias=False) def forward(self, x): nb, nc, nx, ny = x.shape output = x.permute(0, 2, 1, 3) output = output.reshape(nb * nx, nc, ny) output = self.conv(output) output = output.view(nb, nx, 256, ny - 2) output = output.permute(0, 2, 1, 3) return output x = torch.rand(10, 64, 128, 128).cuda() # nb, nc, nx, ny = x.shape # x = x.permute(0, 2, 1, 3) # x = x.reshape(nb * nx, nc, ny) torch.manual_seed(0) conv2 = torch.nn.Conv2d(64, 256, (3, 1), bias=False).cuda() start = torch.cuda.Event(enable_timing=True) end = torch.cuda.Event(enable_timing=True) start.record() out2 = conv2(x) y = torch.sum(out2) y.backward() end.record() torch.cuda.synchronize() print(start.elapsed_time(end)) torch.manual_seed(0) conv1 = PermConv().cuda() start = torch.cuda.Event(enable_timing=True) end = torch.cuda.Event(enable_timing=True) start.record() out1 = conv1(x) y = torch.sum(out1) y.backward() end.record() torch.cuda.synchronize() print(start.elapsed_time(end)) start = torch.cuda.Event(enable_timing=True) end = torch.cuda.Event(enable_timing=True) start.record() out2 = conv2(x) y = torch.sum(out2) y.backward() end.record() torch.cuda.synchronize() print(start.elapsed_time(end))
{"/tests/test_loss.py": ["/ssp/loss.py"], "/ssp/train.py": ["/ssp/config.py", "/ssp/loss.py", "/ssp/utils.py"], "/tests/test_networks.py": ["/ssp/network.py"], "/scripts/compare_kernel.py": ["/ssp/utils.py"], "/ssp/network.py": ["/ssp/config.py"], "/tests/test_fwhm.py": ["/ssp/utils.py"], "/tests/test_kernel.py": ["/ssp/network.py"], "/scripts/train2d.py": ["/ssp/config.py", "/ssp/train.py", "/ssp/network.py", "/ssp/utils.py"]}
41,986
shuohan/espreso
refs/heads/master
/tests/test_networks.py
#!/usr/bin/env python import torch from pathlib import Path from pytorchviz import make_dot from ssp.network import KernelNet1d, KernelNet2d from ssp.network import LowResDiscriminator1d, LowResDiscriminator2d def test_networks(): dirname = Path('results_networks') dirname.mkdir(exist_ok=True) patch1d = torch.rand(2, 1, 64).cuda() patch2d = torch.rand(2, 1, 64, 64).cuda() kn = KernelNet1d().cuda() print(kn) assert kn(patch1d).shape == (2, 1, 44) assert kn.input_size_reduced == 20 kn_dot = make_dot(patch1d, kn) kn_dot.render(dirname.joinpath('kn1d')) kn = KernelNet2d().cuda() print(kn) assert kn(patch2d).shape == (2, 1, 44, 64) assert kn.input_size_reduced == 20 kn_dot = make_dot(patch2d, kn) kn_dot.render(dirname.joinpath('kn2d')) lrd = LowResDiscriminator1d().cuda() print(lrd) assert lrd(patch1d).shape == (2, 1, 49) lrd_dot = make_dot(patch1d, lrd) lrd_dot.render(dirname.joinpath('lrd1d')) lrd = LowResDiscriminator2d().cuda() print(lrd) assert lrd(patch2d).shape == (2, 1, 49, 64) lrd_dot = make_dot(patch2d, lrd) lrd_dot.render(dirname.joinpath('lrd2d')) if __name__ == '__main__': test_networks()
{"/tests/test_loss.py": ["/ssp/loss.py"], "/ssp/train.py": ["/ssp/config.py", "/ssp/loss.py", "/ssp/utils.py"], "/tests/test_networks.py": ["/ssp/network.py"], "/scripts/compare_kernel.py": ["/ssp/utils.py"], "/ssp/network.py": ["/ssp/config.py"], "/tests/test_fwhm.py": ["/ssp/utils.py"], "/tests/test_kernel.py": ["/ssp/network.py"], "/scripts/train2d.py": ["/ssp/config.py", "/ssp/train.py", "/ssp/network.py", "/ssp/utils.py"]}
41,987
shuohan/espreso
refs/heads/master
/ssp/utils.py
import torch import numpy as np from scipy.interpolate import interp1d from torch.nn.functional import interpolate def calc_patch_size(patch_size, scale_factor, nz): """Calculates the patch size. Args: patch_size (int): The size of the low-resolution patches. scale_factor (float): The scale factor > 1. nz (int): The size of low-resolution direction. Returns ------- hr_patch_size: int The calculated high-resolution patch size. lr_patch_size: int The calculated low-resolution patch size. """ lr_patch_size = np.minimum(patch_size, nz) image = torch.rand(1, 1, lr_patch_size, lr_patch_size).float() up = interpolate(image, scale_factor=scale_factor, mode='bilinear') hr_patch_size = up.shape[2] down = interpolate(up, scale_factor=1/scale_factor, mode='bilinear') lr_patch_size = down.shape[2] return hr_patch_size, lr_patch_size def calc_fwhm(kernel): """Calculates the full width at half maximum (FWHM) using linear interp. Args: kernel (numpy.ndarray): The kernel to calculat the FWHM from. Returns ------- fwhm: float The calculated FWHM. It is equal to ``right - left``. left: float The position of the left of the FWHM. right: float The position of the right of the FWHM. """ kernel = kernel.squeeze() half_max = float(np.max(kernel)) / 2 indices = np.where(kernel > half_max)[0] left = indices[0] if left > 0: interp = interp1d((kernel[left-1], kernel[left]), (left - 1, left)) left = interp(half_max) right = indices[-1] if right < len(kernel) - 1: interp = interp1d((kernel[right+1], kernel[right]), (right + 1, right)) right = interp(half_max) fwhm = right - left return fwhm, left, right
{"/tests/test_loss.py": ["/ssp/loss.py"], "/ssp/train.py": ["/ssp/config.py", "/ssp/loss.py", "/ssp/utils.py"], "/tests/test_networks.py": ["/ssp/network.py"], "/scripts/compare_kernel.py": ["/ssp/utils.py"], "/ssp/network.py": ["/ssp/config.py"], "/tests/test_fwhm.py": ["/ssp/utils.py"], "/tests/test_kernel.py": ["/ssp/network.py"], "/scripts/train2d.py": ["/ssp/config.py", "/ssp/train.py", "/ssp/network.py", "/ssp/utils.py"]}
41,988
shuohan/espreso
refs/heads/master
/scripts/compare_kernel.py
#!/usr/bin/env python import argparse parser = argparse.ArgumentParser() parser.add_argument('-i', '--input-kernel', help='Input image.') parser.add_argument('-r', '--reference-kernel', help='Input image.') parser.add_argument('-o', '--output-filename', help='Output directory.') args = parser.parse_args() import numpy as np import matplotlib.pyplot as plt from pathlib import Path from ssp.utils import calc_fwhm def plot_kernel(ax, kernel, fwhm, left, right, vp=0.5, color='b'): ax.plot(kernel, color, marker='o') ax.plot([left] * 2, [0, np.max(kernel)], color + '--') ax.plot([right] * 2, [0, np.max(kernel)], color + '--') # ax.plot([0, len(kernel)-1], [np.max(kernel)/2] * 2, color + '--') ax.text((left + right) / 2, vp * np.max(kernel), '%.4f' % fwhm, ha='center', color=color) Path(args.output_filename).parent.mkdir(exist_ok=True, parents=True) in_kernel = np.load(args.input_kernel).squeeze() ref_kernel = np.load(args.reference_kernel).squeeze() left_padding = (len(in_kernel) - len(ref_kernel)) // 2 right_padding = len(in_kernel) - len(ref_kernel) - left_padding ref_kernel = np.pad(ref_kernel, (left_padding, right_padding)) in_fwhm, in_left, in_right = calc_fwhm(in_kernel) ref_fwhm, ref_left, ref_right = calc_fwhm(ref_kernel) kernel_diff = np.sum(np.abs(in_kernel - ref_kernel)) fwhm_diff = np.abs(in_fwhm - ref_fwhm) title = 'kernel abs diff %.4f, fwhm abs diff %.4f' % (kernel_diff, fwhm_diff) fig = plt.figure() ax = fig.add_subplot(111) plot_kernel(ax, in_kernel, in_fwhm, in_left, in_right, vp=0.5, color='b') plot_kernel(ax, ref_kernel, ref_fwhm, ref_left, ref_right, vp=0.25, color='r') plt.title(title) plt.grid(True) plt.tight_layout() fig.savefig(args.output_filename)
{"/tests/test_loss.py": ["/ssp/loss.py"], "/ssp/train.py": ["/ssp/config.py", "/ssp/loss.py", "/ssp/utils.py"], "/tests/test_networks.py": ["/ssp/network.py"], "/scripts/compare_kernel.py": ["/ssp/utils.py"], "/ssp/network.py": ["/ssp/config.py"], "/tests/test_fwhm.py": ["/ssp/utils.py"], "/tests/test_kernel.py": ["/ssp/network.py"], "/scripts/train2d.py": ["/ssp/config.py", "/ssp/train.py", "/ssp/network.py", "/ssp/utils.py"]}
41,989
shuohan/espreso
refs/heads/master
/ssp/network.py
import torch import numpy as np from torch import nn import torch.nn.functional as F from .config import Config class Clamp(nn.Module): def __init__(self, min, max): super().__init__() self.min = min self.max = max def forward(self, x): return torch.clamp(x, self.min, self.max) class KernelNet(nn.Sequential): """The network outputs a 1D blur kernel to estimate slice selection. """ def __init__(self): super().__init__() config = Config() self.input_weight = nn.Parameter(torch.zeros(1, config.kn_num_channels)) self.input_clamp = Clamp(-3, 3) for i in range(config.kn_num_linears - 1): linear = nn.Linear(config.kn_num_channels, config.kn_num_channels) self.add_module('linear%d' % i, linear) self.add_module('relu%d' % i, Clamp(-3, 3)) linear = nn.Linear(config.kn_num_channels, config.kernel_length) self.add_module('linear%d' % (config.kn_num_linears - 1), linear) self.softmax = nn.Softmax(dim=1) self.reset_parameters() self._kernel_cuda = None self.register_buffer('avg_kernel', self._calc_kernel().detach()) def reset_parameters(self): """Resets :attr:`input_weight`.""" nn.init.kaiming_uniform_(self.input_weight, a=np.sqrt(5)) def extra_repr(self): return '(input_weight): Parameter(size=%s)' \ % str(tuple(self.input_weight.size())) def _calc_kernel(self): """Calculates the current kernel.""" kernel = self.input_clamp(self.input_weight) for module in self: kernel = module(kernel) kernel = self._reshape_kernel(kernel) return kernel def _reshape_kernel(self, kernel): """Reshapes the kernel to be compatible with the image shape.""" raise NotImplementedError def update_kernel(self): """Updates the current kernel and calculates the moving average.""" beta = Config().kernel_avg_beta self._kernel_cuda = self._calc_kernel() self.avg_kernel = (1 - beta) * self._kernel_cuda.detach() \ + beta * self.avg_kernel @property def kernel_cuda(self): """Returns the current kernel on CUDA.""" if self._kernel_cuda is None: self._kernel_cuda = self._calc_kernel() return self._kernel_cuda @property def kernel(self): """Returns the current kernel on CPU.""" return self.kernel_cuda.detach().cpu() @property def input_size_reduced(self): """Returns the number of pixels reduced from the input image.""" return Config().kernel_length - 1 def forward(self, x): raise NotImplementedError class KernelNet1d(KernelNet): """Estimates the kernel from 1D patches. """ def _reshape_kernel(self, kernel): return kernel.view(1, 1, -1) def forward(self, x): return F.conv1d(x, self.kernel_cuda) class KernelNet2d(KernelNet): """Estimates the kernel from 2D patches. """ def _reshape_kernel(self, kernel): return kernel.view(1, 1, -1, 1) def forward(self, x): return F.conv2d(x, self.kernel_cuda) class LowResDiscriminator(nn.Sequential): """Discriminator to low-resolution patches. """ def __init__(self): super().__init__() config = Config() in_ch = 1 out_ch = config.lrd_num_channels for i in range(config.lrd_num_convs - 1): conv = self._create_conv(in_ch, out_ch) conv = nn.utils.spectral_norm(conv) self.add_module('conv%d' % i, conv) relu = nn.LeakyReLU(config.lrelu_neg_slope) self.add_module('relu%d' % i, relu) in_ch = out_ch out_ch = in_ch * 2 conv = self._create_conv(in_ch, 1) conv = nn.utils.spectral_norm(conv) self.add_module('conv%d' % (config.lrd_num_convs - 1), conv) def _create_conv(self, in_ch, out_ch): """Creates a conv layer.""" raise NotImplementedError class LowResDiscriminator1d(LowResDiscriminator): """Discriminator for 1D low-resolution patches. """ def _create_conv(self, in_ch, out_ch): return nn.Conv1d(in_ch, out_ch, 4, stride=1, padding=0, bias=True) class LowResDiscriminator2d(LowResDiscriminator): """Discriminator for 2D low-resolution patches. """ def _create_conv(self, in_ch, out_ch): return nn.Conv2d(in_ch, out_ch, (4, 1), stride=1, padding=0, bias=True)
{"/tests/test_loss.py": ["/ssp/loss.py"], "/ssp/train.py": ["/ssp/config.py", "/ssp/loss.py", "/ssp/utils.py"], "/tests/test_networks.py": ["/ssp/network.py"], "/scripts/compare_kernel.py": ["/ssp/utils.py"], "/ssp/network.py": ["/ssp/config.py"], "/tests/test_fwhm.py": ["/ssp/utils.py"], "/tests/test_kernel.py": ["/ssp/network.py"], "/scripts/train2d.py": ["/ssp/config.py", "/ssp/train.py", "/ssp/network.py", "/ssp/utils.py"]}