zip
stringlengths 19
109
| filename
stringlengths 4
185
| contents
stringlengths 0
30.1M
| type_annotations
sequencelengths 0
1.97k
| type_annotation_starts
sequencelengths 0
1.97k
| type_annotation_ends
sequencelengths 0
1.97k
|
---|---|---|---|---|---|
archives/007MrNiko_Stepper.zip | about/urls.py | from django.urls import path
from about import views
#creating of section "about"
app_name = 'about'
urlpatterns = [
path('about_project', views.index, name='video'),
]
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | about/views.py | from django.shortcuts import render, redirect
from django.http import HttpResponse
#connecting of html file (section "about")
def index(request):
return render(request, 'index_about.html')
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | accounts/__init__.py | [] | [] | [] |
|
archives/007MrNiko_Stepper.zip | accounts/admin.py | from django.contrib import admin
# Register your models here.
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | accounts/forms.py | from django import forms
from django.contrib.auth.models import User
def widget_attrs(placeholder):
return {'class': 'u-full-width', 'placeholder': placeholder}
def form_kwargs(widget, label='', max_length=64):
return {'widget': widget, 'label': label, 'max_length': max_length}
#login form
class LoginForm(forms.Form):
username = forms.CharField(
**form_kwargs(widget=forms.TextInput(attrs=widget_attrs('Username')))
)
password = forms.CharField(
**form_kwargs(
widget=forms.PasswordInput(attrs=widget_attrs('Password'))
)
)
#cleaning of form
def clean(self):
# Don't check if we already have errors.
if self.errors:
return self.cleaned_data
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
user = User.objects.filter(username=username).first()
if not user or not user.check_password(password):
raise forms.ValidationError('Incorrect username and/or password.')
return self.cleaned_data
#registration
class RegistrationForm(forms.Form):
username = forms.CharField(
**form_kwargs(widget=forms.TextInput(attrs=widget_attrs('Username')))
)
email = forms.EmailField(
**form_kwargs(widget=forms.TextInput(attrs=widget_attrs('Email')))
)
password = forms.CharField(
**form_kwargs(
widget=forms.PasswordInput(attrs=widget_attrs('Password'))
)
)
password_confirmation = forms.CharField(
**form_kwargs(
widget=forms.PasswordInput(
attrs=widget_attrs('Password confirmation')
)
)
)
def clean(self):
password = self.cleaned_data.get('password')
password_confirmation = self.cleaned_data.get('password_confirmation')
if password and password != password_confirmation:
raise forms.ValidationError("Passwords don't match.")
return self.cleaned_data
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | accounts/migrations/__init__.py | [] | [] | [] |
|
archives/007MrNiko_Stepper.zip | accounts/models.py | from django.db import models
# Create your models here.
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | accounts/tests.py | from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from django import forms
from accounts.forms import RegistrationForm, LoginForm
class AccountsTests(TestCase):
def setUp(self):
self.register_data = {
'email': '[email protected]',
'username': 'new_user',
'password': 'test',
'password_confirmation': 'test'
}
User.objects.create_user('test', '[email protected]', 'test')
def tearDown(self):
User.objects.get(username='test').delete()
def test_get_register(self):
response = self.client.get(reverse('auth:register'))
self.assertTemplateUsed(response, 'accounts/register.html')
self.assertIsInstance(response.context['form'], RegistrationForm)
def test_get_login(self):
response = self.client.get(reverse('auth:login'))
self.assertTemplateUsed(response, 'accounts/login.html')
self.assertIsInstance(response.context['form'], LoginForm)
def test_register(self):
response = self.client.post(
reverse('auth:register'), data=self.register_data
)
self.assertRedirects(response, '/auth/login/')
# new user was created
self.assertIsNotNone(User.objects.get(username='new_user'))
def test_login(self):
# no user is logged in
self.assertFalse('_auth_user_id' in self.client.session)
login_data = {'username': 'test', 'password': 'test'}
response = self.client.post(reverse('auth:login'), data=login_data)
self.assertRedirects(response, '/')
# user is logged in
self.assertEqual(self.client.session['_auth_user_id'], '1')
# check if error messages are part of the response
def test_faulty_login(self):
# change username for invalid post
login_data = {'username': 65 * 'X', 'password': 'test'}
response = self.client.post(reverse('auth:login'), data=login_data)
error_message = 'Ensure this value has at most 64 characters'
self.assertContains(response, error_message, status_code=200)
def test_login_with_non_existent_user(self):
# change username for invalid post
login_data = {'username': 'notauser', 'password': 'stillapassowrd'}
response = self.client.post(reverse('auth:login'), data=login_data)
error_message = 'Incorrect username and/or password.'
self.assertContains(response, error_message, status_code=200)
def test_login_with_wrong_password(self):
# change username for invalid post
login_data = {'username': 'test', 'password': 'wrongpassword'}
response = self.client.post(reverse('auth:login'), data=login_data)
error_message = 'Incorrect username and/or password.'
self.assertContains(response, error_message, status_code=200)
def test_faulty_register(self):
# change username for invalid post
self.register_data['username'] = 65 * 'X'
response = self.client.post(
reverse('auth:register'), data=self.register_data
)
error_message = 'Ensure this value has at most 64 characters'
self.assertContains(response, error_message, status_code=200)
def test_logout(self):
response = self.client.get(reverse('auth:logout'))
self.assertRedirects(response, '/')
# no user logged in anymore
self.assertFalse('_auth_user_id' in self.client.session)
class LoginFormTests(TestCase):
# valid test case is covered by AccountsTests (because we need a user)
def setUp(self):
self.too_long_password = {'username': 'test', 'password': 65 * 'X'}
self.too_long_username = {'username': 65 * 'X', 'password': 'test'}
def test_too_long_username(self):
form = LoginForm(self.too_long_username)
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'username': [u'Ensure this value has at most 64' +
' characters (it has 65).']}
)
def test_too_long_password(self):
form = LoginForm(self.too_long_password)
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'password': [u'Ensure this value has at most 64' +
' characters (it has 65).']}
)
def test_no_username(self):
form = LoginForm({'password': 'test'})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'username': [u'This field is required.']}
)
def test_no_password(self):
form = LoginForm({'username': 'test'})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'password': [u'This field is required.']}
)
def test_empty_username(self):
form = LoginForm({'username': '', 'password': 'test'})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'username': [u'This field is required.']}
)
def test_empty_password(self):
form = LoginForm({'username': 'test', 'password': ''})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'password': [u'This field is required.']}
)
class RegistrationFormTests(TestCase):
def setUp(self):
self.valid_form_data = {
'email': '[email protected]',
'username': 'test',
'password': 'test',
'password_confirmation': 'test'
}
self.invalid_email = {
'email': 'test(at)example.com',
'username': 'test',
'password': 'test',
'password_confirmation': 'test'
}
self.non_matching_passwords = {
'email': '[email protected]',
'username': 'test',
'password': 'test1',
'password_confirmation': 'test2'
}
# some tests can be skipped because of the coverage of LoginFormTests
def test_valid_input(self):
form = RegistrationForm(self.valid_form_data)
self.assertTrue(form.is_valid())
def test_invalid_email(self):
form = RegistrationForm(self.invalid_email)
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'email': [u'Enter a valid email address.']}
)
def test_non_matching_passwords(self):
form = RegistrationForm(self.non_matching_passwords)
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'__all__': [u"Passwords don't match."]}
)
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | accounts/urls.py | from django.urls import path
from accounts import views
#connecting of authorisation form
app_name = 'auth'
urlpatterns = [
path('login/', views.login_view, name='login'),
path('logout/', views.logout_view, name='logout'),
path('register/', views.register, name='register'),
]
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | accounts/views.py | from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from accounts.forms import LoginForm, RegistrationForm
from lists.forms import TodoForm
#login request
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
user = authenticate(
username=request.POST['username'],
password=request.POST['password']
)
if user is not None:
if user.is_active:
login(request, user)
return redirect('lists:index')
else:
return render(request, 'accounts/login.html', {'form': form})
else:
return render(request, 'accounts/login.html', {'form': LoginForm()})
return redirect('lists:index')
#register request
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
User.objects.create_user(
username=request.POST['username'],
email=request.POST['email'],
password=request.POST['password']
)
return redirect('auth:login')
else:
return render(request, 'accounts/register.html', {'form': form})
else:
return render(
request, 'accounts/register.html', {'form': RegistrationForm()}
)
#logout request
def logout_view(request):
logout(request)
return redirect('lists:index')
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | api/__init__.py | [] | [] | [] |
|
archives/007MrNiko_Stepper.zip | api/migrations/__init__.py | [] | [] | [] |
|
archives/007MrNiko_Stepper.zip | api/serializers.py | from django.contrib.auth.models import User
from rest_framework import serializers
from lists.models import TodoList, Todo
class UserSerializer(serializers.ModelSerializer):
todolists = serializers.PrimaryKeyRelatedField(
many=True, queryset=TodoList.objects.all()
)
class Meta:
model = User
fields = ('id', 'username', 'last_login', 'date_joined', 'todolists')
class TodoListSerializer(serializers.ModelSerializer):
creator = serializers.ReadOnlyField(source='creator.username')
class Meta:
model = TodoList
fields = ('id', 'title', 'created_at', 'creator', 'todos')
class TodoSerializer(serializers.ModelSerializer):
creator = serializers.ReadOnlyField(source='creator.username')
class Meta:
model = Todo
fields = (
'id', 'todolist', 'description', 'created_at',
'creator', 'is_finished', 'finished_at'
)
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | api/tests.py | from django.urls import reverse
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APITestCase
from lists.models import TodoList
class UserTests(APITestCase):
def setUp(self):
User.objects.create_user('test', '[email protected]', 'test')
self.client.login(username='test', password='test')
def tearDown(self):
User.objects.get(username='test').delete()
self.client.logout()
def test_post_on_read_only(self):
response = self.client.post('api:user-list', {}, format='json')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_get_user_if_not_admin(self):
# get user (test user from setup)
get_response = self.client.get('/api/users/{0}/'.format(1))
self.assertEqual(get_response.status_code, status.HTTP_403_FORBIDDEN)
def test_get_user_if_admin(self):
# create admin user and login as such
User.objects.create_superuser('admin', '[email protected]', 'admin')
self.client.login(username='admin', password='admin')
# get user (test user from setup)
get_response = self.client.get('/api/users/{0}/'.format(1))
self.assertEqual(get_response.status_code, status.HTTP_200_OK)
# check user
self.assertEqual(get_response.data['username'], 'test')
class TodoListTests(APITestCase):
def setUp(self):
User.objects.create_user('test', '[email protected]', 'test')
self.client.login(username='test', password='test')
self.test_data = {'title': 'some other title', 'todos': []}
def tearDown(self):
User.objects.get(username='test').delete()
self.client.logout()
def post_new_todolist(self, data):
url = reverse('api:todolist-list')
return self.client.post(url, data, format='json')
def test_create_todolist(self):
response = self.post_new_todolist(self.test_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['title'], self.test_data['title'])
def test_get_todolist(self):
# add todolist
post_response = self.post_new_todolist(self.test_data)
self.assertEqual(post_response.status_code, status.HTTP_201_CREATED)
# get todolist
todolist_id = post_response.data['id']
self.assertEqual(todolist_id, 1)
get_response = self.client.get(
'/api/todolists/{0}/'.format(todolist_id)
)
self.assertEqual(get_response.status_code, status.HTTP_200_OK)
# check todolist
self.assertEqual(get_response.data, post_response.data)
def test_get_when_not_logged_in(self):
# add some data
post_response = self.post_new_todolist(self.test_data)
self.assertEqual(post_response.status_code, status.HTTP_201_CREATED)
# make sure the user is logged out
self.client.logout()
response = self.client.get('/api/todolists/1/')
# expect 200, because reading is allowed for everybody
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_non_existent_todolist(self):
response = self.client.get('/api/todolists/0/')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_post_for_anon_users(self):
# make sure the user is logged out
self.client.logout()
# try posting a todolist
response = self.post_new_todolist(self.test_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_put_todolist(self):
# add todolist
post_response = self.post_new_todolist(self.test_data)
self.assertEqual(post_response.status_code, status.HTTP_201_CREATED)
# put todolist
todolist_id = post_response.data['id']
put_data = post_response.data
put_data['title'] = 'changed title'
put_response = self.client.put(
'/api/todolists/{0}/'.format(todolist_id), put_data, format='json'
)
self.assertEqual(put_response.status_code, status.HTTP_200_OK)
get_response = self.client.get(
'/api/todolists/{0}/'.format(todolist_id)
)
self.assertEqual(put_response.status_code, status.HTTP_200_OK)
self.assertEqual(get_response.data['title'], 'changed title')
def test_delete_todolist(self):
# add todolist
post_response = self.post_new_todolist(self.test_data)
self.assertEqual(post_response.status_code, status.HTTP_201_CREATED)
# delete todolist
todolist_id = post_response.data['id']
delete_response = self.client.delete(
'/api/todolists/{0}/'.format(todolist_id)
)
self.assertEqual(
delete_response.status_code, status.HTTP_204_NO_CONTENT
)
# get todolist and expect 404
get_response = self.client.get(
'/api/todolists/{0}/'.format(todolist_id)
)
self.assertEqual(get_response.status_code, status.HTTP_404_NOT_FOUND)
class TodoTests(APITestCase):
def setUp(self):
self.test_user = User.objects.create_user(
'test', '[email protected]', 'test'
)
self.client.login(username='test', password='test')
self.test_todolist = TodoList(
title='some title', creator=self.test_user
)
self.test_todolist.save()
self.test_data = {
'description': 'some description',
'todolist': self.test_todolist.id
}
def tearDown(self):
test_user = User.objects.get(username='test')
test_user.delete()
self.client.logout()
def post_new_todo(self, data):
url = reverse('api:todo-list')
return self.client.post(url, data, format='json')
def test_create_todo(self):
response = self.post_new_todo(self.test_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(
response.data['description'], self.test_data['description']
)
def test_get_todo(self):
# add todo
post_response = self.post_new_todo(self.test_data)
self.assertEqual(post_response.status_code, status.HTTP_201_CREATED)
# get todo
todo_id = post_response.data['id']
self.assertEqual(todo_id, 1)
get_response = self.client.get(
'/api/todos/{0}/'.format(todo_id)
)
self.assertEqual(get_response.status_code, status.HTTP_200_OK)
# check todo
self.assertEqual(get_response.data, post_response.data)
def test_get_when_not_logged_in(self):
# add some data
post_response = self.post_new_todo(self.test_data)
self.assertEqual(post_response.status_code, status.HTTP_201_CREATED)
# make sure the user is logged out
self.client.logout()
response = self.client.get('/api/todos/1/')
# expect 200, because reading is allowed for everybody
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_non_existent_todo(self):
response = self.client.get('/api/todo/0/')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_post_for_anon_users(self):
# make sure the user is logged out
self.client.logout()
# try posting a todo
response = self.post_new_todo(self.test_data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_put_todo(self):
# add todo
post_response = self.post_new_todo(self.test_data)
self.assertEqual(post_response.status_code, status.HTTP_201_CREATED)
# put todo
todo_id = post_response.data['id']
put_data = post_response.data
put_data['description'] = 'changed description'
put_response = self.client.put(
'/api/todos/{0}/'.format(todo_id), put_data, format='json'
)
self.assertEqual(put_response.status_code, status.HTTP_200_OK)
get_response = self.client.get(
'/api/todos/{0}/'.format(todo_id)
)
self.assertEqual(put_response.status_code, status.HTTP_200_OK)
self.assertEqual(
get_response.data['description'], 'changed description'
)
def test_put_todo_changing_status(self):
# add todo
post_response = self.post_new_todo(self.test_data)
self.assertEqual(post_response.status_code, status.HTTP_201_CREATED)
# put todo
todo_id = post_response.data['id']
put_data = post_response.data
put_data['is_finished'] = True
put_response = self.client.put(
'/api/todos/{0}/'.format(todo_id), put_data, format='json'
)
self.assertEqual(put_response.status_code, status.HTTP_200_OK)
get_response = self.client.get(
'/api/todos/{0}/'.format(todo_id)
)
self.assertEqual(put_response.status_code, status.HTTP_200_OK)
self.assertEqual(
get_response.data['is_finished'], True
)
def test_delete_todo(self):
# add todo
post_response = self.post_new_todo(self.test_data)
self.assertEqual(post_response.status_code, status.HTTP_201_CREATED)
# delete todolist
todo_id = post_response.data['id']
delete_response = self.client.delete(
'/api/todos/{0}/'.format(todo_id)
)
self.assertEqual(
delete_response.status_code, status.HTTP_204_NO_CONTENT
)
# get todolist and expect 404
get_response = self.client.get(
'/api/todos/{0}/'.format(todo_id)
)
self.assertEqual(get_response.status_code, status.HTTP_404_NOT_FOUND)
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | api/urls.py | from django.urls import path, include
from rest_framework.routers import DefaultRouter
from api import views
router = DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'todolists', views.TodoListViewSet)
router.register(r'todos', views.TodoViewSet)
#connecting of api
app_name = 'api'
urlpatterns = [
path('', include(router.urls)),
]
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | api/views.py | from django.contrib.auth.models import User
from rest_framework import permissions, viewsets
from api.serializers import UserSerializer, TodoListSerializer, TodoSerializer
from lists.models import TodoList, Todo
class IsCreatorOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `creator` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# If the object doesn't have a creator (i.e. anon) allow all methods.
if not obj.creator:
return True
# Instance must have an attribute named `creator`.
return obj.creator == request.user
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (permissions.IsAdminUser,)
class TodoListViewSet(viewsets.ModelViewSet):
queryset = TodoList.objects.all()
serializer_class = TodoListSerializer
permission_classes = (IsCreatorOrReadOnly,)
def perform_create(self, serializer):
user = self.request.user
creator = user if user.is_authenticated else None
serializer.save(creator=creator)
class TodoViewSet(viewsets.ModelViewSet):
queryset = Todo.objects.all()
serializer_class = TodoSerializer
permission_classes = (IsCreatorOrReadOnly,)
def perform_create(self, serializer):
user = self.request.user
creator = user if user.is_authenticated else None
serializer.save(creator=creator)
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | lists/__init__.py | [] | [] | [] |
|
archives/007MrNiko_Stepper.zip | lists/admin.py | from django.contrib import admin
# Register your models here.
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | lists/forms.py | from django import forms
def widget_attrs(placeholder):
return {'class': 'u-full-width', 'placeholder': placeholder}
def form_kwargs(widget, label='', max_length=128):
return {'widget': widget, 'label': label, 'max_length': max_length}
class TodoForm(forms.Form):
description = forms.CharField(
**form_kwargs(
widget=forms.TextInput(attrs=widget_attrs('Enter what you want todo'))
)
)
class TodoListForm(forms.Form):
title = forms.CharField(
**form_kwargs(
widget=forms.TextInput(
attrs=widget_attrs('Enter a title of your new todo list')
)
)
)
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | lists/migrations/0001_initial.py | # Generated by Django 2.0 on 2017-12-02 17:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Todo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.CharField(max_length=128)),
('created_at', models.DateTimeField(auto_now=True)),
('finished_at', models.DateTimeField(null=True)),
('is_finished', models.BooleanField(default=False)),
('creator', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='todos', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('created_at',),
},
),
migrations.CreateModel(
name='TodoList',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(default='Planning is Good', max_length=128)),
('created_at', models.DateTimeField(auto_now=True)),
('creator', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='todolists', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('created_at',),
},
),
migrations.AddField(
model_name='todo',
name='todolist',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='todos', to='lists.TodoList'),
),
]
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | lists/migrations/__init__.py | [] | [] | [] |
|
archives/007MrNiko_Stepper.zip | lists/models.py | from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class TodoList(models.Model):
title = models.CharField(max_length=128, default='List')
created_at = models.DateTimeField(auto_now=True)
creator = models.ForeignKey(User, null=True, related_name='todolists', on_delete=models.CASCADE)
class Meta:
ordering = ('created_at',)
def __str__(self):
return self.title
def count(self):
return self.todos.count()
def count_finished(self):
return self.todos.filter(is_finished=True).count()
def count_open(self):
return self.todos.filter(is_finished=False).count()
class Todo(models.Model):
description = models.CharField(max_length=128)
created_at = models.DateTimeField(auto_now=True)
finished_at = models.DateTimeField(null=True)
is_finished = models.BooleanField(default=False)
creator = models.ForeignKey(User, null=True, related_name='todos', on_delete=models.CASCADE)
todolist = models.ForeignKey(TodoList, related_name='todos', on_delete=models.CASCADE)
class Meta:
ordering = ('created_at',)
def __str__(self):
return self.description
def close(self):
self.is_finished = True
self.finished_at = timezone.now()
self.save()
def reopen(self):
self.is_finished = False
self.finished_at = None
self.save()
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | lists/templatetags/__init__.py | [] | [] | [] |
|
archives/007MrNiko_Stepper.zip | lists/templatetags/lists_extras.py | from django import template
from datetime import datetime
register = template.Library()
@register.filter('humanize')
def humanize_time(dt, past_='ago', future_='from now', default='just now'):
"""
Returns string representing 'time since'
or 'time until' e.g.
3 days ago, 5 hours from now etc.
"""
now = datetime.utcnow()
# remove tzinfo
dt = dt.replace(tzinfo=None)
if now > dt:
diff = now - dt
dt_is_past = True
else:
diff = dt - now
dt_is_past = False
periods = (
(diff.days // 365, 'year', 'years'),
(diff.days // 30, 'month', 'months'),
(diff.days // 7, 'week', 'weeks'),
(diff.days, 'day', 'days'),
(diff.seconds // 3600, 'hour', 'hours'),
(diff.seconds // 60, 'minute', 'minutes'),
(diff.seconds, 'second', 'seconds'),
)
for period, singular, plural in periods:
if period:
return '%d %s %s' % (
period,
singular if period == 1 else plural,
past_ if dt_is_past else future_
)
return default
@register.filter('in_seconds')
def in_seconds(dt):
return int(
(dt.replace(tzinfo=None) - datetime(1970, 1, 1)).total_seconds()
)
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | lists/tests.py | from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from lists.forms import TodoForm, TodoListForm
from lists.models import Todo, TodoList
from unittest import skip
class ListTests(TestCase):
def setUp(self):
self.user = User.objects.create_user(
'test', '[email protected]', 'test'
)
self.todolist = TodoList(title='test title', creator=self.user)
self.todolist.save()
self.todo = Todo(
description='save todo',
todolist_id=self.todolist.id,
creator=self.user
)
self.todo.save()
self.client.login(username='test', password='test')
def tearDown(self):
self.client.logout()
self.user.delete()
self.todolist.delete()
self.todo.delete()
def test_get_index_page(self):
response = self.client.get(reverse('lists:index'))
self.assertTemplateUsed(response, 'lists/index.html')
self.assertIsInstance(response.context['form'], TodoForm)
def test_add_todo_to_index_page(self):
response = self.client.post(
reverse('lists:index'), {'description': 'test'}
)
self.assertTemplateUsed(response, 'lists/index.html')
self.assertIsInstance(response.context['form'], TodoForm)
def test_get_todolist_view(self):
response = self.client.get(
reverse(
'lists:todolist', kwargs={'todolist_id': self.todolist.id}
)
)
self.assertTemplateUsed(response, 'lists/todolist.html')
self.assertIsInstance(response.context['form'], TodoForm)
def test_add_todo_to_todolist_view(self):
response = self.client.post(
reverse(
'lists:todolist', kwargs={'todolist_id': self.todolist.id}
),
{'description': 'test'}
)
self.assertTemplateUsed(response, 'lists/todolist.html')
self.assertIsInstance(response.context['form'], TodoForm)
self.assertContains(response, 'test')
def test_get_todolist_overview(self):
response = self.client.get(reverse('lists:overview'))
self.assertTemplateUsed(response, 'lists/overview.html')
self.assertIsInstance(response.context['form'], TodoListForm)
def test_get_todolist_overview_redirect_when_not_logged_in(self):
self.client.logout()
response = self.client.get(reverse('lists:overview'))
self.assertRedirects(response, '/auth/login/?next=/todolists/')
def test_add_todolist_to_todolist_overview(self):
response = self.client.post(
reverse('lists:overview'), {'title': 'some title'}
)
self.assertRedirects(
response, '/todolist/add/',
target_status_code=302, fetch_redirect_response=False
)
class TodoListFormTests(TestCase):
def setUp(self):
self.vaild_form_data = {
'title': 'some title'
}
self.too_long_title = {
'title': 129 * 'X'
}
def test_valid_input(self):
form = TodoListForm(self.vaild_form_data)
self.assertTrue(form.is_valid())
def test_no_title(self):
form = TodoListForm({})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'title': [u'This field is required.']}
)
def test_empty_title(self):
form = TodoListForm({'title': ''})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'title': [u'This field is required.']}
)
def test_too_long_title(self):
form = TodoListForm(self.too_long_title)
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'title': [u'Ensure this value has at most 128 ' +
'characters (it has 129).']}
)
class TodoFormTests(TestCase):
def setUp(self):
self.valid_form_data = {
'description': 'something to be done'
}
self.too_long_description = {
'description': 129 * 'X'
}
def test_valid_input(self):
form = TodoForm(self.valid_form_data)
self.assertTrue(form.is_valid())
def test_no_description(self):
form = TodoForm({})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'description': [u'This field is required.']}
)
def test_empty_description(self):
form = TodoForm({'description': ''})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'description': [u'This field is required.']}
)
def test_too_title(self):
form = TodoForm(self.too_long_description)
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{'description': [u'Ensure this value has at most 128 ' +
'characters (it has 129).']}
)
class ListModelTests(TestCase):
def setUp(self):
self.user = User.objects.create_user(
'test', '[email protected]', 'test'
)
self.todolist = TodoList(title='title', creator=self.user)
self.todolist.save()
self.todo = Todo(
description='description',
todolist_id=self.todolist.id,
creator=self.user
)
self.todo.save()
def tearDown(self):
self.todo.delete()
self.todolist.delete()
self.user.delete()
def test_count_todos(self):
self.assertEqual(self.todolist.count(), 1)
new_todo = Todo(
description='test',
todolist_id=self.todolist.id,
creator=self.user
)
new_todo.save()
self.assertEqual(self.todolist.count(), 2)
def test_count_open_todos(self):
self.assertEqual(self.todolist.count_open(), 1)
new_todo = Todo(
description='test',
todolist_id=self.todolist.id,
creator=self.user
)
new_todo.save()
self.assertEqual(self.todolist.count_open(), 2)
new_todo.close()
self.assertEqual(self.todolist.count_open(), 1)
def test_count_closed_todos(self):
self.assertEqual(self.todolist.count_finished(), 0)
new_todo = Todo(
description='test',
todolist_id=self.todolist.id,
creator=self.user
)
new_todo.close()
self.todo.close()
self.assertEqual(self.todolist.count_finished(), 2)
self.assertIsNotNone(new_todo.finished_at)
self.todo.reopen()
self.assertEqual(self.todolist.count_finished(), 1)
self.assertIsNone(self.todo.finished_at)
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | lists/urls.py | from django.urls import path
from lists import views
#connecting of lists
app_name = 'lists'
urlpatterns = [
path('', views.index, name='index'),
path('todolist/<int:todolist_id>/', views.todolist, name='todolist'),
path('todolist/new/', views.new_todolist, name='new_todolist'),
path('todolist/add/', views.add_todolist, name='add_todolist'),
path('todo/add/<int:todolist_id>/', views.add_todo, name='add_todo'),
path('todolists/', views.overview, name='overview'),
]
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | lists/views.py | from django.shortcuts import get_object_or_404, render, redirect
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from lists.models import TodoList, Todo
from lists.forms import TodoForm, TodoListForm
def index(request):
return render(request, 'lists/index.html', {'form': TodoForm()})
def todolist(request, todolist_id):
todolist = get_object_or_404(TodoList, pk=todolist_id)
if request.method == 'POST':
redirect('lists:add_todo', todolist_id=todolist_id)
return render(
request, 'lists/todolist.html',
{'todolist': todolist, 'form': TodoForm()}
)
def add_todo(request, todolist_id):
if request.method == 'POST':
form = TodoForm(request.POST)
if form.is_valid():
user = request.user if request.user.is_authenticated else None
todo = Todo(
description=request.POST['description'],
todolist_id=todolist_id,
creator=user
)
todo.save()
return redirect('lists:todolist', todolist_id=todolist_id)
else:
return render(request, 'lists/todolist.html', {'form': form})
return redirect('lists:index')
@login_required
def overview(request):
if request.method == 'POST':
return redirect('lists:add_todolist')
return render(request, 'lists/overview.html', {'form': TodoListForm()})
def new_todolist(request):
if request.method == 'POST':
form = TodoForm(request.POST)
if form.is_valid():
# create default todolist
user = request.user if request.user.is_authenticated else None
todolist = TodoList(creator=user)
todolist.save()
todo = Todo(
description=request.POST['description'],
todolist_id=todolist.id,
creator=user
)
todo.save()
return redirect('lists:todolist', todolist_id=todolist.id)
else:
return render(request, 'lists/index.html', {'form': form})
return redirect('lists:index')
def add_todolist(request):
if request.method == 'POST':
form = TodoListForm(request.POST)
if form.is_valid():
user = request.user if request.user.is_authenticated else None
todolist = TodoList(title=request.POST['title'], creator=user)
todolist.save()
return redirect('lists:todolist', todolist_id=todolist.id)
else:
return render(request, 'lists/overview.html', {'form': form})
return redirect('lists:index')
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "todolist.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | todolist/__init__.py | [] | [] | [] |
|
archives/007MrNiko_Stepper.zip | todolist/settings.py | """
Django settings for todolist project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
#SECRET_KEY = '@e2(yx)v&tgh3_s=0yja-i!dpebxsz^dg47x)-k&kq_3zf*9e*'
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'cg#p$g+j9tax!#a3cup@1$8obt2_+&k3q+pmu)5%asj6yjpkag')
# SECURITY WARNING: don't run with debug turned on in production!
#DEBUG = False
DEBUG = bool( os.environ.get('DJANGO_DEBUG', True) )
ALLOWED_HOSTS = ['stepper-v2.herokuapp.com',
'127.0.0.1']
# Application definition
INSTALLED_APPS = (
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'todolist',
'lists',
'accounts',
'rest_framework',
'api',
'about',
'weather',
)
SITE_ID = 1
MIDDLEWARE = (
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'todolist.urls'
WSGI_APPLICATION = 'todolist.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
# Login settings
LOGIN_URL = '/auth/login/'
LOGOUT_URL = '/auth/logout/'
# rest (api) framework
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'debug': True,
},
},
]
# Heroku: Update database configuration from $DATABASE_URL.
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
# The absolute path to the directory where collectstatic will collect static files for deployment.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# The URL to use when referring to static files (where they will be served from)
STATIC_URL = '/static/'
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' | [] | [] | [] |
archives/007MrNiko_Stepper.zip | todolist/urls.py | from django.urls import path, include
from django.contrib import admin
#connecting of urls
urlpatterns = [
path('', include('lists.urls')),
path('auth/', include('accounts.urls')),
path('api/', include('api.urls')),
path('api-auth/', include('rest_framework.urls')),
path('admin/', admin.site.urls),
path('weather/', include('weather.urls')),
path('about/', include('about.urls')),
]
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | todolist/wsgi.py | """
WSGI config for todolist project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "todolist.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | weather/urls.py | from django.urls import path
from weather import views
#creating of the weather_app
app_name = 'weather'
urlpatterns = [
path('your_weather', views.index, name='weather'),
]
| [] | [] | [] |
archives/007MrNiko_Stepper.zip | weather/views.py | from django.shortcuts import render, redirect
from django.http import HttpResponse
#connecting of html file (section "weather")
def index(request):
return render(request, 'index.html')
| [] | [] | [] |
archives/097475_hansberger.zip | config/__init__.py | [] | [] | [] |
|
archives/097475_hansberger.zip | config/settings/__init__.py | [] | [] | [] |
|
archives/097475_hansberger.zip | config/settings/base.py | """
Base settings to build other settings files upon.
"""
import environ
ASGI_APPLICATION = 'hansberger.routing.application'
DATA_UPLOAD_MAX_MEMORY_SIZE = 104857600
ROOT_DIR = (
environ.Path(__file__) - 3
) # (hansberger/config/settings/base.py - 3 = hansberger/)
APPS_DIR = ROOT_DIR.path("hansberger")
env = environ.Env()
READ_DOT_ENV_FILE = env.bool("DJANGO_READ_DOT_ENV_FILE", default=False)
if READ_DOT_ENV_FILE:
# OS environment variables take precedence over variables from .env
env.read_env(str(ROOT_DIR.path(".env")))
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = env.bool("DJANGO_DEBUG", False)
# Local time zone. Choices are
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# though not all of them may be available with every OS.
# In Windows, this must be set to your system time zone.
TIME_ZONE = "Europe/Rome"
# https://docs.djangoproject.com/en/dev/ref/settings/#language-code
LANGUAGE_CODE = "en-us"
# https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1
# https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True
# https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
USE_L10N = True
# https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
USE_TZ = True
# DATABASES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
"default": env.db("DATABASE_URL", default="postgres:///hansberger")
}
DATABASES["default"]["ATOMIC_REQUESTS"] = True
# URLS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf
ROOT_URLCONF = "config.urls"
# https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = "config.wsgi.application"
# APPS
# ------------------------------------------------------------------------------
DJANGO_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.messages",
"django.contrib.staticfiles",
# "django.contrib.humanize", # Handy template tags
"django.contrib.admin",
]
THIRD_PARTY_APPS = [
"channels",
"crispy_forms",
"allauth",
"allauth.account",
"allauth.socialaccount",
"rest_framework",
]
LOCAL_APPS = [
"hansberger.users.apps.UsersAppConfig",
"hansberger.research.apps.ResearchConfig",
"hansberger.datasets.apps.DatasetsConfig",
"hansberger.analysis.apps.AnalysisConfig"
# Your stuff: custom apps go here
]
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.timer.TimerDebugPanel',
'pympler.panels.MemoryPanel',
)
# https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
INSTALLED_APPS = INSTALLED_APPS + ['pympler']
# MIGRATIONS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#migration-modules
MIGRATION_MODULES = {"sites": "hansberger.contrib.sites.migrations"}
# AUTHENTICATION
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#authentication-backends
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
]
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model
AUTH_USER_MODEL = "users.User"
# https://docs.djangoproject.com/en/dev/ref/settings/#login-redirect-url
LOGIN_REDIRECT_URL = "users:redirect"
# https://docs.djangoproject.com/en/dev/ref/settings/#login-url
LOGIN_URL = "account_login"
# PASSWORDS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers
PASSWORD_HASHERS = [
# https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django
"django.contrib.auth.hashers.Argon2PasswordHasher",
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
"django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
"django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
"django.contrib.auth.hashers.BCryptPasswordHasher",
]
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
# MIDDLEWARE
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#middleware
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
# STATIC
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = str(ROOT_DIR("staticfiles"))
# https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = "/static/"
# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = [str(APPS_DIR.path("static"))]
# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
# MEDIA
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = str(APPS_DIR("media"))
# https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = "/media/"
# TEMPLATES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES = [
{
# https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND
"BACKEND": "django.template.backends.django.DjangoTemplates",
# https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
"DIRS": [str(APPS_DIR.path("templates"))],
"OPTIONS": {
# https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
"debug": DEBUG,
# https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
# https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types
"loaders": [
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
],
# https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
},
}
]
# http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs
CRISPY_TEMPLATE_PACK = "bootstrap4"
# FIXTURES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#fixture-dirs
FIXTURE_DIRS = (str(APPS_DIR.path("fixtures")),)
# SECURITY
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-httponly
SESSION_COOKIE_HTTPONLY = True
# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-httponly
CSRF_COOKIE_HTTPONLY = True
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-browser-xss-filter
SECURE_BROWSER_XSS_FILTER = True
# https://docs.djangoproject.com/en/dev/ref/settings/#x-frame-options
X_FRAME_OPTIONS = 'SAMEORIGIN'
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = env(
"DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.smtp.EmailBackend"
)
# ADMIN
# ------------------------------------------------------------------------------
# Django Admin URL.
ADMIN_URL = "admin/"
# https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = [("""Matteo Belenchia and Sebastiano Verdolini""", "[email protected]")]
# https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS
# django-allauth
# ------------------------------------------------------------------------------
ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True)
# https://django-allauth.readthedocs.io/en/latest/configuration.html
ACCOUNT_AUTHENTICATION_METHOD = "username"
# https://django-allauth.readthedocs.io/en/latest/configuration.html
ACCOUNT_EMAIL_REQUIRED = True
# https://django-allauth.readthedocs.io/en/latest/configuration.html
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
# https://django-allauth.readthedocs.io/en/latest/configuration.html
ACCOUNT_ADAPTER = "hansberger.users.adapters.AccountAdapter"
# https://django-allauth.readthedocs.io/en/latest/configuration.html
SOCIALACCOUNT_ADAPTER = "hansberger.users.adapters.SocialAccountAdapter"
# Your stuff...
# ------------------------------------------------------------------------------
| [] | [] | [] |
archives/097475_hansberger.zip | config/settings/local.py | from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env(
"DJANGO_SECRET_KEY",
default="0mtXWuK6ERxey9kqse5UUrxcBsTOjQayYqfOLE4fn962rOwH0J1q01X4kZfTm6U7",
)
# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["localhost", "0.0.0.0", "127.0.0.1"]
# CACHES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "",
}
}
# TEMPLATES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES[0]["OPTIONS"]["debug"] = DEBUG # noqa F405
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = env(
"DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.console.EmailBackend"
)
# https://docs.djangoproject.com/en/dev/ref/settings/#email-host
EMAIL_HOST = "localhost"
# https://docs.djangoproject.com/en/dev/ref/settings/#email-port
EMAIL_PORT = 1025
# django-debug-toolbar
# ------------------------------------------------------------------------------
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#prerequisites
INSTALLED_APPS += ["debug_toolbar"] # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#middleware
MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"] # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/configuration.html#debug-toolbar-config
DEBUG_TOOLBAR_CONFIG = {
"DISABLE_PANELS": ["debug_toolbar.panels.redirects.RedirectsPanel"],
"SHOW_TEMPLATE_CONTEXT": True,
}
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#internal-ips
INTERNAL_IPS = ["127.0.0.1", "10.0.2.2"]
# django-extensions
# ------------------------------------------------------------------------------
# https://django-extensions.readthedocs.io/en/latest/installation_instructions.html#configuration
INSTALLED_APPS += ["django_extensions"] # noqa F405
# Your stuff...
# ------------------------------------------------------------------------------
| [] | [] | [] |
archives/097475_hansberger.zip | config/settings/production.py | from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env("DJANGO_SECRET_KEY")
# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["example.com"])
# DATABASES
# ------------------------------------------------------------------------------
DATABASES["default"] = env.db("DATABASE_URL") # noqa F405
DATABASES["default"]["ATOMIC_REQUESTS"] = True # noqa F405
DATABASES["default"]["CONN_MAX_AGE"] = env.int("CONN_MAX_AGE", default=60) # noqa F405
# CACHES
# ------------------------------------------------------------------------------
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": env("REDIS_URL"),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
# Mimicing memcache behavior.
# http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior
"IGNORE_EXCEPTIONS": True,
},
}
}
# SECURITY
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-ssl-redirect
SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True)
# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-secure
SESSION_COOKIE_SECURE = True
# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-secure
CSRF_COOKIE_SECURE = True
# https://docs.djangoproject.com/en/dev/topics/security/#ssl-https
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-seconds
# TODO: set this to 60 seconds first and then to 518400 once you prove the former works
SECURE_HSTS_SECONDS = 60
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-include-subdomains
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(
"DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True
)
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-preload
SECURE_HSTS_PRELOAD = env.bool("DJANGO_SECURE_HSTS_PRELOAD", default=True)
# https://docs.djangoproject.com/en/dev/ref/middleware/#x-content-type-options-nosniff
SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
"DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True
)
# STORAGES
# ------------------------------------------------------------------------------
# https://django-storages.readthedocs.io/en/latest/#installation
INSTALLED_APPS += ["storages"] # noqa F405
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_ACCESS_KEY_ID = env("DJANGO_AWS_ACCESS_KEY_ID")
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_SECRET_ACCESS_KEY = env("DJANGO_AWS_SECRET_ACCESS_KEY")
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_STORAGE_BUCKET_NAME = env("DJANGO_AWS_STORAGE_BUCKET_NAME")
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_QUERYSTRING_AUTH = False
# DO NOT change these unless you know what you're doing.
_AWS_EXPIRY = 60 * 60 * 24 * 7
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_S3_OBJECT_PARAMETERS = {
"CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate"
}
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_DEFAULT_ACL = None
# STATIC
# ------------------------
STATICFILES_STORAGE = "config.settings.production.StaticRootS3Boto3Storage"
STATIC_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/static/"
# MEDIA
# ------------------------------------------------------------------------------
# region http://stackoverflow.com/questions/10390244/
# Full-fledge class: https://stackoverflow.com/a/18046120/104731
from storages.backends.s3boto3 import S3Boto3Storage # noqa E402
class StaticRootS3Boto3Storage(S3Boto3Storage):
location = "static"
class MediaRootS3Boto3Storage(S3Boto3Storage):
location = "media"
file_overwrite = False
# endregion
DEFAULT_FILE_STORAGE = "config.settings.production.MediaRootS3Boto3Storage"
MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/media/"
# TEMPLATES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES[0]["OPTIONS"]["loaders"] = [ # noqa F405
(
"django.template.loaders.cached.Loader",
[
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
],
)
]
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email
DEFAULT_FROM_EMAIL = env(
"DJANGO_DEFAULT_FROM_EMAIL", default="HansBerger <[email protected]>"
)
# https://docs.djangoproject.com/en/dev/ref/settings/#server-email
SERVER_EMAIL = env("DJANGO_SERVER_EMAIL", default=DEFAULT_FROM_EMAIL)
# https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix
EMAIL_SUBJECT_PREFIX = env(
"DJANGO_EMAIL_SUBJECT_PREFIX", default="[HansBerger]"
)
# ADMIN
# ------------------------------------------------------------------------------
# Django Admin URL regex.
ADMIN_URL = env("DJANGO_ADMIN_URL")
# Anymail (Mailgun)
# ------------------------------------------------------------------------------
# https://anymail.readthedocs.io/en/stable/installation/#installing-anymail
INSTALLED_APPS += ["anymail"] # noqa F405
EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend"
# https://anymail.readthedocs.io/en/stable/installation/#anymail-settings-reference
ANYMAIL = {
"MAILGUN_API_KEY": env("MAILGUN_API_KEY"),
"MAILGUN_SENDER_DOMAIN": env("MAILGUN_DOMAIN"),
}
# Gunicorn
# ------------------------------------------------------------------------------
INSTALLED_APPS += ["gunicorn"] # noqa F405
# Collectfast
# ------------------------------------------------------------------------------
# https://github.com/antonagestam/collectfast#installation
INSTALLED_APPS = ["collectfast"] + INSTALLED_APPS # noqa F405
AWS_PRELOAD_METADATA = True
# LOGGING
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#logging
# See https://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}},
"formatters": {
"verbose": {
"format": "%(levelname)s %(asctime)s %(module)s "
"%(process)d %(thread)d %(message)s"
}
},
"handlers": {
"mail_admins": {
"level": "ERROR",
"filters": ["require_debug_false"],
"class": "django.utils.log.AdminEmailHandler",
},
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "verbose",
},
},
"loggers": {
"django.request": {
"handlers": ["mail_admins"],
"level": "ERROR",
"propagate": True,
},
"django.security.DisallowedHost": {
"level": "ERROR",
"handlers": ["console", "mail_admins"],
"propagate": True,
},
},
}
# Your stuff...
# ------------------------------------------------------------------------------
| [] | [] | [] |
archives/097475_hansberger.zip | config/settings/test.py | """
With these settings, tests run faster.
"""
from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = False
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env(
"DJANGO_SECRET_KEY",
default="erUDbhof0rcYmmw3H8Xirg44hVgOGPbiHpqtggEXotfG3NvWWXRK0CGCQsda0byV",
)
# https://docs.djangoproject.com/en/dev/ref/settings/#test-runner
TEST_RUNNER = "django.test.runner.DiscoverRunner"
# CACHES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "",
}
}
# PASSWORDS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers
PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
# TEMPLATES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES[0]["OPTIONS"]["debug"] = DEBUG # noqa F405
TEMPLATES[0]["OPTIONS"]["loaders"] = [ # noqa F405
(
"django.template.loaders.cached.Loader",
[
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
],
)
]
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
# https://docs.djangoproject.com/en/dev/ref/settings/#email-host
EMAIL_HOST = "localhost"
# https://docs.djangoproject.com/en/dev/ref/settings/#email-port
EMAIL_PORT = 1025
# Your stuff...
# ------------------------------------------------------------------------------
| [] | [] | [] |
archives/097475_hansberger.zip | config/urls.py | from django.conf import settings
from django.urls import include, path
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
urlpatterns = [
path("", TemplateView.as_view(template_name="pages/home.html"), name="home"),
path(
"about/", TemplateView.as_view(template_name="pages/about.html"), name="about"
),
path("contact/", TemplateView.as_view(template_name="pages/contact.html"), name="contact"),
# Django Admin, use {% url 'admin:index' %}
path(settings.ADMIN_URL, admin.site.urls),
# User management
path("users/", include("hansberger.users.urls", namespace="users")),
path("accounts/", include("allauth.urls")),
# Your stuff: custom urls includes go here
path("research/", include("research.urls")),
path("research/<slug:research_slug>/datasets/", include("datasets.urls")),
path("research/<slug:research_slug>/analysis/", include("analysis.urls"))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [
path(
"400/",
default_views.bad_request,
kwargs={"exception": Exception("Bad Request!")},
),
path(
"403/",
default_views.permission_denied,
kwargs={"exception": Exception("Permission Denied")},
),
path(
"404/",
default_views.page_not_found,
kwargs={"exception": Exception("Page not Found")},
),
path("500/", default_views.server_error),
]
if "debug_toolbar" in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns = [path("__debug__/", include(debug_toolbar.urls))] + urlpatterns
| [] | [] | [] |
archives/097475_hansberger.zip | config/wsgi.py | """
WSGI config for HansBerger project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
import sys
from django.core.wsgi import get_wsgi_application
# This allows easy placement of apps within the interior
# hansberger directory.
app_path = os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir)
)
sys.path.append(os.path.join(app_path, "hansberger"))
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| [] | [] | [] |
archives/097475_hansberger.zip | docs/__init__.py | # Included so that Django's startproject comment runs against the docs directory
| [] | [] | [] |
archives/097475_hansberger.zip | docs/conf.py | # HansBerger documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
import sys
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix of source filenames.
source_suffix = ".rst"
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "HansBerger"
copyright = """2019, Matteo Belenchia and Sebastiano Verdolini"""
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = "0.1"
# The full version, including alpha/beta/rc tags.
release = "0.1"
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ["_build"]
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "default"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = "hansbergerdoc"
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
(
"index",
"hansberger.tex",
"HansBerger Documentation",
"""Matteo Belenchia and Sebastiano Verdolini""",
"manual",
)
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(
"index",
"hansberger",
"HansBerger Documentation",
["""Matteo Belenchia and Sebastiano Verdolini"""],
1,
)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
"index",
"hansberger",
"HansBerger Documentation",
"""Matteo Belenchia and Sebastiano Verdolini""",
"HansBerger",
"""Web application for topological analysis""",
"Miscellaneous",
)
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/__init__.py | __version__ = "0.1.0"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/__init__.py | default_app_config = 'analysis.apps.AnalysisConfig'
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/admin.py | from django.contrib import admin
# Register your models here.
from .models import FiltrationAnalysis, MapperAnalysis
admin.site.register(FiltrationAnalysis)
admin.site.register(MapperAnalysis)
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/apps.py | from django.apps import AppConfig
class AnalysisConfig(AppConfig):
name = 'analysis'
def ready(self):
import analysis.signals # noqa
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/consumers.py | from channels.generic.websocket import WebsocketConsumer
import json
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
def analysis_logger_decorator(func):
def wrapper(instance, *args, **kwargs):
status_logger = StatusHolder()
status_logger.set_limit(instance.get_expected_window_number())
func(instance, *args, **kwargs)
status_logger.reset()
return wrapper
def bottleneck_logger_decorator(func):
def wrapper(instance, *args, **kwargs):
status_logger = StatusHolder()
if instance.window is not None:
count = instance.window.get_window_number()
else:
count = instance.analysis.get_window_number()
status_logger.set_limit(count)
func(instance, *args, **kwargs)
status_logger.reset()
return wrapper
class StatusHolder(metaclass=Singleton):
def __init__(self):
self.reset()
def set_status(self, value):
self.status = value
def set_limit(self, value):
self.limit = value
def get_status(self):
return self.status
def get_limit(self):
return self.limit
def reset(self):
self.status = 0
self.limit = 0
self.kill = False
def set_kill(self):
self.kill = True
def get_kill(self):
return self.kill
class AnalysisConsumer(WebsocketConsumer):
def connect(self):
self.accept()
self.status_logger = StatusHolder()
def disconnect(self, close_code):
pass
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['signal']
if message == 'status':
self.send(text_data=json.dumps({
'status': self.status_logger.get_status(),
'limit': self.status_logger.get_limit()
}))
elif message == 'kill':
self.status_logger.set_kill()
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/forms.py | from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, Field, Div
from django.urls import reverse_lazy
from .models import FiltrationAnalysis, MapperAnalysis, Bottleneck
from datasets.models import Dataset, DatasetKindChoice
def analysis_name_unique_check(name, research):
return bool((FiltrationAnalysis.objects.filter(
research__slug=research.slug,
name=name
).first()
or
MapperAnalysis.objects.filter(
research__slug=research.slug,
name=name
).first()))
class SourceChoiceForm(forms.Form):
ANALYSIS_OPTIONS = [('filtration_analysis', "Filtration Analysis with ripser"),
('mapper_analysis', "Mapper Analysis with KeplerMapper")]
SOURCE_OPTIONS = [('dataset', 'Dataset'), ('precomputed', 'Precomputed distance matrices')]
analysis = forms.ChoiceField(widget=forms.RadioSelect, choices=ANALYSIS_OPTIONS)
source = forms.ChoiceField(widget=forms.RadioSelect, choices=SOURCE_OPTIONS)
class DatasetAnalysisCreationForm(forms.ModelForm):
def window_overlap_checks(self, window_size, window_overlap, dataset):
if dataset.kind == DatasetKindChoice.EDF.value:
dataset = dataset.edfdataset
elif dataset.kind == DatasetKindChoice.TEXT.value:
dataset = dataset.textdataset
if window_size == 0:
self.add_error("window_size", "Window size can't be equal to 0")
raise forms.ValidationError("Window size can't be equal to 0")
if window_size > len(dataset.get_matrix_data()[0]):
self.add_error("window_size", "Window size can't be greater than the number of columns in the dataset")
raise forms.ValidationError("Window size can't be greater than the number of columns in the dataset")
if window_overlap >= window_size:
self.add_error("window_overlap", "Window overlap can't be greater than or equal to window size")
raise forms.ValidationError("Window overlap can't be greater than or equal to window size")
class PrecomputedAnalysisCreationForm(forms.ModelForm):
precomputed_distance_matrix = forms.FileField(required=False)
class FiltrationAnalysisCreationForm_Dataset(DatasetAnalysisCreationForm):
def __init__(self, research, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['research'].initial = research
self.fields['dataset'].queryset = Dataset.objects.filter(research__slug=research.slug)
self.fields['dataset'].required = True
self.helper = FormHelper(self)
self.helper.form_method = 'POST'
self.helper.form_action = reverse_lazy('analysis:filtrationanalysis-create', kwargs={
'form': 'dataset',
'research_slug': research.slug})
self.helper.form_id = "analysis_form"
self.helper.layout = Layout(
'name',
'description',
Field('research', type="hidden"),
'dataset',
Div(id='peek_dataset'),
'window_size',
'window_overlap',
'filtration_type',
'distance_matrix_metric',
Fieldset(
'Ripser arguments',
'max_homology_dimension',
'max_distances_considered',
'coeff',
'do_cocycles',
'n_perm'
)
)
def clean(self):
cleaned_data = super().clean()
dataset = cleaned_data.get("dataset")
filtration_type = cleaned_data.get("filtration_type")
distance_matrix_metric = cleaned_data.get("distance_matrix_metric")
window_overlap = cleaned_data.get("window_overlap")
window_size = cleaned_data.get("window_size")
name = cleaned_data.get("name")
research = cleaned_data.get("research")
if analysis_name_unique_check(name, research):
self.add_error("name", "An analysis with this name already exists.")
raise forms.ValidationError("An analysis with this name already exists.")
if window_size is not None:
self.window_overlap_checks(window_size, window_overlap, dataset)
if filtration_type == FiltrationAnalysis.VIETORIS_RIPS_FILTRATION and distance_matrix_metric == '':
raise forms.ValidationError("You must provide a distance matrix metric for a Vietoris-Rips Filtration")
self.add_error("distance_matrix_metric",
"You must provide a distance matrix metric for a Vietoris-Rips Filtration")
class Meta:
model = FiltrationAnalysis
exclude = ['slug', 'precomputed_distance_matrix', 'precomputed_distance_matrix_json',
'entropy_normalized_graph', 'entropy_unnormalized_graph']
class FiltrationAnalysisCreationForm_Precomputed(PrecomputedAnalysisCreationForm):
def __init__(self, research, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['research'].initial = research
self.helper = FormHelper(self)
self.helper.form_method = 'POST'
self.helper.form_action = reverse_lazy('analysis:filtrationanalysis-create', kwargs={
'form': 'precomputed',
'research_slug': research.slug})
self.helper.form_id = "analysis_form"
self.helper.layout = Layout(
'name',
'description',
Field('research', type="hidden"),
Field('precomputed_distance_matrix', multiple=True),
Field('precomputed_distance_matrix_json', type="hidden"),
Fieldset(
'Ripser arguments',
'max_homology_dimension',
'max_distances_considered',
'coeff',
'do_cocycles',
'n_perm'
)
)
def clean(self):
cleaned_data = super().clean()
precomputed_distance_matrix = cleaned_data.get("precomputed_distance_matrix")
name = cleaned_data.get("name")
research = cleaned_data.get("research")
if analysis_name_unique_check(name, research):
self.add_error("name", "An analysis with this name already exists.")
raise forms.ValidationError("An analysis with this name already exists.")
if not precomputed_distance_matrix:
self.add_error("precomputed_distance_matrix", "You must provide a precomputed distance matrix")
raise forms.ValidationError("You must provide a precomputed distance matrix")
class Meta:
model = FiltrationAnalysis
exclude = ['slug', 'dataset', 'window_size', 'window_overlap', 'filtration_type', 'distance_matrix_metric',
'entropy_normalized_graph', 'entropy_unnormalized_graph']
class MapperAnalysisCreationForm_Dataset(DatasetAnalysisCreationForm):
def __init__(self, research, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['research'].initial = research
self.fields['dataset'].queryset = Dataset.objects.filter(research__slug=research.slug)
self.fields['dataset'].required = True
self.helper = FormHelper(self)
self.helper.form_method = 'POST'
self.helper.form_action = reverse_lazy('analysis:mapperanalysis-create', kwargs={
'form': 'dataset',
'research_slug': research.slug})
self.helper.form_id = "analysis_form"
self.helper.layout = Layout(
'name',
'description',
Field('research', type="hidden"),
'dataset',
Div(id='peek_dataset'),
'window_size',
'window_overlap',
'distance_matrix_metric',
Fieldset(
'fit_transform parameters',
'projection',
'knn_n_value',
'scaler',
),
Fieldset(
'map parameters',
'use_original_data',
'clusterer',
'cover_n_cubes',
'cover_perc_overlap',
'graph_nerve_min_intersection',
'precomputed',
'remove_duplicate_nodes'
)
)
def clean(self):
cleaned_data = super().clean()
dataset = cleaned_data.get("dataset")
window_overlap = cleaned_data.get("window_overlap")
window_size = cleaned_data.get("window_size")
name = cleaned_data.get("name")
research = cleaned_data.get("research")
projection = cleaned_data.get("projection")
knn_n_value = cleaned_data.get("knn_n_value")
distance_matrix_metric = cleaned_data.get("distance_matrix_metric")
if analysis_name_unique_check(name, research):
self.add_error("name", "An analysis with this name already exists.")
raise forms.ValidationError("An analysis with this name already exists.")
if window_size is not None:
self.window_overlap_checks(window_size, window_overlap, dataset)
if distance_matrix_metric == '':
self.add_error('distance_matrix_metric', 'Field required')
if projection == 'knn_distance_n' and not knn_n_value:
self.add_error("projection", "You must provide a value for n in knn_distance_n")
raise forms.ValidationError("You must provide a value for n in knn_distance_n")
class Meta:
model = MapperAnalysis
exclude = ['slug', 'graph', 'precomputed_distance_matrix', 'precomputed_distance_matrix_json']
class MapperAnalysisCreationForm_Precomputed(PrecomputedAnalysisCreationForm):
def __init__(self, research, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['research'].initial = research
self.helper = FormHelper(self)
self.helper.form_method = 'POST'
self.helper.form_action = reverse_lazy('analysis:mapperanalysis-create', kwargs={
'form': 'precomputed',
'research_slug': research.slug})
self.helper.form_id = "analysis_form"
self.helper.layout = Layout(
'name',
'description',
Field('research', type="hidden"),
Field('precomputed_distance_matrix', multiple=True),
Field('precomputed_distance_matrix_json', type="hidden"),
Fieldset(
'fit_transform parameters',
'projection',
'knn_n_value',
'scaler',
),
Fieldset(
'map parameters',
'use_original_data',
'clusterer',
'cover_n_cubes',
'cover_perc_overlap',
'graph_nerve_min_intersection',
'precomputed',
'remove_duplicate_nodes'
)
)
def clean(self):
cleaned_data = super().clean()
precomputed_distance_matrix = cleaned_data.get("precomputed_distance_matrix")
name = cleaned_data.get("name")
research = cleaned_data.get("research")
projection = cleaned_data.get("projection")
knn_n_value = cleaned_data.get("knn_n_value")
if analysis_name_unique_check(name, research):
self.add_error("name", "An analysis with this name already exists.")
raise forms.ValidationError("An analysis with this name already exists.")
if not precomputed_distance_matrix:
self.add_error("precomputed_distance_matrix", "You must provide a precomputed distance matrix")
raise forms.ValidationError("You must provide a precomputed distance matrix")
if projection == 'knn_distance_n' and not knn_n_value:
self.add_error("projection", "You must provide a value for n in knn_distance_n")
raise forms.ValidationError("You must provide a value for n in knn_distance_n")
class Meta:
model = MapperAnalysis
exclude = ['slug', 'graph', 'window_size', 'window_overlap', 'filtration_type', 'distance_matrix_metric']
class AnalysisBottleneckCreationForm(forms.Form):
BOTTLENECK_OPTIONS = [(Bottleneck.CONS, 'Bottleneck of consecutive windows'),
(Bottleneck.ALL, 'Bottleneck of each window to each window')]
bottleneck_type = forms.ChoiceField(widget=forms.RadioSelect, choices=BOTTLENECK_OPTIONS)
homology = forms.ChoiceField(widget=forms.RadioSelect)
def __init__(self, _homology, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['homology'].choices = [(i, i) for i in range(_homology+1)]
class WindowBottleneckCreationForm(forms.Form):
homology = forms.ChoiceField(widget=forms.RadioSelect)
def __init__(self, _homology, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['homology'].choices = [(i, i) for i in range(_homology+1)]
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/migrations/0001_initial.py | # Generated by Django 2.0.13 on 2019-06-27 17:04
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('research', '0001_initial'),
('datasets', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Bottleneck',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('homology', models.PositiveIntegerField()),
('kind', models.CharField(choices=[('consecutive', 'consecutive'), ('one_to_all', 'one_to_all'), ('all_to_all', 'all_to_all')], max_length=20)),
],
),
migrations.CreateModel(
name='Diagram',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', models.TextField()),
('bottleneck_distance', models.FloatField()),
('bottleneck', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='analysis.Bottleneck')),
],
),
migrations.CreateModel(
name='FiltrationAnalysis',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Name this analysis', max_length=100)),
('slug', models.SlugField(max_length=110)),
('description', models.TextField(blank=True, help_text='Write a brief description of the analysis', max_length=500)),
('creation_date', models.DateTimeField(auto_now_add=True)),
('precomputed_distance_matrix_json', django.contrib.postgres.fields.jsonb.JSONField(default='"[]"')),
('window_size', models.PositiveIntegerField(blank=True, default=None, help_text="Leave window size blank to not use windows. Window parameter\n is ignored when dealing with precomputed distance matrix. Always check\n the dimensions of the dataset your are operating on and plan your windows\n accordingly; eventual data that won't fit into the final window will be\n discarded.", null=True)),
('window_overlap', models.PositiveIntegerField(default=0, help_text='How many columns of overlap to have in\n consequent windows, if windows are being used. It must be at most 1\n less than window size.')),
('filtration_type', models.CharField(choices=[('VRF', 'Vietoris Rips Filtration'), ('CWRF', 'Clique Weighted Rank Filtration')], help_text='Choose the type of analysis.', max_length=50)),
('distance_matrix_metric', models.CharField(blank=True, choices=[('braycurtis', 'Braycurtis'), ('canberra', 'Canberra'), ('chebyshev', 'Chebyshev'), ('cityblock', 'City block'), ('correlation', 'Correlation'), ('cosine', 'Cosine'), ('dice', 'Dice'), ('euclidean', 'Euclidean'), ('hamming', 'Hamming'), ('jaccard', 'Jaccard'), ('jensenshannon', 'Jensen Shannon'), ('kulsinski', 'Kulsinski'), ('mahalanobis', 'Mahalonobis'), ('matching', 'Matching'), ('minkowski', 'Minkowski'), ('rogerstanimoto', 'Rogers-Tanimoto'), ('russellrao', 'Russel Rao'), ('seuclidean', 'Seuclidean'), ('sokalmichener', 'Sojal-Michener'), ('sokalsneath', 'Sokal-Sneath'), ('sqeuclidean', 'Sqeuclidean'), ('yule', 'Yule')], help_text='If Vietoris-Rips filtration is selected and not using a precomputed distance matrix, choose the\n distance metric to use on the selected dataset. This parameter is ignored in all other cases.', max_length=20)),
('max_homology_dimension', models.PositiveIntegerField(default=1, help_text='Maximum homology dimension computed. Will compute all dimensions lower than and equal to this value.\n For 1, H_0 and H_1 will be computed.')),
('max_distances_considered', models.FloatField(blank=True, default=None, help_text='Maximum distances considered when constructing filtration.\n If blank, compute the entire filtration.', null=True)),
('coeff', models.PositiveIntegerField(default=2, help_text='Compute homology with coefficients in the prime field Z/pZ for\n p=coeff.')),
('do_cocycles', models.BooleanField(default=False, help_text='Indicator of whether to compute cocycles.')),
('n_perm', models.IntegerField(blank=True, default=None, help_text='The number of points to subsample in\n a “greedy permutation,” or a furthest point sampling of the points. These points will\n be used in lieu of the full point cloud for a faster computation, at the expense of\n some accuracy, which can be bounded as a maximum bottleneck distance to all diagrams\n on the original point set', null=True)),
('entropy_normalized_graph', models.TextField(blank=True, null=True)),
('entropy_unnormalized_graph', models.TextField(blank=True, null=True)),
('dataset', models.ForeignKey(blank=True, default=None, help_text='Select the source dataset from the loaded datasets', null=True, on_delete=django.db.models.deletion.CASCADE, to='datasets.Dataset')),
('research', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='research.Research')),
],
options={
'verbose_name': 'filtration analysis',
'verbose_name_plural': 'filtration analyses',
'abstract': False,
},
),
migrations.CreateModel(
name='FiltrationWindow',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.PositiveIntegerField()),
('slug', models.SlugField(max_length=150)),
('creation_date', models.DateTimeField(auto_now_add=True)),
('start', models.PositiveIntegerField(blank=True, null=True)),
('end', models.PositiveIntegerField(blank=True, null=True)),
('result_matrix', django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True)),
('diagrams', django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True)),
('result_entropy_normalized', django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True)),
('result_entropy_unnormalized', django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True)),
('analysis', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='analysis.FiltrationAnalysis')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='MapperAnalysis',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Name this analysis', max_length=100)),
('slug', models.SlugField(max_length=110)),
('description', models.TextField(blank=True, help_text='Write a brief description of the analysis', max_length=500)),
('creation_date', models.DateTimeField(auto_now_add=True)),
('precomputed_distance_matrix_json', django.contrib.postgres.fields.jsonb.JSONField(default='"[]"')),
('window_size', models.PositiveIntegerField(blank=True, default=None, help_text="Leave window size blank to not use windows. Window parameter\n is ignored when dealing with precomputed distance matrix. Always check\n the dimensions of the dataset your are operating on and plan your windows\n accordingly; eventual data that won't fit into the final window will be\n discarded.", null=True)),
('window_overlap', models.PositiveIntegerField(default=0, help_text='How many columns of overlap to have in\n consequent windows, if windows are being used. It must be at most 1\n less than window size.')),
('distance_matrix_metric', models.CharField(blank=True, choices=[('braycurtis', 'Braycurtis'), ('canberra', 'Canberra'), ('chebyshev', 'Chebyshev'), ('cityblock', 'City block'), ('correlation', 'Correlation'), ('cosine', 'Cosine'), ('dice', 'Dice'), ('euclidean', 'Euclidean'), ('hamming', 'Hamming'), ('jaccard', 'Jaccard'), ('jensenshannon', 'Jensen Shannon'), ('kulsinski', 'Kulsinski'), ('mahalanobis', 'Mahalonobis'), ('matching', 'Matching'), ('minkowski', 'Minkowski'), ('rogerstanimoto', 'Rogers-Tanimoto'), ('russellrao', 'Russel Rao'), ('seuclidean', 'Seuclidean'), ('sokalmichener', 'Sojal-Michener'), ('sokalsneath', 'Sokal-Sneath'), ('sqeuclidean', 'Sqeuclidean'), ('yule', 'Yule')], help_text='If not using a precomputed matrix, choose the distance metric to use on the dataset.', max_length=20)),
('projection', models.CharField(choices=[('sum', 'Sum'), ('mean', 'Mean'), ('median', 'Median'), ('max', 'Max'), ('min', 'Min'), ('std', 'Std'), ('dist_mean', 'Dist_mean'), ('l2norm', 'L2norm'), ('knn_distance_n', 'knn_distance_n')], default='sum', help_text='Specify a projection/lens type.', max_length=50)),
('knn_n_value', models.PositiveIntegerField(blank=True, help_text='Specify the value of n in knn_distance_n', null=True)),
('scaler', models.CharField(choices=[('None', 'None'), ('MinMaxScaler', 'MinMaxScaler'), ('MaxAbsScaler', 'MaxAbsScaler'), ('RobustScaler', 'RobustScaler'), ('StandardScaler', 'StandardScaler')], default='MinMaxScaler', help_text='Scaler of the data applied after mapping. Use None for no scaling.', max_length=50)),
('use_original_data', models.BooleanField(default=False, help_text='If ticked, clustering is run on the original data,\n else it will be run on the lower dimensional projection.')),
('clusterer', models.CharField(choices=[('k-means', 'K-Means'), ('affinity_propagation', 'Affinity propagation'), ('mean-shift', 'Mean-shift'), ('spectral_clustering', 'Spectral clustering'), ('agglomerative_clustering', 'StandardScaler'), ('DBSCAN(min_samples=1)', 'DBSCAN(min_samples=1)'), ('DBSCAN', 'DBSCAN'), ('gaussian_mixtures', 'Gaussian mixtures'), ('birch', 'Birch')], default='DBSCAN', help_text='Select the clustering algorithm.', max_length=50)),
('cover_n_cubes', models.PositiveIntegerField(default=10, help_text='Number of hypercubes along each dimension.\n Sometimes referred to as resolution.')),
('cover_perc_overlap', models.FloatField(default=0.5, help_text='Amount of overlap between adjacent cubes calculated\n only along 1 dimension.')),
('graph_nerve_min_intersection', models.IntegerField(default=1, help_text='Minimum intersection considered when\n computing the nerve. An edge will be created only when the\n intersection between two nodes is greater than or equal to\n min_intersection')),
('precomputed', models.BooleanField(default=False, help_text='Tell Mapper whether the data that you are clustering on\n is a precomputed distance matrix. If set to True, the assumption is that you are\n also telling your clusterer that metric=’precomputed’ (which is an argument for\n DBSCAN among others), which will then cause the clusterer to expect a square\n distance matrix for each hypercube. precomputed=True will give a square matrix\n to the clusterer to fit on for each hypercube.')),
('remove_duplicate_nodes', models.BooleanField(default=False, help_text='Removes duplicate nodes before edges are\n determined. A node is considered to be duplicate if it has exactly\n the same set of points as another node.')),
('dataset', models.ForeignKey(blank=True, default=None, help_text='Select the source dataset from the loaded datasets', null=True, on_delete=django.db.models.deletion.CASCADE, to='datasets.Dataset')),
('research', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='research.Research')),
],
options={
'verbose_name': 'mapper algorithm analysis',
'verbose_name_plural': 'mapper algoritm analyses',
'abstract': False,
},
),
migrations.CreateModel(
name='MapperWindow',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.PositiveIntegerField()),
('slug', models.SlugField(max_length=150)),
('creation_date', models.DateTimeField(auto_now_add=True)),
('start', models.PositiveIntegerField(blank=True, null=True)),
('end', models.PositiveIntegerField(blank=True, null=True)),
('graph', models.TextField(blank=True, null=True)),
('analysis', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='windows', related_query_name='window', to='analysis.MapperAnalysis')),
],
options={
'abstract': False,
},
),
migrations.AddField(
model_name='diagram',
name='window1',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='window1', to='analysis.FiltrationWindow'),
),
migrations.AddField(
model_name='diagram',
name='window2',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='window2', to='analysis.FiltrationWindow'),
),
migrations.AddField(
model_name='bottleneck',
name='analysis',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='analysis.FiltrationAnalysis'),
),
migrations.AddField(
model_name='bottleneck',
name='window',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='analysis.FiltrationWindow'),
),
migrations.AlterUniqueTogether(
name='mapperanalysis',
unique_together={('slug', 'research')},
),
migrations.AlterUniqueTogether(
name='filtrationanalysis',
unique_together={('slug', 'research')},
),
]
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/migrations/0002_auto_20190628_1222.py | # Generated by Django 2.0.13 on 2019-06-28 10:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('analysis', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='filtrationwindow',
name='diagrams',
),
migrations.AddField(
model_name='filtrationwindow',
name='diagram',
field=models.TextField(blank=True, null=True),
),
]
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/migrations/__init__.py | [] | [] | [] |
|
archives/097475_hansberger.zip | hansberger/analysis/models/__init__.py | from .analysis import Analysis, MapperAnalysis, FiltrationAnalysis # noqa
from .window import Window, MapperWindow, FiltrationWindow # noqa
from .bottleneck import Bottleneck, Diagram # noqa | [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/models/analysis.py | import math
import json
import gc
import matplotlib
import matplotlib.pyplot as plt
import mpld3
import pandas
from django.db import models
from django.utils.text import slugify
from django.contrib.postgres.fields import JSONField
import ripser
import kmapper
import sklearn.cluster
import sklearn.preprocessing
import sklearn.mixture
import numpy
from research.models import Research
from datasets.models import Dataset, DatasetKindChoice
from datasets.models.dataset import distance_matrix, correlation_matrix
from .window import FiltrationWindow, MapperWindow, window_batch_generator
from .bottleneck import Bottleneck
from ..consumers import StatusHolder, analysis_logger_decorator
matplotlib.use('Agg')
class Analysis(models.Model):
def precomputed_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'research/precomputed/'+instance.slug+'/'+filename
METRIC_CHOICES = (
('braycurtis', 'Braycurtis'),
('canberra', 'Canberra'),
('chebyshev', 'Chebyshev'),
('cityblock', 'City block'),
('correlation', 'Correlation'),
('cosine', 'Cosine'),
('dice', 'Dice'),
('euclidean', 'Euclidean'),
('hamming', 'Hamming'),
('jaccard', 'Jaccard'),
('jensenshannon', 'Jensen Shannon'),
('kulsinski', 'Kulsinski'),
('mahalanobis', 'Mahalonobis'),
('matching', 'Matching'),
('minkowski', 'Minkowski'),
('rogerstanimoto', 'Rogers-Tanimoto'),
('russellrao', 'Russel Rao'),
('seuclidean', 'Seuclidean'),
('sokalmichener', 'Sojal-Michener'),
('sokalsneath', 'Sokal-Sneath'),
('sqeuclidean', 'Sqeuclidean'),
('yule', 'Yule'),
)
name = models.CharField(max_length=100, help_text="Name this analysis")
slug = models.SlugField(db_index=True, max_length=110)
description = models.TextField(max_length=500, blank=True, help_text="Write a brief description of the analysis")
creation_date = models.DateTimeField(auto_now_add=True)
research = models.ForeignKey(
Research,
on_delete=models.CASCADE
)
dataset = models.ForeignKey(
Dataset,
on_delete=models.CASCADE,
help_text="Select the source dataset from the loaded datasets",
default=None,
blank=True,
null=True
)
precomputed_distance_matrix_json = JSONField(default=json.dumps('[]'))
window_size = models.PositiveIntegerField(default=None, null=True, blank=True,
help_text="""Leave window size blank to not use windows. Window parameter
is ignored when dealing with precomputed distance matrix. Always check
the dimensions of the dataset your are operating on and plan your windows
accordingly; eventual data that won't fit into the final window will be
discarded.""")
window_overlap = models.PositiveIntegerField(default=0, help_text="""How many columns of overlap to have in
consequent windows, if windows are being used. It must be at most 1
less than window size.""")
def get_type(self):
return self._meta.verbose_name
def get_expected_window_number(self):
precomputed_distance_matrixes = json.loads(self.precomputed_distance_matrix_json)
if precomputed_distance_matrixes != []:
return len(precomputed_distance_matrixes)
elif self.window_size is not None:
matrix = self.dataset.get_matrix_data()
cols = len(matrix[0])
step = self.window_size - self.window_overlap
return 1 + (cols - self.window_size) // step
else:
return 1
class Meta:
abstract = True
unique_together = (('slug', 'research'))
def __str__(self):
return self.name
def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(self.name)
if self.dataset:
if self.dataset.kind == DatasetKindChoice.EDF.value:
self.dataset = self.dataset.edfdataset
elif self.dataset.kind == DatasetKindChoice.TEXT.value:
self.dataset = self.dataset.textdataset
super().save(*args, **kwargs)
class MapperAnalysis(Analysis):
scalers = {
'None': None,
'MinMaxScaler': sklearn.preprocessing.MinMaxScaler(),
'MaxAbsScaler': sklearn.preprocessing.MaxAbsScaler(),
'RobustScaler': sklearn.preprocessing.RobustScaler(),
'StandardScaler': sklearn.preprocessing.StandardScaler()
}
clusterers = {
'k-means': sklearn.cluster.KMeans(),
'affinity_propagation': sklearn.cluster.AffinityPropagation(),
'mean-shift': sklearn.cluster.MeanShift(),
'spectral_clustering': sklearn.cluster.SpectralClustering(),
'agglomerative_clustering': sklearn.cluster.AgglomerativeClustering(),
'DBSCAN': sklearn.cluster.DBSCAN(min_samples=3), # should be 3
'DBSCAN(min_samples=1)': sklearn.cluster.DBSCAN(min_samples=1), # should be 3
'gaussian_mixtures': sklearn.mixture.GaussianMixture(),
'birch': sklearn.cluster.Birch()
}
PROJECTION_CHOICES = (
('sum', 'Sum'),
('mean', 'Mean'),
('median', 'Median'),
('max', 'Max'),
('min', 'Min'),
('std', 'Std'),
('dist_mean', 'Dist_mean'),
('l2norm', 'L2norm'),
('knn_distance_n', 'knn_distance_n')
)
SCALER_CHOICES = (
('None', 'None'),
('MinMaxScaler', 'MinMaxScaler'),
('MaxAbsScaler', 'MaxAbsScaler'),
('RobustScaler', 'RobustScaler'),
('StandardScaler', 'StandardScaler'),
)
CLUSTERER_CHOICES = (
('k-means', 'K-Means'),
('affinity_propagation', 'Affinity propagation'),
('mean-shift', 'Mean-shift'),
('spectral_clustering', 'Spectral clustering'),
('agglomerative_clustering', 'StandardScaler'),
('DBSCAN(min_samples=1)', 'DBSCAN(min_samples=1)'),
('DBSCAN', 'DBSCAN'),
('gaussian_mixtures', 'Gaussian mixtures'),
('birch', 'Birch')
)
distance_matrix_metric = models.CharField(
max_length=20,
choices=Analysis.METRIC_CHOICES,
help_text="If not using a precomputed matrix, choose the distance metric to use on the dataset.",
blank=True
)
projection = models.CharField(
max_length=50,
choices=PROJECTION_CHOICES,
help_text="Specify a projection/lens type.",
default='sum'
)
knn_n_value = models.PositiveIntegerField(
help_text="Specify the value of n in knn_distance_n",
blank=True,
null=True
)
scaler = models.CharField(
max_length=50,
choices=SCALER_CHOICES,
help_text="Scaler of the data applied after mapping. Use None for no scaling.",
default='MinMaxScaler'
)
use_original_data = models.BooleanField(default=False, help_text="""If ticked, clustering is run on the original data,
else it will be run on the lower dimensional projection.""")
clusterer = models.CharField(
max_length=50,
choices=CLUSTERER_CHOICES,
default='DBSCAN',
help_text="Select the clustering algorithm."
)
cover_n_cubes = models.PositiveIntegerField(default=10, help_text="""Number of hypercubes along each dimension.
Sometimes referred to as resolution.""")
cover_perc_overlap = models.FloatField(default=0.5, help_text="""Amount of overlap between adjacent cubes calculated
only along 1 dimension.""")
graph_nerve_min_intersection = models.IntegerField(default=1, help_text="""Minimum intersection considered when
computing the nerve. An edge will be created only when the
intersection between two nodes is greater than or equal to
min_intersection""")
precomputed = models.BooleanField(default=False, help_text="""Tell Mapper whether the data that you are clustering on
is a precomputed distance matrix. If set to True, the assumption is that you are
also telling your clusterer that metric=’precomputed’ (which is an argument for
DBSCAN among others), which will then cause the clusterer to expect a square
distance matrix for each hypercube. precomputed=True will give a square matrix
to the clusterer to fit on for each hypercube.""")
remove_duplicate_nodes = models.BooleanField(default=False, help_text="""Removes duplicate nodes before edges are
determined. A node is considered to be duplicate if it has exactly
the same set of points as another node.""")
class Meta(Analysis.Meta):
verbose_name = "mapper algorithm analysis"
verbose_name_plural = "mapper algoritm analyses"
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
run_analysis(self)
def execute(self, distance_matrix, original_matrix=None, number=0):
mapper = kmapper.KeplerMapper()
mycover = kmapper.Cover(n_cubes=self.cover_n_cubes, perc_overlap=self.cover_perc_overlap)
mynerve = kmapper.GraphNerve(min_intersection=self.graph_nerve_min_intersection)
original_data = original_matrix.transpose() if self.use_original_data else None
projection = self.projection if self.projection != 'knn_distance_n' else 'knn_distance_' + str(self.knn_n_value)
projected_data = mapper.fit_transform(distance_matrix, projection=projection,
scaler=MapperAnalysis.scalers[self.scaler], distance_matrix=False)
graph = mapper.map(projected_data, X=original_data, clusterer=MapperAnalysis.clusterers[self.clusterer],
cover=mycover, nerve=mynerve, precomputed=self.precomputed,
remove_duplicate_nodes=self.remove_duplicate_nodes)
output_graph = mapper.visualize(graph, save_file=False)
window = MapperWindow.objects.create_window(number, self)
window.save_data(output_graph)
def get_window_number(self):
return MapperWindow.objects.filter(analysis=self).count()
class FiltrationAnalysis(Analysis):
VIETORIS_RIPS_FILTRATION = 'VRF'
CLIQUE_WEIGHTED_RANK_FILTRATION = 'CWRF'
FILTRATION_TYPE_CHOICES = (
(VIETORIS_RIPS_FILTRATION, 'Vietoris Rips Filtration'),
(CLIQUE_WEIGHTED_RANK_FILTRATION, 'Clique Weight Rank Filtration'),
)
filtration_type = models.CharField(
max_length=50,
choices=FILTRATION_TYPE_CHOICES,
help_text="Choose the type of analysis."
)
distance_matrix_metric = models.CharField(
max_length=20,
choices=Analysis.METRIC_CHOICES,
blank=True,
help_text="""If Vietoris-Rips filtration is selected and not using a precomputed distance matrix, choose the
distance metric to use on the selected dataset. This parameter is ignored in all other cases."""
)
max_homology_dimension = models.PositiveIntegerField(default=1, help_text="""Maximum homology dimension computed. Will compute all dimensions lower than and equal to this value.
For 1, H_0 and H_1 will be computed.""")
max_distances_considered = models.FloatField(default=None, null=True, blank=True, help_text="""Maximum distances considered when constructing filtration.
If blank, compute the entire filtration.""")
coeff = models.PositiveIntegerField(default=2, help_text="""Compute homology with coefficients in the prime field Z/pZ for
p=coeff.""")
do_cocycles = models.BooleanField(default=False, help_text="Indicator of whether to compute cocycles.")
n_perm = models.IntegerField(default=None, null=True, blank=True, help_text="""The number of points to subsample in
a “greedy permutation,” or a furthest point sampling of the points. These points will
be used in lieu of the full point cloud for a faster computation, at the expense of
some accuracy, which can be bounded as a maximum bottleneck distance to all diagrams
on the original point set""")
entropy_normalized_graph = models.TextField(blank=True, null=True)
entropy_unnormalized_graph = models.TextField(blank=True, null=True)
class Meta(Analysis.Meta):
verbose_name = "filtration analysis"
verbose_name_plural = "filtration analyses"
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
run_analysis(self)
self.entropy_normalized_graph = self.plot_entropy(True)
self.entropy_unnormalized_graph = self.plot_entropy(False)
super().save(*args, **kwargs)
@models.permalink
def get_absolute_url(self):
return ('research:filtrationanalysis-detail', (), {'filtrationanalysis_slug': self.slug,
'research_slug': self.research.slug})
def execute(self, input_matrix, number=0):
_thresh = math.inf if self.max_distances_considered is None else self.max_distances_considered
result = ripser.ripser(input_matrix, maxdim=self.max_homology_dimension, thresh=_thresh, coeff=self.coeff,
distance_matrix=True, do_cocycles=self.do_cocycles, n_perm=self.n_perm)
window = FiltrationWindow.objects.create_window(number, self)
window.save_data(result)
def get_entropy_data(self, normalized):
entropies = {"H"+str(i): [] for i in range(self.max_homology_dimension + 1)} # initialize result dict
for window_batch in window_batch_generator(self):
if normalized:
entropy_dicts = map(lambda window: json.loads(window.result_entropy_normalized), window_batch)
else:
entropy_dicts = map(lambda window: json.loads(window.result_entropy_unnormalized), window_batch)
for entropy_dict in entropy_dicts:
for key, value in entropy_dict.items():
entropies[key].append(value)
return entropies
def plot_entropy(self, normalized):
entropies = self.get_entropy_data(normalized)
plt.figure(figsize=(10, 5))
for key in entropies:
plt.plot(entropies[key], '-o')
plt.legend([key for key in entropies])
figure = plt.gcf()
html_figure = mpld3.fig_to_html(figure, template_type='general')
plt.close()
return html_figure
def get_entropy_csv(self):
entropies_normalized = self.get_entropy_data(True)
entropies_unnormalized = self.get_entropy_data(False)
entropies = {}
for key in entropies_normalized:
entropies[key+"_normalized"] = entropies_normalized[key]
for key in entropies_unnormalized:
entropies[key+"_unnormalized"] = entropies_unnormalized[key]
df = pandas.DataFrame(entropies)
return df.to_csv(index=True, header=True)
def bottleneck_calculation_consecutive(self, homology):
if Bottleneck.objects.filter(analysis=self, kind=Bottleneck.CONS, homology=homology).count() == 1:
return
# windows = FiltrationWindow.objects.filter(analysis=self).order_by('name')
windows = window_batch_generator(self)
bottleneck = Bottleneck.objects.create_bottleneck(self, Bottleneck.CONS, homology)
bottleneck.run_bottleneck(windows)
bottleneck.save()
def bottleneck_calculation_alltoall(self, homology):
if Bottleneck.objects.filter(analysis=self, kind=Bottleneck.ALL, homology=homology).count() == 1:
return
# windows = FiltrationWindow.objects.filter(analysis=self).order_by('name')
batch_1 = window_batch_generator(self)
batch_2 = window_batch_generator(self)
bottleneck = Bottleneck.objects.create_bottleneck(self, Bottleneck.ALL, homology)
bottleneck.run_bottleneck(batch_1, batch_2)
bottleneck.save()
def get_bottleneck(self, kind, homology):
return Bottleneck.objects.get(analysis=self, kind=kind, homology=homology)
def get_window_number(self):
return FiltrationWindow.objects.filter(analysis=self).count()
# multithreading decorator -> add connection.close() at end of function
'''
def start_new_thread(function):
def decorator(*args, **kwargs):
t = Thread(target=function, args=args, kwargs=kwargs)
t.daemon = True
t.start()
return decorator
'''
@analysis_logger_decorator
def single_run(instance):
analysis_type = type(instance)
StatusHolder().set_status(0)
if analysis_type is FiltrationAnalysis:
if instance.filtration_type == FiltrationAnalysis.VIETORIS_RIPS_FILTRATION:
input_matrix = instance.dataset.get_distance_matrix(instance.distance_matrix_metric)
elif instance.filtration_type == FiltrationAnalysis.CLIQUE_WEIGHTED_RANK_FILTRATION:
input_matrix = instance.dataset.get_correlation_matrix()
instance.execute(input_matrix)
elif analysis_type is MapperAnalysis:
input_matrix = instance.dataset.get_distance_matrix(instance.distance_matrix_metric)
original_matrix = numpy.array(instance.dataset.get_matrix_data())
instance.execute(input_matrix, original_matrix)
@analysis_logger_decorator
def multiple_run(instance, window_generator):
count = 0
analysis_type = type(instance)
if analysis_type is FiltrationAnalysis:
for window in window_generator:
if instance.filtration_type == FiltrationAnalysis.VIETORIS_RIPS_FILTRATION:
input_matrix = distance_matrix(window, instance.distance_matrix_metric)
elif instance.filtration_type == FiltrationAnalysis.CLIQUE_WEIGHTED_RANK_FILTRATION:
input_matrix = correlation_matrix(window)
instance.execute(input_matrix, count)
count = count + 1
if StatusHolder().get_kill():
return
StatusHolder().set_status(count)
elif analysis_type is MapperAnalysis:
for window in window_generator:
input_matrix = distance_matrix(window, instance.distance_matrix_metric)
original_matrix = numpy.array(window)
instance.execute(input_matrix, original_matrix, count)
count = count + 1
if StatusHolder().get_kill():
return
StatusHolder().set_status(count)
@analysis_logger_decorator
def multiple_run_precomputed(instance, precomputed_matrixes):
count = 0
analysis_type = type(instance)
if analysis_type is FiltrationAnalysis:
for matrix in precomputed_matrixes:
instance.execute(numpy.array(matrix), count)
count = count + 1
if StatusHolder().get_kill():
return
StatusHolder().set_status(count)
elif analysis_type is MapperAnalysis:
for matrix in precomputed_matrixes:
original_matrix = numpy.array(matrix)
instance.execute(numpy.array(matrix), original_matrix, count)
count = count + 1
if StatusHolder().get_kill():
return
StatusHolder().set_status(count)
def run_analysis(instance):
precomputed_distance_matrixes = json.loads(instance.precomputed_distance_matrix_json)
if instance.window_size is not None and precomputed_distance_matrixes == []:
window_generator = instance.dataset.split_matrix(instance.window_size, instance.window_overlap)
multiple_run(instance, window_generator)
elif precomputed_distance_matrixes != [] and instance.window_size is None:
multiple_run_precomputed(instance, precomputed_distance_matrixes)
else:
single_run(instance)
gc.collect()
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/models/bottleneck.py | import matplotlib
import matplotlib.pyplot as plt
import persim
import ripser
import base64
import numpy
import pandas
import gc
from io import BytesIO
from django.db import models
from django.core.exceptions import ObjectDoesNotExist
from ..consumers import StatusHolder, bottleneck_logger_decorator
matplotlib.use('Agg')
class BottleneckManager(models.Manager):
def create_bottleneck(self, owner, kind, homology):
if kind == Bottleneck.CONS or kind == Bottleneck.ALL:
bottleneck = self.create(analysis=owner, kind=kind, homology=homology)
elif kind == Bottleneck.ONE:
bottleneck = self.create(window=owner, kind=kind, homology=homology)
return bottleneck
class DiagramManager(models.Manager):
def create_diagram(self, bottleneck, window1, window2, value, image):
return self.create(bottleneck=bottleneck, window1=window1, window2=window2, bottleneck_distance=value,
image=image)
class Bottleneck(models.Model):
CONS = 'consecutive'
ONE = 'one_to_all'
ALL = 'all_to_all'
BOTTLENECK_TYPES = [(CONS, 'consecutive'), (ONE, 'one_to_all'), (ALL, 'all_to_all')]
analysis = models.ForeignKey(
'analysis.FiltrationAnalysis',
on_delete=models.CASCADE,
null=True
)
window = models.ForeignKey(
'analysis.FiltrationWindow',
on_delete=models.CASCADE,
null=True
)
homology = models.PositiveIntegerField()
kind = models.CharField(choices=BOTTLENECK_TYPES, max_length=20)
objects = BottleneckManager()
def manage_persim_crash(self, window, other_window_name):
diagram = window.get_diagram(self.homology)
if diagram == []:
diagram = numpy.empty(shape=(0, 2))
else:
diagram = numpy.array(diagram)
ripser.Rips().plot(diagram, labels='window_'+str(window.name)+', window_'+str(other_window_name))
# Save it to a temporary buffer.
buf = BytesIO()
plt.savefig(buf, format="png")
# Embed the result in the html output.
data = base64.b64encode(buf.getbuffer()).decode("ascii")
plt.close()
return (0, f"<img src='data:image/png;base64,{data}'/>")
def __bottleneck(self, reference_window, window):
diag1 = reference_window.get_diagram(self.homology)
diag2 = window.get_diagram(self.homology)
if diag1.size == 0 or diag2.size == 0:
return
if reference_window == window:
(d, image) = self.manage_persim_crash(reference_window, window.name)
else:
(d, (matching, D)) = persim.bottleneck(diag1, diag2, True)
image = self.plot_bottleneck(reference_window, window, matching, D)
diagram = Diagram.objects.create_diagram(self, reference_window, window, d, image)
diagram.save()
@bottleneck_logger_decorator
def bottleneck_calculation_CONS(self, windows):
last = None
for window_batch in windows:
batch = list(window_batch)
if last is not None and batch != []:
self.__bottleneck(last, batch[0])
for i, window1 in enumerate(batch[:-1]):
window2 = batch[i+1]
self.__bottleneck(window1, window2)
if StatusHolder().get_kill():
return
StatusHolder().set_status(window1.name)
last = batch[-1]
@bottleneck_logger_decorator
def bottleneck_calculation_ONE(self, windows):
reference_window = self.window
for window_batch in windows:
for window in window_batch:
self.__bottleneck(reference_window, window)
if StatusHolder().get_kill():
return
StatusHolder().set_status(window.name)
gc.collect()
@bottleneck_logger_decorator
def bottleneck_calculation_ALL(self, batch_1, batch_2):
batch_2 = list(batch_2)
for window_batch_1 in batch_1:
for reference_window in window_batch_1:
StatusHolder().set_status(reference_window.name)
for window_batch_2 in batch_2:
for window in window_batch_2:
if window.name < reference_window.name:
continue
self.__bottleneck(reference_window, window)
if StatusHolder().get_kill():
return
gc.collect()
gc.collect()
def plot_bottleneck(self, window1, window2, matchidx, D):
persim.bottleneck_matching(window1.get_diagram(self.homology), window2.get_diagram(self.homology), matchidx, D,
labels=["window_"+str(window1.name), "window_"+str(window2.name)])
buf = BytesIO()
plt.savefig(buf, format="png")
# Embed the result in the html output.
data = base64.b64encode(buf.getbuffer()).decode("ascii")
plt.close()
return f"<img src='data:image/png;base64,{data}'/>"
def run_bottleneck(self, *args):
if self.kind == self.ONE:
self.bottleneck_calculation_ONE(*args)
elif self.kind == self.CONS:
self.bottleneck_calculation_CONS(*args)
elif self.kind == self.ALL:
self.bottleneck_calculation_ALL(*args)
def get_bottleneck_matrix(self):
diagrams = Diagram.objects.filter(bottleneck=self).order_by('window1__name', 'window2__name')
if self.kind == self.ONE:
data = []
labels = []
reference_window = diagrams.first().window1.name
for diagram in diagrams:
data.append(diagram.bottleneck_distance)
labels.append(str(diagram.window2.name))
df = pandas.DataFrame([data], index=[str(reference_window)], columns=labels)
return df.to_csv(index=True, header=True)
elif self.kind == self.CONS:
data = []
labels = []
for diagram in diagrams:
data.append(diagram.bottleneck_distance)
labels.append(str(diagram.window1.name))
df = pandas.DataFrame([data], index=['n+1'], columns=labels)
return df.to_csv(index=True, header=True)
elif self.kind == self.ALL:
row = diagrams.filter(window1__name=0)
n_cols = row.count() # actual number of cols
expected_cols = self.analysis.get_window_number()
labels = [i for i in range(expected_cols)]
matrix = []
i = 0
while(n_cols != 0):
current_row = []
for j in range(expected_cols):
if j < i:
current_row.append(0)
else:
try:
current_row.append(diagrams.get(window1__name=i, window2__name=j).bottleneck_distance)
except ObjectDoesNotExist:
current_row.append(float('NaN'))
matrix.append(current_row)
i = i + 1
row = diagrams.filter(window1__name=i)
n_cols = row.count()
if matrix == [] or len(matrix) < expected_cols:
for i in range(expected_cols - len(matrix)):
matrix.append([float('NaN')]*expected_cols)
out = matrix
else:
matrix = numpy.array(matrix)
out = matrix.T + matrix
numpy.fill_diagonal(out, numpy.diag(matrix))
df = pandas.DataFrame(out, index=labels, columns=labels)
return df.to_csv(index=True, header=True)
def get_diagrams(self):
return Diagram.objects.filter(bottleneck=self).order_by('window1__name', 'window2__name')
class Diagram(models.Model):
bottleneck = models.ForeignKey(
Bottleneck,
on_delete=models.CASCADE
)
window1 = models.ForeignKey(
'analysis.FiltrationWindow',
on_delete=models.CASCADE,
related_name='window1'
)
window2 = models.ForeignKey(
'analysis.FiltrationWindow',
on_delete=models.CASCADE,
related_name='window2'
)
image = models.TextField()
bottleneck_distance = models.FloatField()
objects = DiagramManager()
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/models/window.py | import json
import matplotlib
import matplotlib.pyplot as plt
import ripser
import numpy
import math
import base64
from io import BytesIO
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.utils.text import slugify
from .bottleneck import Bottleneck
matplotlib.use('Agg')
def window_batch_generator(analysis):
window_count = FiltrationWindow.objects.filter(analysis=analysis).order_by('name').count()
batch_size = window_count // 16 if window_count > 16 else 16
remainder = 1 if window_count % 16 != 0 else 0
for window_batch in range(window_count // batch_size + remainder):
windows = FiltrationWindow.objects.filter(analysis=analysis).order_by(
'name')[batch_size*window_batch:batch_size*window_batch+batch_size]
yield windows
class WindowManager(models.Manager):
def create_window(self, name, analysis):
window = self.create(name=name, analysis=analysis)
return window
class Window(models.Model):
name = models.PositiveIntegerField()
slug = models.SlugField(db_index=True, max_length=150)
creation_date = models.DateTimeField(auto_now_add=True)
start = models.PositiveIntegerField(null=True, blank=True)
end = models.PositiveIntegerField(null=True, blank=True)
class Meta:
abstract = True
def save_window_info(self):
analysis = self.analysis
if json.loads(analysis.precomputed_distance_matrix_json) != []: # no windows and no datasets are being used
self.start = None
self.end = None
else:
if analysis.window_size is None: # no windows are used
self.start = 0
self.end = analysis.dataset.cols
else:
self.start = 0 if self.name == 0 else self.name * analysis.window_size - analysis.window_overlap
self.end = self.start + analysis.window_size
def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(self.name)
super().save(*args, **kwargs)
class FiltrationWindow(Window):
analysis = models.ForeignKey(
'analysis.FiltrationAnalysis',
on_delete=models.CASCADE
)
result_matrix = JSONField(blank=True, null=True)
diagram = models.TextField(blank=True, null=True)
result_entropy_normalized = JSONField(blank=True, null=True)
result_entropy_unnormalized = JSONField(blank=True, null=True)
objects = WindowManager()
def save_data(self, result):
self.save_diagram(result['dgms'])
self.save_entropy_json(result['dgms'])
self.save_matrix_json(result) # this method modifies permanently the result dict
self.save_window_info()
self.save()
def save_diagram(self, diagrams):
self.diagram = self.plot(diagrams)
def get_diagram(self, homology):
diagrams = json.loads(self.result_matrix)['dgms']
return numpy.array(diagrams[homology])
def save_matrix_json(self, analysis_result_matrix):
for k in analysis_result_matrix:
if isinstance(analysis_result_matrix[k], numpy.ndarray):
analysis_result_matrix[k] = analysis_result_matrix[k].tolist()
elif isinstance(analysis_result_matrix[k], list):
analysis_result_matrix[k] = [l.tolist() for l in analysis_result_matrix[k]
if isinstance(l, numpy.ndarray)]
self.result_matrix = json.dumps(analysis_result_matrix)
def save_entropy_json(self, diagrams):
entropies_normalized = dict()
entropies_unnormalized = dict()
i = 0
for ripser_matrix in diagrams:
entropies_normalized["H"+str(i)] = FiltrationWindow.calculate_entropy(ripser_matrix, True)
entropies_unnormalized["H"+str(i)] = FiltrationWindow.calculate_entropy(ripser_matrix, False)
i = i + 1
self.result_entropy_normalized = json.dumps(entropies_normalized)
self.result_entropy_unnormalized = json.dumps(entropies_unnormalized)
@staticmethod
def calculate_entropy(ripser_matrix, normalize=False):
if ripser_matrix.size == 0:
return 0
non_infinity = list(filter((lambda x: x[1] != math.inf), ripser_matrix))
if non_infinity == []: # single infinity element
return 0
max_death = max(map((lambda x: x[1]), non_infinity)) + 1
li = list(map((lambda x: x[1]-x[0] if x[1] != math.inf else max_death - x[0]), ripser_matrix))
ltot = sum(li)
if normalize:
norm_value = (1 / numpy.log10(len(ripser_matrix))) if len(ripser_matrix) != 1 else 1
return norm_value * -sum(map((lambda x: x/ltot * numpy.log10(x/ltot)), li))
else:
return -sum(map((lambda x: x/ltot * math.log10(x/ltot)), li))
def plot(self, diagrams):
ripser.Rips().plot(diagrams)
# Save it to a temporary buffer.
buf = BytesIO()
plt.savefig(buf, format="png")
# Embed the result in the html output.
data = base64.b64encode(buf.getbuffer()).decode("ascii")
plt.close()
return f"<img src='data:image/png;base64,{data}'/>"
def bottleneck_calculation_onetoall(self, homology):
if Bottleneck.objects.filter(window=self, kind=Bottleneck.ONE, homology=homology).count() == 1:
return
# windows = FiltrationWindow.objects.filter(analysis=self.analysis).order_by('name')
windows = window_batch_generator(self.analysis)
bottleneck = Bottleneck.objects.create_bottleneck(self, Bottleneck.ONE, homology)
bottleneck.run_bottleneck(windows)
bottleneck.save()
def get_bottleneck(self, homology):
return Bottleneck.objects.get(window=self, kind=Bottleneck.ONE, homology=homology)
def get_window_number(self):
return self.analysis.get_window_number()
class MapperWindow(Window):
analysis = models.ForeignKey(
'analysis.MapperAnalysis',
on_delete=models.CASCADE,
related_name='windows',
related_query_name='window'
)
graph = models.TextField(blank=True, null=True)
objects = WindowManager()
def save_data(self, output_graph):
self.graph = output_graph
self.save_window_info()
self.save()
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/routing.py | from django.conf.urls import url
from . import consumers
websocket_urlpatterns = [
# (http->django views is added by default)
url(r'^ws/analysis/', consumers.AnalysisConsumer),
]
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/signals.py | [] | [] | [] |
|
archives/097475_hansberger.zip | hansberger/analysis/tests.py | from django.test import TestCase
# Create your tests here.
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/urls.py | from django.urls import path
from .views import (
AnalysisListView,
FiltrationAnalysisCreateView,
MapperAnalysisCreateView,
AnalysisDetailView,
AnalysisDeleteView,
WindowListView,
WindowDetailView,
MapperAnalysisView,
WindowBottleneckView,
AnalysisConsecutiveBottleneckView,
AnalysisAlltoallBottleneckView,
SourceChoice,
RipserDownloadView,
EntropyDownloadView,
BottleneckALLDownloadView,
BottleneckCONSDownloadView,
BottleneckONEDownloadView,
AnalysisBottleneckCreateView,
WindowBottleneckCreateView,
ONEBottleneckDeleteView,
CONSBottleneckDeleteView,
ALLBottleneckDeleteView
)
app_name = 'analysis'
urlpatterns = [
path("", view=AnalysisListView.as_view(), name="analysis-list"),
path("add/", view=SourceChoice, name="analysis-source-choice"),
path("add/<form>/filtrationanalysis/", view=FiltrationAnalysisCreateView.as_view(), name="filtrationanalysis-create"), # noqa
path("add/<form>/mapperanalysis/", view=MapperAnalysisCreateView.as_view(), name="mapperanalysis-create"), # noqa
path("<slug:analysis_slug>/", view=AnalysisDetailView.as_view(), name="analysis-detail"), # noqa
path("<slug:analysis_slug>/delete/", view=AnalysisDeleteView.as_view(), name="analysis-delete"), # noqa
path("<slug:analysis_slug>/windows/", view=WindowListView.as_view(), name="window-list"), # noqa
path("<slug:analysis_slug>/windows/<slug:window_slug>/", view=WindowDetailView.as_view(), name="window-detail"), # noqa
path("<slug:analysis_slug>/windows/<slug:window_slug>/bottleneck/", view=WindowBottleneckCreateView, name="window-bottleneck-create"), # noqa
path("<slug:analysis_slug>/windows/<slug:window_slug>/graph/", view=MapperAnalysisView.as_view(), name="mapperanalysis-graph"), # noqa
path("<slug:analysis_slug>/windows/<slug:window_slug>/<int:homology>/bottleneck_onetoall/", view=WindowBottleneckView.as_view(), name="window-bottleneck-onetoall"), # noqa
path("<slug:analysis_slug>/bottleneck/", view=AnalysisBottleneckCreateView, name="analysis-bottleneck-create"), # noqa
path("<slug:analysis_slug>/<int:homology>/bottleneck_consecutive/", view=AnalysisConsecutiveBottleneckView.as_view(), name="analysis-bottleneck-consecutive"), # noqa
path("<slug:analysis_slug>/<int:homology>/bottleneck_alltoall/", view=AnalysisAlltoallBottleneckView.as_view(), name="analysis-bottleneck-alltoall"), # noqa
path("<slug:analysis_slug>/windows/<slug:window_slug>/ripser_download/", view=RipserDownloadView.as_view(), name="ripser-download"), # noqa
path("<slug:analysis_slug>/entropy_download/", view=EntropyDownloadView.as_view(), name="entropy-download"), # noqa
path("<slug:analysis_slug>/<int:homology>/bottleneck_alltoall/bottleneck_ALL_download/", view=BottleneckALLDownloadView.as_view(), name="bottleneck-ALL-download"), # noqa
path("<slug:analysis_slug>/<int:homology>/bottleneck_consecutive/bottleneck_CONS_download/", view=BottleneckCONSDownloadView.as_view(), name="bottleneck-CONS-download"), # noqa
path("<slug:analysis_slug>/windows/<slug:window_slug>/<int:homology>/bottleneck_onetoall/bottleneck_ONE_download/", view=BottleneckONEDownloadView.as_view(), name="bottleneck-ONE-download"), # noqa
path("<slug:analysis_slug>/windows/<slug:window_slug>/<int:homology>/bottleneck_onetoall/delete/", view=ONEBottleneckDeleteView.as_view(), name="bottleneck-delete-ONE"), # noqa
path("<slug:analysis_slug>/<int:homology>/bottleneck_consecutive/delete/", view=CONSBottleneckDeleteView.as_view(), name="bottleneck-delete-CONS"), # noqa
path("<slug:analysis_slug>/<int:homology>/bottleneck_alltoall/delete/", view=ALLBottleneckDeleteView.as_view(), name="bottleneck-delete-ALL"), # noqa
]
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/analysis/views.py | import numpy
import json
from itertools import chain
from django.shortcuts import redirect
from django.http import HttpResponse
from django_downloadview import VirtualDownloadView
from django.core.files.base import ContentFile
from django.shortcuts import get_object_or_404, render
from django.urls import reverse_lazy
from django.db.transaction import non_atomic_requests
from django.utils.decorators import method_decorator
from django.views.generic import (
View,
CreateView,
DeleteView,
DetailView,
ListView,
)
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import (
Analysis,
FiltrationAnalysis,
MapperAnalysis,
Window,
FiltrationWindow,
MapperWindow,
Bottleneck,
)
from research.models import Research
from .forms import (
SourceChoiceForm,
FiltrationAnalysisCreationForm_Dataset,
FiltrationAnalysisCreationForm_Precomputed,
MapperAnalysisCreationForm_Dataset,
MapperAnalysisCreationForm_Precomputed,
AnalysisBottleneckCreationForm,
WindowBottleneckCreationForm
)
form_dict = {
'filtration_analysis': {
'precomputed': FiltrationAnalysisCreationForm_Precomputed,
'dataset': FiltrationAnalysisCreationForm_Dataset
},
'mapper_analysis': {
'precomputed': MapperAnalysisCreationForm_Precomputed,
'dataset': MapperAnalysisCreationForm_Dataset
}
}
def SourceChoice(request, research_slug):
research = get_object_or_404(Research, slug=research_slug)
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = SourceChoiceForm(request.POST)
# check whether it's valid:
if form.is_valid():
cleaned_data = form.cleaned_data
analysis = cleaned_data.get("analysis")
source = cleaned_data.get("source")
if analysis == 'filtration_analysis':
return redirect('analysis:filtrationanalysis-create', form=source, research_slug=research.slug)
elif analysis == 'mapper_analysis':
return redirect('analysis:mapperanalysis-create', form=source, research_slug=research.slug)
# if a GET (or any other method) we'll create a blank form
else:
form = SourceChoiceForm()
return render(request, 'analysis/analysis_source_choice.html', {'form': form, 'research': research})
class AnalysisDetailView(View):
def get(self, request, *args, **kwargs):
my_analysis = (FiltrationAnalysis.objects.filter(
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
).first()
or
MapperAnalysis.objects.filter(
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
).first())
if isinstance(my_analysis, FiltrationAnalysis):
return render(request, 'analysis/filtrationanalysis_detail.html', context={'analysis': my_analysis,
'homology': range(my_analysis.max_homology_dimension + 1)})
elif isinstance(my_analysis, MapperAnalysis):
return render(request, 'analysis/mapperanalysis_detail.html', context={'analysis': my_analysis})
class AnalysisDeleteView(DeleteView):
model = Analysis
context_object_name = 'analysis'
template_name = "analysis/analysis_confirm_delete.html"
def get_object(self):
return (FiltrationAnalysis.objects.filter(
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
).first()
or
MapperAnalysis.objects.filter(
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
).first())
def get_success_url(self):
return reverse_lazy('analysis:analysis-list', kwargs={
'research_slug': self.kwargs['research_slug']
})
class AnalysisListView(ListView):
model = Analysis
context_object_name = 'analyses'
paginate_by = 10
template_name = "analysis/analysis_list.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['research'] = self.research
return context
def get_queryset(self):
self.research = get_object_or_404(
Research,
slug=self.kwargs['research_slug']
)
filtration_analyses = FiltrationAnalysis.objects.filter(
research=self.research
).only('name', 'creation_date', 'slug', 'research')
mapper_analyses = MapperAnalysis.objects.filter(
research=self.research
).only('name', 'creation_date', 'slug', 'research')
return sorted(chain(filtration_analyses, mapper_analyses), key=lambda x: x.creation_date, reverse=True)
@method_decorator(non_atomic_requests, name='dispatch')
class FiltrationAnalysisCreateView(CreateView):
model = FiltrationAnalysis
def get_template_names(self):
print(self.get_form_class())
if self.get_form_class() is FiltrationAnalysisCreationForm_Dataset:
return "analysis/filtrationanalysis_dataset_form.html"
elif self.get_form_class() is FiltrationAnalysisCreationForm_Precomputed:
return "analysis/filtrationanalysis_precomputed_form.html"
def get_form_class(self):
return form_dict['filtration_analysis'][self.kwargs['form']]
def get_success_url(self):
return reverse_lazy('analysis:analysis-detail', kwargs={
'research_slug': self.kwargs['research_slug'],
'analysis_slug': self.analysis.slug
})
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['research'] = self.research
return context
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
self.research = get_object_or_404(
Research,
slug=self.kwargs['research_slug']
)
kwargs['research'] = self.research
return kwargs
def form_valid(self, form):
self.analysis = form.save(commit=False)
self.analysis.precomputed_distance_matrix_json = self.precomputed_distance_matrix_json
return super().form_valid(form)
def post(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
files = request.FILES.getlist('precomputed_distance_matrix')
if form.is_valid():
precomputed_distance_matrixes = []
for f in sorted(files):
precomputed_distance_matrixes.append(numpy.loadtxt(f).tolist())
self.precomputed_distance_matrix_json = json.dumps(precomputed_distance_matrixes)
return self.form_valid(form)
else:
return self.form_invalid(form)
@method_decorator(non_atomic_requests, name='dispatch')
class MapperAnalysisCreateView(CreateView):
model = MapperAnalysis
def get_template_names(self):
if self.get_form_class() is MapperAnalysisCreationForm_Dataset:
return "analysis/mapperanalysis_dataset_form.html"
elif self.get_form_class() is MapperAnalysisCreationForm_Precomputed:
return "analysis/mapperanalysis_precomputed_form.html"
def get_form_class(self):
return form_dict['mapper_analysis'][self.kwargs['form']]
def get_success_url(self):
return reverse_lazy('analysis:analysis-detail', kwargs={
'research_slug': self.kwargs['research_slug'],
'analysis_slug': self.analysis.slug
})
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['research'] = self.research
return context
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
self.research = get_object_or_404(
Research,
slug=self.kwargs['research_slug']
)
kwargs['research'] = self.research
return kwargs
def form_valid(self, form):
self.analysis = form.save(commit=False)
self.analysis.precomputed_distance_matrix_json = self.precomputed_distance_matrix_json
return super().form_valid(form)
def post(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
files = request.FILES.getlist('precomputed_distance_matrix')
if form.is_valid():
precomputed_distance_matrixes = []
for f in files:
precomputed_distance_matrixes.append(numpy.loadtxt(f).tolist())
self.precomputed_distance_matrix_json = json.dumps(precomputed_distance_matrixes)
return self.form_valid(form)
else:
return self.form_invalid(form)
class MapperAnalysisView(View):
def get(self, request, *args, **kwargs):
my_analysis = get_object_or_404(
MapperAnalysis,
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
)
my_window = get_object_or_404(
MapperWindow,
analysis=my_analysis,
slug=self.kwargs['window_slug']
)
return HttpResponse(my_window.graph)
class WindowDetailView(DetailView):
def get(self, request, *args, **kwargs):
my_analysis = (FiltrationAnalysis.objects.filter(
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
).first()
or
MapperAnalysis.objects.filter(
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
).first())
if type(my_analysis) is FiltrationAnalysis:
my_window = get_object_or_404(
FiltrationWindow,
analysis=my_analysis,
slug=self.kwargs['window_slug']
)
elif type(my_analysis) is MapperAnalysis:
my_window = get_object_or_404(
MapperWindow,
analysis=my_analysis,
slug=self.kwargs['window_slug']
)
if isinstance(my_window, FiltrationWindow):
return render(request, 'analysis/window/filtrationwindow_detail.html', context={'window': my_window,
'homology': range(my_analysis.max_homology_dimension + 1)})
elif isinstance(my_window, MapperWindow):
return render(request, 'analysis/window/mapperwindow_detail.html', context={'window': my_window})
class WindowListView(ListView):
model = Window
context_object_name = 'windows'
paginate_by = 10
template_name = "analysis/window/window_list.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['analysis'] = self.analysis
return context
def get_queryset(self):
self.analysis = (FiltrationAnalysis.objects.filter(
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
).first()
or
MapperAnalysis.objects.filter(
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
).first())
if type(self.analysis) is FiltrationAnalysis:
windows = FiltrationWindow.objects.filter(
analysis=self.analysis
)
elif type(self.analysis) is MapperAnalysis:
windows = MapperWindow.objects.filter(
analysis=self.analysis
)
return windows.only('name', 'creation_date', 'slug').order_by('name')
class WindowBottleneckView(View):
def get(self, request, *args, **kwargs):
my_analysis = get_object_or_404(
FiltrationAnalysis,
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
)
my_window = get_object_or_404(
FiltrationWindow,
analysis=my_analysis,
slug=self.kwargs['window_slug']
)
my_window.bottleneck_calculation_onetoall(self.kwargs['homology'])
bottleneck = my_window.get_bottleneck(self.kwargs['homology'])
diagram_list = bottleneck.get_diagrams()
page = request.GET.get('page', 1)
paginator = Paginator(diagram_list, 10)
try:
diagrams = paginator.page(page)
except PageNotAnInteger:
diagrams = paginator.page(1)
except EmptyPage:
diagrams = paginator.page(paginator.num_pages)
return render(request, 'analysis/window/filtrationwindow_bottleneck.html', context={'diagrams': diagrams,
'window': my_window})
class AnalysisConsecutiveBottleneckView(View):
def get(self, request, *args, **kwargs):
my_analysis = get_object_or_404(
FiltrationAnalysis,
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
)
my_analysis.bottleneck_calculation_consecutive(self.kwargs['homology'])
bottleneck = my_analysis.get_bottleneck(Bottleneck.CONS, self.kwargs['homology'])
diagram_list = bottleneck.get_diagrams()
page = request.GET.get('page', 1)
paginator = Paginator(diagram_list, 10)
try:
diagrams = paginator.page(page)
except PageNotAnInteger:
diagrams = paginator.page(1)
except EmptyPage:
diagrams = paginator.page(paginator.num_pages)
return render(request, 'analysis/filtrationanalysis_bottleneck_consecutive.html',
context={'diagrams': diagrams,
'analysis': my_analysis
})
class AnalysisAlltoallBottleneckView(View):
def get(self, request, *args, **kwargs):
my_analysis = get_object_or_404(
FiltrationAnalysis,
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
)
my_analysis.bottleneck_calculation_alltoall(self.kwargs['homology'])
bottleneck = my_analysis.get_bottleneck(Bottleneck.ALL, self.kwargs['homology'])
diagram_list = bottleneck.get_diagrams()
page = request.GET.get('page', 1)
paginator = Paginator(diagram_list, 10)
try:
diagrams = paginator.page(page)
except PageNotAnInteger:
diagrams = paginator.page(1)
except EmptyPage:
diagrams = paginator.page(paginator.num_pages)
return render(request, 'analysis/filtrationanalysis_bottleneck_alltoall.html',
context={'diagrams': diagrams,
'analysis': my_analysis
})
class RipserDownloadView(VirtualDownloadView):
def get_object(self):
my_analysis = get_object_or_404(
FiltrationAnalysis,
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
)
return get_object_or_404(
FiltrationWindow,
analysis=my_analysis,
slug=self.kwargs['window_slug']
)
def get_file(self):
window_analysis = self.get_object()
return ContentFile(window_analysis.result_matrix, name=window_analysis.analysis.research.name + '_' +
window_analysis.analysis.name + '_' + str(window_analysis.name) + '.dat')
class EntropyDownloadView(VirtualDownloadView):
def get_object(self):
return get_object_or_404(
FiltrationAnalysis,
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
)
def get_file(self):
analysis = self.get_object()
return ContentFile(analysis.get_entropy_csv(), name=analysis.research.name + '_' +
analysis.name + '_entropy.csv')
class BottleneckONEDownloadView(VirtualDownloadView):
def get_object(self):
my_analysis = get_object_or_404(
FiltrationAnalysis,
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
)
my_window = get_object_or_404(
FiltrationWindow,
analysis=my_analysis,
slug=self.kwargs['window_slug']
)
return get_object_or_404(
Bottleneck,
window=my_window,
kind=Bottleneck.ONE,
homology=self.kwargs['homology']
)
def get_file(self):
bottleneck = self.get_object()
return ContentFile(bottleneck.get_bottleneck_matrix(),
name=bottleneck.window.analysis.research.name + '_' +
bottleneck.window.analysis.name + '_' +
str(bottleneck.window.name) + '_bottleneck_distance_one_to_all_H' + str(bottleneck.homology)
+ '.csv')
class BottleneckALLDownloadView(VirtualDownloadView):
def get_object(self):
my_analysis = get_object_or_404(
FiltrationAnalysis,
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
)
return get_object_or_404(
Bottleneck,
analysis=my_analysis,
kind=Bottleneck.ALL,
homology=self.kwargs['homology']
)
def get_file(self):
bottleneck = self.get_object()
return ContentFile(bottleneck.get_bottleneck_matrix(), name=bottleneck.analysis.research.name + '_'
+ bottleneck.analysis.name + '_bottleneck_distance_all_to_all_H' +
str(bottleneck.homology) + '.csv')
class BottleneckCONSDownloadView(VirtualDownloadView):
def get_object(self):
my_analysis = get_object_or_404(
FiltrationAnalysis,
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
)
return get_object_or_404(
Bottleneck,
analysis=my_analysis,
kind=Bottleneck.CONS,
homology=self.kwargs['homology']
)
def get_file(self):
bottleneck = self.get_object()
return ContentFile(bottleneck.get_bottleneck_matrix(), name=bottleneck.analysis.research.name + '_'
+ bottleneck.analysis.name + '_bottleneck_distance_consecutive_H' +
str(bottleneck.homology) + '.csv')
def AnalysisBottleneckCreateView(request, research_slug, analysis_slug):
research = get_object_or_404(Research, slug=research_slug)
analysis = get_object_or_404(FiltrationAnalysis, research=research, slug=analysis_slug)
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = AnalysisBottleneckCreationForm(analysis.max_homology_dimension, request.POST)
# check whether it's valid:
if form.is_valid():
cleaned_data = form.cleaned_data
bottleneck_type = cleaned_data.get("bottleneck_type")
homology = cleaned_data.get("homology")
if bottleneck_type == Bottleneck.CONS:
return redirect('analysis:analysis-bottleneck-consecutive', homology=homology,
analysis_slug=analysis.slug, research_slug=research.slug)
elif bottleneck_type == Bottleneck.ALL:
return redirect('analysis:analysis-bottleneck-alltoall', homology=homology,
analysis_slug=analysis.slug, research_slug=research.slug)
# if a GET (or any other method) we'll create a blank form
else:
form = AnalysisBottleneckCreationForm(analysis.max_homology_dimension)
return render(request, 'analysis/analysis_bottleneck_form.html',
{'form': form, 'research': research, 'analysis': analysis})
def WindowBottleneckCreateView(request, research_slug, analysis_slug, window_slug):
research = get_object_or_404(Research, slug=research_slug)
analysis = get_object_or_404(FiltrationAnalysis, research=research, slug=analysis_slug)
window = get_object_or_404(FiltrationWindow, analysis=analysis, slug=window_slug)
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = WindowBottleneckCreationForm(analysis.max_homology_dimension, request.POST)
# check whether it's valid:
if form.is_valid():
cleaned_data = form.cleaned_data
homology = cleaned_data.get("homology")
return redirect('analysis:window-bottleneck-onetoall', homology=homology,
window_slug=window.slug,
analysis_slug=analysis.slug, research_slug=research.slug)
# if a GET (or any other method) we'll create a blank form
else:
form = WindowBottleneckCreationForm(analysis.max_homology_dimension)
return render(request, 'analysis/window/window_bottleneck_form.html',
{'form': form, 'research': research, 'analysis': analysis, 'window': window})
class ALLBottleneckDeleteView(DeleteView):
model = Bottleneck
context_object_name = 'bottleneck'
template_name = "analysis/bottleneck_confirm_delete_ALL.html"
def get_object(self):
my_analysis = get_object_or_404(
FiltrationAnalysis,
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
)
return get_object_or_404(
Bottleneck,
analysis=my_analysis,
homology=self.kwargs['homology'],
kind=Bottleneck.ALL
)
def get_success_url(self):
return reverse_lazy('analysis:analysis-detail', kwargs={
'research_slug': self.kwargs['research_slug'],
'analysis_slug': self.kwargs['analysis_slug']
})
class CONSBottleneckDeleteView(DeleteView):
model = Bottleneck
context_object_name = 'bottleneck'
template_name = "analysis/bottleneck_confirm_delete_CONS.html"
def get_object(self):
my_analysis = get_object_or_404(
FiltrationAnalysis,
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
)
return get_object_or_404(
Bottleneck,
analysis=my_analysis,
homology=self.kwargs['homology'],
kind=Bottleneck.CONS
)
def get_success_url(self):
return reverse_lazy('analysis:analysis-detail', kwargs={
'research_slug': self.kwargs['research_slug'],
'analysis_slug': self.kwargs['analysis_slug']
})
class ONEBottleneckDeleteView(DeleteView):
model = Bottleneck
context_object_name = 'bottleneck'
template_name = "analysis/window/bottleneck_confirm_delete_ONE.html"
def get_object(self):
my_analysis = get_object_or_404(
FiltrationAnalysis,
research__slug=self.kwargs['research_slug'],
slug=self.kwargs['analysis_slug']
)
my_window = get_object_or_404(
FiltrationWindow,
analysis=my_analysis,
slug=self.kwargs['window_slug']
)
return get_object_or_404(
Bottleneck,
window=my_window,
homology=self.kwargs['homology'],
kind=Bottleneck.ONE
)
def get_success_url(self):
return reverse_lazy('analysis:window-detail', kwargs={
'research_slug': self.kwargs['research_slug'],
'analysis_slug': self.kwargs['analysis_slug'],
'window_slug': self.kwargs['window_slug']
})
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/conftest.py | import pytest
from django.conf import settings
from django.test import RequestFactory
from hansberger.users.tests.factories import UserFactory
@pytest.fixture(autouse=True)
def media_storage(settings, tmpdir):
settings.MEDIA_ROOT = tmpdir.strpath
@pytest.fixture
def user() -> settings.AUTH_USER_MODEL:
return UserFactory()
@pytest.fixture
def request_factory() -> RequestFactory:
return RequestFactory()
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/contrib/__init__.py | """
To understand why this file is here, please read:
http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/contrib/sites/__init__.py | """
To understand why this file is here, please read:
http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/contrib/sites/migrations/0001_initial.py | import django.contrib.sites.models
from django.contrib.sites.models import _simple_domain_name_validator
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="Site",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"domain",
models.CharField(
max_length=100,
verbose_name="domain name",
validators=[_simple_domain_name_validator],
),
),
("name", models.CharField(max_length=50, verbose_name="display name")),
],
options={
"ordering": ("domain",),
"db_table": "django_site",
"verbose_name": "site",
"verbose_name_plural": "sites",
},
bases=(models.Model,),
managers=[("objects", django.contrib.sites.models.SiteManager())],
)
]
| [] | [] | [] |
archives/097475_hansberger.zip | hansberger/contrib/sites/migrations/0002_alter_domain_unique.py | import django.contrib.sites.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("sites", "0001_initial")]
operations = [
migrations.AlterField(
model_name="site",
name="domain",
field=models.CharField(
max_length=100,
unique=True,
validators=[django.contrib.sites.models._simple_domain_name_validator],
verbose_name="domain name",
),
)
]
| [] | [] | [] |
ManyTypes4Py-Reconstructed
This is a reconstruction of the original code from the ManyTypes4Py paper from the following paper
A. M. Mir, E. Latoškinas and G. Gousios, "ManyTypes4Py: A Benchmark Python Dataset for Machine Learning-based Type Inference," IEEE/ACM International Conference on Mining Software Repositories (MSR), 2021, pp. 585-589
The artifact (v0.7) for ManyTypes4Py does not have the original Python files. Instead, each file is pre-processed into a stream of types without comments, and the contents of each repository are stored in a single JSON file. This reconstructed dataset has raw Python code.
More specifically:
We extract the list of repositories from the "clean" subset of ManyTypes4Py, which are the repositories that type-check with mypy.
We attempt to download all repositories, but only succeed in fetching 4,663 (out of ~5.2K).
We augment each file with the text of each type annotation, as well as their start and end positions (in bytes) in the code.
Internal Note
The dataset construction code is on the Discovery cluster at /work/arjunguha-research-group/arjun/projects/ManyTypesForPy_reconstruction
.
- Downloads last month
- 59