index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
51,233 | pavansai018/E-Learning-Portal | refs/heads/master | /educationPortal/migrations/0037_auto_20210801_0841.py | # Generated by Django 3.2.5 on 2021-08-01 12:41
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('educationPortal', '0036_auto_20210731_2146'),
]
operations = [
migrations.AddField(
model_name='assignment',
name='title',
field=models.CharField(default='', max_length=500),
),
migrations.AlterField(
model_name='announcement',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 8, 1, 8, 41, 7, 841382)),
),
migrations.AlterField(
model_name='comment',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 8, 1, 8, 41, 7, 837388)),
),
migrations.AlterField(
model_name='text',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 8, 1, 8, 41, 7, 841382)),
),
]
| {"/educationPortal/views.py": ["/educationPortal/models.py"]} |
51,234 | pavansai018/E-Learning-Portal | refs/heads/master | /educationPortal/migrations/0020_alter_announcement_body.py | # Generated by Django 3.2.5 on 2021-07-29 18:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('educationPortal', '0019_auto_20210729_1134'),
]
operations = [
migrations.AlterField(
model_name='announcement',
name='body',
field=models.CharField(default='', max_length=10000),
),
]
| {"/educationPortal/views.py": ["/educationPortal/models.py"]} |
51,235 | pavansai018/E-Learning-Portal | refs/heads/master | /educationPortal/migrations/0038_auto_20210801_1229.py | # Generated by Django 3.2.5 on 2021-08-01 16:29
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('educationPortal', '0037_auto_20210801_0841'),
]
operations = [
migrations.AddField(
model_name='assignment',
name='givenFiles',
field=models.ManyToManyField(blank=True, to='educationPortal.FileModel'),
),
migrations.AlterField(
model_name='announcement',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 8, 1, 12, 29, 55, 536441)),
),
migrations.AlterField(
model_name='comment',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 8, 1, 12, 29, 55, 535444)),
),
migrations.AlterField(
model_name='text',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 8, 1, 12, 29, 55, 536441)),
),
]
| {"/educationPortal/views.py": ["/educationPortal/models.py"]} |
51,236 | pavansai018/E-Learning-Portal | refs/heads/master | /educationPortal/migrations/0026_conversation_lastinteracted.py | # Generated by Django 3.2.5 on 2021-07-31 01:33
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('educationPortal', '0025_auto_20210730_1745'),
]
operations = [
migrations.AddField(
model_name='conversation',
name='lastInteracted',
field=models.DateField(default=django.utils.timezone.now),
),
]
| {"/educationPortal/views.py": ["/educationPortal/models.py"]} |
51,237 | pavansai018/E-Learning-Portal | refs/heads/master | /educationPortal/models.py | from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models.fields import CharField
from django.db.models.fields.files import FileField, ImageField
from django.utils.timezone import localtime, now
from datetime import datetime
import time
import os
class User(AbstractUser):
userType = models.CharField(max_length=20, default="student")
profile_pic = models.ImageField(
null=True, blank=True, default="blankUserIcon.svg")
class Classroom(models.Model):
name = models.CharField(max_length=100, default="Classroom")
students = models.ManyToManyField(User, blank=True)
teacher = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="teacher")
code = models.CharField(max_length=20)
subject = models.CharField(max_length=50, default="")
theme = models.CharField(max_length=20, default="cardBlue")
class Comment(models.Model):
date = models.DateTimeField(default=datetime.now())
text = CharField(max_length=5000, default="")
commenter = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="commenter", null=True)
class Announcement(models.Model):
classroom = models.ForeignKey(
Classroom, on_delete=models.CASCADE, related_name="classroom", null=True)
body = CharField(max_length=20000, default="")
creator = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="creator", null=True)
date = models.DateTimeField(default=datetime.now())
comments = models.ManyToManyField(Comment, blank=True)
class Text(models.Model):
sender = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="sender")
reciever = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="reciever")
date = models.DateTimeField(default=datetime.now())
text = CharField(max_length=1000, default="")
class Conversation(models.Model):
user1 = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="user1")
user2 = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="user2")
texts = models.ManyToManyField(Text, blank=True)
lastInteracted = models.FloatField()
class FileModel(models.Model):
file = models.FileField(blank=True)
def name(self):
return os.path.basename(self.file.name)
class Submission(models.Model):
resubmitted = models.BooleanField(default=False)
grade = models.IntegerField(default=-1)
files = models.ManyToManyField(FileModel, blank=True)
description = models.CharField(max_length=1000, default="")
user = models.ForeignKey(
User, null=True, related_name="submitter", on_delete=models.CASCADE)
date = models.DateField(default=datetime.now())
class Assignment(models.Model):
givenFiles = models.ManyToManyField(FileModel, blank=True)
title = models.CharField(max_length=500, default="")
description = models.CharField(max_length=20000, default="")
duedate = models.DateTimeField()
submissions = models.ManyToManyField(Submission, blank=True)
classroom = models.ForeignKey(
Classroom, on_delete=models.CASCADE, related_name="belongingToClassroom", null=True)
class MCanswer(models.Model):
answer = models.IntegerField(default=-1)
class MultipleChoiceQuestion(models.Model):
question = models.CharField(max_length=1000)
option1 = models.CharField(max_length=1000)
option2 = models.CharField(max_length=1000)
option3 = models.CharField(max_length=1000)
option4 = models.CharField(max_length=1000)
correctOption = models.IntegerField(default=1)
selectedOption = models.IntegerField(default=-1)
class QuizSubmission(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
date = models.DateField(default=datetime.now())
grade = models.IntegerField(default=0)
answers = models.ManyToManyField(MCanswer, blank=True)
class Quiz(models.Model):
name = models.CharField(max_length=1000, default="Untitled Quiz")
submissions = models.ManyToManyField(QuizSubmission, blank=True)
questions = models.ManyToManyField(MultipleChoiceQuestion, blank=True)
duedate = models.DateTimeField(null=True)
classroom = models.ForeignKey(
Classroom, null=True, on_delete=models.CASCADE)
| {"/educationPortal/views.py": ["/educationPortal/models.py"]} |
51,238 | pavansai018/E-Learning-Portal | refs/heads/master | /educationPortal/migrations/0005_auto_20210728_1025.py | # Generated by Django 3.2.5 on 2021-07-28 14:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('educationPortal', '0004_classroom'),
]
operations = [
migrations.AddField(
model_name='classroom',
name='subject',
field=models.CharField(default='', max_length=50),
),
migrations.AddField(
model_name='classroom',
name='theme',
field=models.CharField(default='cardBlue', max_length=20),
),
]
| {"/educationPortal/views.py": ["/educationPortal/models.py"]} |
51,239 | pavansai018/E-Learning-Portal | refs/heads/master | /educationPortal/migrations/0006_announcement.py | # Generated by Django 3.2.5 on 2021-07-29 15:07
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('educationPortal', '0005_auto_20210728_1025'),
]
operations = [
migrations.CreateModel(
name='Announcement',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateTimeField(default=datetime.datetime(2021, 7, 29, 15, 7, 11, 734355, tzinfo=utc))),
],
),
]
| {"/educationPortal/views.py": ["/educationPortal/models.py"]} |
51,240 | pavansai018/E-Learning-Portal | refs/heads/master | /educationPortal/migrations/0043_auto_20210801_1936.py | # Generated by Django 3.2.5 on 2021-08-01 23:36
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('educationPortal', '0042_auto_20210801_1754'),
]
operations = [
migrations.AddField(
model_name='submission',
name='date',
field=models.DateField(default=datetime.datetime(2021, 8, 1, 19, 36, 55, 924351)),
),
migrations.AlterField(
model_name='announcement',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 8, 1, 19, 36, 55, 920388)),
),
migrations.AlterField(
model_name='comment',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 8, 1, 19, 36, 55, 920388)),
),
migrations.AlterField(
model_name='text',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 8, 1, 19, 36, 55, 921386)),
),
]
| {"/educationPortal/views.py": ["/educationPortal/models.py"]} |
51,241 | pavansai018/E-Learning-Portal | refs/heads/master | /educationPortal/migrations/0023_alter_user_profile_pic.py | # Generated by Django 3.2.5 on 2021-07-30 01:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('educationPortal', '0022_user_profile_pic'),
]
operations = [
migrations.AlterField(
model_name='user',
name='profile_pic',
field=models.ImageField(blank=True, default='userImages/blankUserIcon.svg', null=True, upload_to='userImages/'),
),
]
| {"/educationPortal/views.py": ["/educationPortal/models.py"]} |
51,242 | pavansai018/E-Learning-Portal | refs/heads/master | /educationPortal/migrations/0042_auto_20210801_1754.py | # Generated by Django 3.2.5 on 2021-08-01 21:54
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('educationPortal', '0041_auto_20210801_1719'),
]
operations = [
migrations.AlterField(
model_name='announcement',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 8, 1, 17, 54, 47, 166350)),
),
migrations.AlterField(
model_name='comment',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 8, 1, 17, 54, 47, 166350)),
),
migrations.AlterField(
model_name='text',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 8, 1, 17, 54, 47, 166350)),
),
]
| {"/educationPortal/views.py": ["/educationPortal/models.py"]} |
51,243 | pavansai018/E-Learning-Portal | refs/heads/master | /educationPortal/migrations/0004_classroom.py | # Generated by Django 3.2.5 on 2021-07-28 01:28
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('educationPortal', '0003_auto_20210725_1530'),
]
operations = [
migrations.CreateModel(
name='Classroom',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(default='Classroom', max_length=100)),
('code', models.CharField(max_length=20)),
('students', models.ManyToManyField(blank=True, to=settings.AUTH_USER_MODEL)),
('teacher', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='teacher', to=settings.AUTH_USER_MODEL)),
],
),
]
| {"/educationPortal/views.py": ["/educationPortal/models.py"]} |
51,244 | pavansai018/E-Learning-Portal | refs/heads/master | /educationPortal/migrations/0034_auto_20210731_2144.py | # Generated by Django 3.2.5 on 2021-08-01 01:44
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('educationPortal', '0033_auto_20210731_2144'),
]
operations = [
migrations.AlterField(
model_name='announcement',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 7, 31, 21, 44, 35, 768444)),
),
migrations.AlterField(
model_name='comment',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 7, 31, 21, 44, 35, 768444)),
),
migrations.AlterField(
model_name='text',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 7, 31, 21, 44, 35, 769441)),
),
]
| {"/educationPortal/views.py": ["/educationPortal/models.py"]} |
51,250 | frhrdr/patepy | refs/heads/master | /test_application/validation_experiments.py | import numpy as np
from pate_accountant import PATEPyTorch
# load vote files provided by the paper and use the stated hyperparameters.
# repeatedly let the conident gnmax algorithm answer random queries from the dataset up to the limit given in the paper.
# If the implementation is correct, the final data-dependent eps should match the values given in the paper.
def dataset_validation(patepy, dataset_name, custom_beta, n_to_answer, verbose=True):
votes = np.load("pate2018_test_data/{}.npy".format(dataset_name))
n_votes = votes.shape[0]
votes = votes[np.random.permutation(n_votes)]
assert np.sum(votes[0, :]) == patepy.n_teachers
n_answered = 0
n_unchanged = 0
for idx in range(n_votes):
votes_i = votes[idx, :]
ret_val = patepy.gn_max(votes_i, preds=None)
if ret_val is not None:
n_answered += 1
if ret_val == np.argmax(votes_i):
n_unchanged += 1
if n_answered >= n_to_answer:
if verbose:
print('got {} queries. answered {}. {} answers transmitted correctly'.format(idx+1, n_answered, n_unchanged))
break
data_dependent_rdp_eps, order = patepy._data_dependent_dp(rdp=True)
data_dependent_ddp_eps, delta = patepy._data_dependent_dp(rdp=False)
results = patepy.release_epsilon_fixed_order(custom_beta, analysis=True, verbose=verbose)
rdp_sample, rdp_mean, rdp_sdev, gnss_rdp, ddp_sample, ddp_mean = results
if verbose:
print('data-depentent-analysis: ({}, {})-RDP & ({}, {})-delta-DP'.format(data_dependent_rdp_eps[0, 0], order,
data_dependent_ddp_eps, delta))
print('GNSS mechanism alone: ({}, {})-RDP'.format(gnss_rdp, order))
print('GNSS distribution: mean={}, sdev={}, random draw={}'.format(rdp_mean[0, 0], rdp_sdev, rdp_sample[0, 0]))
print('total epsilon in eps-delta-DP mean={}, random draw={}'.format(ddp_mean[0, 0], ddp_sample[0, 0]))
return ddp_mean, ddp_sample, data_dependent_ddp_eps
def mnist_validation():
patepy = PATEPyTorch(target_delta=1e-5,
sigma_votes=40.,
n_teachers=250,
sigma_eps_release=6.23,
threshold_mode='confident',
threshold_t=200.,
threshold_gamma=None,
sigma_thresh=150.,
order_specs=[14.])
return dataset_validation(patepy, 'mnist_250_teachers', custom_beta=0.0329, n_to_answer=286, verbose=True)
def svhn_validation():
patepy = PATEPyTorch(target_delta=1e-6,
sigma_votes=40.,
n_teachers=250,
sigma_eps_release=4.88,
threshold_mode='confident',
threshold_t=300.,
threshold_gamma=None,
sigma_thresh=200.,
order_specs=[7.5])
return dataset_validation(patepy, 'svhn_250_teachers', custom_beta=0.0533, n_to_answer=3098, verbose=True)
def glyph_validation(n_to_answer=10762):
if n_to_answer > 1000:
print('caution! this will take a while...')
patepy = PATEPyTorch(target_delta=1e-8,
sigma_votes=100.,
n_teachers=5000,
sigma_eps_release=11.9,
threshold_mode='confident',
threshold_t=1000.,
threshold_gamma=None,
sigma_thresh=500.,
order_specs=[20.5])
return dataset_validation(patepy, 'glyph_5000_teachers', custom_beta=0.0205, n_to_answer=n_to_answer, verbose=True)
if __name__ == '__main__':
mnist_validation()
# svhn_validation()
# glyph_validation()
| {"/test_application/validation_experiments.py": ["/pate_accountant.py"], "/pate_accountant.py": ["/aliases.py"], "/aliases.py": ["/pate_core.py"]} |
51,251 | frhrdr/patepy | refs/heads/master | /pate_accountant.py | import numpy as np
from aliases import get_log_q, rdp_max_vote, rdp_threshold, rdp_to_dp, \
local_sensitivity, local_to_smooth_sens, rdp_eps_release
class PATEPyTorch:
"""
This implementation is per sample. Minibatched version coming later...
class is meant to guide training of an arbitrary student model in the PATE framework. Its tasks are:
currently, everything is based on numpy
- track privacy loss during training
- determine, which teacher responses are used for training following GNMax, GN-conf, GN-int or a mix of the latter two
(- terminate training when a predetermined privacy budget is exhausted) useful budget definition is hard to define
- log training details
"""
def __init__(self, target_delta, sigma_votes, n_teachers, sigma_eps_release,
threshold_mode='basic', threshold_t=None, threshold_gamma=None, sigma_thresh=None,
order_specs=None):
super(PATEPyTorch, self).__init__()
self.n_teachers = n_teachers
self.orders = self._get_orders(order_specs)
self.target_delta = target_delta
self.sigma_votes = sigma_votes
self.sigma_thresh = sigma_thresh
self.sigma_eps_release = sigma_eps_release
self.threshold_mode = None
self.basic_mode = 0
self.confident_mode = 1
self.interactive_mode = 2
self.threshold_mode = self._get_threshold_mode(threshold_mode)
self.threshold_T = threshold_t
self.threshold_gamma = threshold_gamma
self.rdp_eps_by_order = np.zeros(len(self.orders)) # stores the data-dependent privacy loss
self.votes_log = [] # stores votes and whether the threshold was passsed for smooth sensitivity analysis
self.selected_order = None
self.data_dependent_ddp_eps = None
self.data_dependent_rdp_eps = None
@staticmethod
def _get_orders(specs):
if specs in ('short', 'shortlist', None):
return np.round(np.concatenate((np.arange(2, 50 + 1, 1), np.logspace(np.log10(50), np.log10(1000), num=20))))
elif specs in ('long', 'longlist'):
return np.concatenate((np.arange(2, 100 + 1, .5), np.logspace(np.log10(100), np.log10(500), num=100)))
elif isinstance(specs, list):
return np.asarray(specs)
else:
raise ValueError
def _get_threshold_mode(self, threshold_mode):
modes = {'basic': self.basic_mode, 'confident': self.confident_mode, 'interactive': self.interactive_mode}
assert threshold_mode in modes
return modes[threshold_mode]
def _add_rdp_loss(self, votes, sigma, thresh=False):
"""
calculates privacy loss from votes and the sigma that was used to perturb them
:param votes:
:param sigma:
:param thresh:
:return:
"""
if thresh:
self.rdp_eps_by_order += rdp_threshold(sigma, self.orders, self.threshold_T, votes)
else:
self.rdp_eps_by_order += rdp_max_vote(sigma, self.orders, get_log_q(votes, sigma))
def gn_max(self, votes, preds):
"""
depending on threshold_mode, return index of noisy teacher consensus, confident student label or None
:param votes: teacher votes
:param preds: student predictions (vector of class probabilities)
:return:
"""
release_votes = False
data_intependent_ret = None
thresh_votes = votes
# thresholding based on mode
if self.threshold_mode == self.basic_mode:
release_votes = True
elif self.threshold_mode == self.confident_mode:
self._add_rdp_loss(votes, self.sigma_thresh, thresh=True)
if np.max(votes) + np.random.normal(0., self.sigma_thresh) >= self.threshold_T:
release_votes = True
elif self.threshold_mode == self.interactive_mode:
thresh_votes = votes - self.n_teachers * preds
self._add_rdp_loss(thresh_votes, self.sigma_thresh, thresh=True)
if np.max(thresh_votes) + np.random.normal(0., self.sigma_thresh) >= self.threshold_T:
release_votes = True
elif np.max(preds) > self.threshold_gamma:
data_intependent_ret = np.argmax(preds)
self.votes_log.append((votes, thresh_votes, release_votes))
# release max vote if threshold is passed
if release_votes:
self._add_rdp_loss(votes, self.sigma_votes, thresh=False)
return np.argmax(votes + np.random.normal(np.ones_like(votes), self.sigma_votes))
else:
return data_intependent_ret
def gn_max_batched(self, votes, preds):
"""
cuts batch of votes and preds into samples and computes rdp_max_vote individually, then aggregates the results.
Filters out none values
more efficient version requires deeper changes and will be added later.
:param votes: tensor of teacher votes (bs, n_labels)
:param preds: student predictions (bs, n_labels)
:return:
"""
bs_range = list(range(votes.size()[0]))
ret_vals = [self.gn_max(votes[idx], preds[idx]) for idx in bs_range]
indices = [idx for idx in bs_range if ret_vals[idx] is not None]
released_vals = ret_vals[indices]
return released_vals, indices
def _data_dependent_dp(self, rdp=True):
"""
computes and saves the data-dependent epsilon
:return:
"""
if self.data_dependent_ddp_eps is None:
eps, order = rdp_to_dp(self.orders, self.rdp_eps_by_order, self.target_delta)
self.selected_order = order
self.data_dependent_ddp_eps = eps
self.data_dependent_rdp_eps = self.rdp_eps_by_order[np.argwhere(self.orders == order)]
if rdp:
return self.data_dependent_rdp_eps, self.selected_order
else:
return self.data_dependent_ddp_eps, self.target_delta
def release_epsilon_fixed_order(self, custom_beta=None, analysis=False, verbose=False):
"""
goes through the votes_log and computes the smooth sensitivity of the data-dependent epsilon
depends on the chosen threshold mode.
As in the Papernot script (smooth_sensitivity_table.py), the best order from the data-dependent RDP cycle is used.
searching over orders in both this and the data-dependent privacy analysis is very costly,
but may be implemented in a separate function later on.
:return: parameters of the private epsilon distribution along with a sinlge draw for release.
"""
data_dependent_rdp_eps, order = self._data_dependent_dp(rdp=True)
ls_by_dist_acc = np.zeros(self.n_teachers)
if verbose:
print('accounting ls of votes:')
for idx, (votes, thresh_votes, released) in enumerate(self.votes_log):
if self.threshold_mode is not self.basic_mode:
ls_by_dist_acc += local_sensitivity(thresh_votes, self.n_teachers, self.sigma_thresh, order, self.threshold_T)
if released:
ls_by_dist_acc += local_sensitivity(votes, self.n_teachers, self.sigma_votes, order)
if verbose and idx % (len(self.votes_log) // 10) == 0 and idx > 0:
print('{}%'.format(idx/len(self.votes_log)))
beta = 0.4 / self.selected_order if custom_beta is None else custom_beta # default recommended in the paper
smooth_s = local_to_smooth_sens(beta, ls_by_dist_acc)
eps_release_rdp = rdp_eps_release(beta, self.sigma_eps_release, order)
release_rdp_mean = data_dependent_rdp_eps + eps_release_rdp
release_rdp_sdev = smooth_s * self.sigma_eps_release
release_rdp_sample = np.random.normal(release_rdp_mean, release_rdp_sdev)
delta_dp_sample, _ = rdp_to_dp([self.selected_order], [release_rdp_sample], self.target_delta)
delta_dp_mean, _ = rdp_to_dp([self.selected_order], [release_rdp_mean], self.target_delta)
if not analysis:
return release_rdp_sample, delta_dp_sample
else:
return release_rdp_sample, release_rdp_mean, release_rdp_sdev, eps_release_rdp, delta_dp_sample, delta_dp_mean
| {"/test_application/validation_experiments.py": ["/pate_accountant.py"], "/pate_accountant.py": ["/aliases.py"], "/aliases.py": ["/pate_core.py"]} |
51,252 | frhrdr/patepy | refs/heads/master | /aliases.py | from pate_core import compute_logq_gaussian, rdp_data_independent_gaussian, rdp_gaussian, _log1mexp, \
compute_eps_from_delta, compute_logpr_answered
from smooth_sensitivity import compute_local_sensitivity_bounds_gnmax, compute_local_sensitivity_bounds_threshold, \
compute_rdp_of_smooth_sensitivity_gaussian, compute_discounted_max
# define aliases of functions from pate_core and smooth_sensitivity in order to simplify things a little bit.
def get_log_q(votes, sigma):
"""
:param votes:
:param sigma:
:return:
"""
return compute_logq_gaussian(votes, sigma)
def rdp_max_vote(sigma, orders, log_q=None):
"""
:param sigma:
:param orders:
:param log_q:
:return:
"""
if log_q is None:
return rdp_data_independent_gaussian(sigma, orders)
else:
return rdp_gaussian(log_q, sigma, orders)
def rdp_threshold(sigma, orders, threshold, votes):
"""
:param sigma:
:param orders:
:param threshold:
:param votes:
:return:
"""
log_pr_answered = compute_logpr_answered(threshold, sigma, votes)
logq = min(log_pr_answered, _log1mexp(log_pr_answered)) if log_pr_answered is not None else None
return rdp_max_vote(2**.5 * sigma, orders, logq) # sqrt(2) due to lower sensitivity
def rdp_to_dp(orders, rdp, delta):
"""
:param orders:
:param rdp:
:param delta:
:return:
"""
return compute_eps_from_delta(orders, rdp, delta)
def local_sensitivity(votes, num_teachers, sigma, order, thresh=None):
"""
:param votes:
:param num_teachers:
:param sigma:
:param order:
:param thresh:
:return:
"""
if thresh is not None:
return compute_local_sensitivity_bounds_threshold(votes, num_teachers, thresh, sigma, order)
else:
return compute_local_sensitivity_bounds_gnmax(votes, num_teachers, sigma, order)
def local_to_smooth_sens(beta, ls_by_dist):
"""
:param beta:
:param ls_by_dist:
:return:
"""
return compute_discounted_max(beta, ls_by_dist)
def rdp_eps_release(beta, sigma, order):
"""
:param beta:
:param sigma:
:param order:
:return:
"""
return compute_rdp_of_smooth_sensitivity_gaussian(beta, sigma, order)
| {"/test_application/validation_experiments.py": ["/pate_accountant.py"], "/pate_accountant.py": ["/aliases.py"], "/aliases.py": ["/pate_core.py"]} |
51,253 | frhrdr/patepy | refs/heads/master | /pate_core.py | # Copyright 2017 The 'Scalable Private Learning with PATE' Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Core functions for RDP analysis in PATE framework.
This library comprises the core functions for doing differentially private
analysis of the PATE architecture and its various Noisy Max and other
mechanisms.
"""
import math
import numpy as np
import scipy.stats
def _logaddexp(x):
"""Addition in the log space. Analogue of numpy.logaddexp for a list."""
m = max(x)
return m + math.log(sum(np.exp(x - m)))
def _log1mexp(x):
"""Numerically stable computation of log(1-exp(x))."""
if x < -1:
return math.log1p(-math.exp(x))
elif x < 0:
return math.log(-math.expm1(x))
elif x == 0:
return -np.inf
else:
raise ValueError("Argument must be non-positive.")
def compute_eps_from_delta(orders, rdp, delta):
"""Translates between RDP and (eps, delta)-DP.
Args:
orders: A list (or a scalar) of orders.
rdp: A list of RDP guarantees (of the same length as orders).
delta: Target delta.
Returns:
Pair of (eps, optimal_order).
Raises:
ValueError: If input is malformed.
"""
if len(orders) != len(rdp):
raise ValueError("Input lists must have the same length.")
eps = np.array(rdp) - math.log(delta) / (np.array(orders) - 1)
idx_opt = np.argmin(eps)
return eps[idx_opt], orders[idx_opt]
#####################
# RDP FOR THE GNMAX #
#####################
def compute_logq_gaussian(counts, sigma):
"""Returns an upper bound on ln Pr[outcome != argmax] for GNMax. Implementation of Proposition 7.
Args:
counts: A numpy array of scores.
sigma: The standard deviation of the Gaussian noise in the GNMax mechanism.
Returns:
logq: Natural log of the probability that outcome is different from argmax.
"""
n = len(counts)
variance = sigma**2
idx_max = np.argmax(counts)
counts_normalized = counts[idx_max] - counts
counts_rest = counts_normalized[np.arange(n) != idx_max] # exclude one index
# Upper bound q via a union bound rather than a more precise calculation.
logq = _logaddexp(
scipy.stats.norm.logsf(counts_rest, scale=math.sqrt(2 * variance))) # sqrt(2) in scale * sqrt(2) in logsf = 2
return min(logq, math.log(1 - (1 / n))) # (n-1)/n is upper bound when distribution is uniform
def rdp_data_independent_gaussian(sigma, orders):
"""Computes a data-independent RDP curve for GNMax. Implementation of Proposition 8.
Args:
sigma: Standard deviation of Gaussian noise.
orders: An array_like list of Renyi orders.
Returns:
Upper bound on RPD for all orders. A scalar if orders is a scalar.
Raises:
ValueError: If the input is malformed.
"""
if sigma < 0 or np.any(orders <= 1): # not defined for alpha=1
raise ValueError("Inputs are malformed.")
variance = sigma**2
if np.isscalar(orders):
return orders / variance
else:
return np.atleast_1d(orders) / variance
def rdp_gaussian(logq, sigma, orders):
"""Bounds RDP from above of GNMax given an upper bound on q (Theorem 6).
Args:
logq: Natural logarithm of the probability of a non-argmax outcome.
sigma: Standard deviation of Gaussian noise.
orders: An array_like list of Renyi orders.
Returns:
Upper bound on RPD for all orders. A scalar if orders is a scalar.
Raises:
ValueError: If the input is malformed.
"""
if logq > 0 or sigma < 0 or np.any(orders <= 1): # not defined for alpha=1
raise ValueError("Inputs are malformed.")
if np.isneginf(logq): # If the mechanism's output is fixed, it has 0-DP.
if np.isscalar(orders):
return 0.
else:
return np.full_like(orders, 0., dtype=np.float)
variance = sigma**2
# Use two different higher orders: mu_hi1 and mu_hi2 computed according to
# Proposition 10.
mu_hi2 = math.sqrt(variance * -logq)
mu_hi1 = mu_hi2 + 1
orders_vec = np.atleast_1d(orders)
ret = orders_vec / variance # baseline: data-independent bound
# Filter out entries where data-dependent bound does not apply.
mask = np.logical_and(mu_hi1 > orders_vec, mu_hi2 > 1)
rdp_hi1 = mu_hi1 / variance
rdp_hi2 = mu_hi2 / variance
log_a2 = (mu_hi2 - 1) * rdp_hi2
# Make sure q is in the increasing wrt q range and A is positive.
comp_val = log_a2 - mu_hi2 * (math.log(1 + 1 / (mu_hi1 - 1)) + math.log(1 + 1 / (mu_hi2 - 1)))
if np.any(mask) and logq <= comp_val and -logq > rdp_hi2:
# Use log1p(x) = log(1 + x) to avoid catastrophic cancellations when x ~ 0.
log1q = _log1mexp(logq) # log1q = log(1-q)
log_a = (orders - 1) * (log1q - _log1mexp((logq + rdp_hi2) * (1 - 1 / mu_hi2)))
log_b = (orders - 1) * (rdp_hi1 - logq / (mu_hi1 - 1))
# Use logaddexp(x, y) = log(e^x + e^y) to avoid overflow for large x, y.
log_s = np.logaddexp(log1q + log_a, logq + log_b)
ret[mask] = np.minimum(ret, log_s / (orders - 1))[mask]
assert np.all(ret >= 0)
if np.isscalar(orders):
return ret.item()
else:
return ret
###################################
# RDP FOR THE THRESHOLD MECHANISM #
###################################
def compute_logpr_answered(t, sigma, counts):
"""Computes log of the probability that a noisy threshold is crossed.
Args:
t: The threshold.
sigma: The stdev of the Gaussian noise added to the threshold.
counts: An array of votes.
Returns:
Natural log of the probability that max is larger than a noisy threshold.
"""
# Compared to the paper, max(counts) is rounded to the nearest integer. This
# is done to facilitate computation of smooth sensitivity for the case of
# the interactive mechanism, where votes are not necessarily integer.
return scipy.stats.norm.logsf(t - round(max(counts)), scale=sigma)
def compute_rdp_data_independent_threshold(sigma, orders):
# The input to the threshold mechanism has stability 1, compared to
# GNMax, which has stability = 2. Hence the sqrt(2) factor below.
return rdp_data_independent_gaussian(2**.5 * sigma, orders)
def compute_rdp_threshold(log_pr_answered, sigma, orders):
logq = min(log_pr_answered, _log1mexp(log_pr_answered))
# The input to the threshold mechanism has stability 1, compared to
# GNMax, which has stability = 2. Hence the sqrt(2) factor below.
return rdp_gaussian(logq, 2**.5 * sigma, orders)
| {"/test_application/validation_experiments.py": ["/pate_accountant.py"], "/pate_accountant.py": ["/aliases.py"], "/aliases.py": ["/pate_core.py"]} |
51,290 | antonnifo/iReporter | refs/heads/develop | /app/api/v1/redflags/views.py | """views for Red-flags"""
from flask import jsonify, make_response, request
from flask_restful import Resource
from .models import RedFlagModel
class RedFlags(Resource):
"""docstring for RedFlags class"""
def __init__(self):
"""initiliase the redflag class"""
self.db = RedFlagModel()
def post(self):
"""docstring for saving a redflag"""
redflag_id = self.db.save()
if redflag_id == "keyerror":
return make_response(jsonify({
"status": 500,
"error": "KeyError for createdBy Red-flag not posted"
}), 500)
return make_response(jsonify({
"status": 201,
"data": {
"id": redflag_id,
"message": "Created red-flag record"
}
}), 201)
def get(self):
"""docstring for getting all the redflags posted"""
self.db.get_all()
return make_response(jsonify({
"status": 200,
"data": self.db.get_all()
}), 200)
class RedFlag(Resource):
"""docstring of a single RedFlag"""
def __init__(self):
"""initiliase the Redflag class"""
self.db = RedFlagModel()
def get(self, redflag_id):
"""docstring for getting a specific red-flag"""
incident = self.db.find(redflag_id)
if incident == "red flag does not exit":
return make_response(jsonify({
"status": 404,
"error": "red flag does not exit"
}), 404)
return make_response(jsonify({
"status": 200,
"data": incident
}), 200)
def delete(self, redflag_id):
"""docstring for deleting a red-flag"""
incident = self.db.find(redflag_id)
if incident == "red flag does not exit":
return make_response(jsonify({
"status": 404,
"error": "red flag does not exit"
}), 404)
delete_status = self.db.delete(incident)
if delete_status == "deleted":
return make_response(jsonify({
"status": 200,
"data": 'red-flag record has been deleted'
}), 200)
def put(self, redflag_id):
"""docstring for updating redflag record"""
incident = self.db.find(redflag_id)
if incident == "red flag does not exit":
return make_response(jsonify({
"status": 404,
"error": "red flag does not exit"
}), 404)
edit_status = self.db.edit_redflag(incident)
if edit_status == "updated":
return make_response(jsonify({
"status": 200,
"data": {
"id": redflag_id,
"message": "Red-flag has been updated"
}
}))
class UpdateLocation(Resource):
"""class to update redflag location"""
def __init__(self):
self.db = RedFlagModel()
def patch(self, redflag_id):
"""method to update redflag location"""
incident = self.db.find(redflag_id)
if incident == "red flag does not exist":
return make_response(jsonify({
"status": 404,
"error": "Red-flag does not exist"
}), 404)
edit_status = self.db.edit_redflag_location(incident)
if edit_status == "keyerror":
return make_response(jsonify({
"status": 500,
"error": "KeyError Red-flag's location not updated"
}), 500)
elif edit_status == "updated":
return make_response(jsonify({
"status": 200,
"data": {
"id": redflag_id,
"message": "Updated red-flag record's location"
}
}), 200)
class UpdateComment(Resource):
"""docstring for patching comment"""
def __init__(self):
self.db = RedFlagModel()
def patch(self, redflag_id):
"""method to update comment in a redflag"""
incident = self.db.find(redflag_id)
if incident == "red flag does not exit":
return make_response(jsonify({
"status": 404,
"error": "red flag does not exit"
}), 404)
edit_status = self.db.edit_redflag_comment(incident)
if edit_status == "keyerror":
return make_response(jsonify({
"status": 500,
"error": "KeyError Red-flag's comment not updated"
}), 500)
elif edit_status == "updated":
return make_response(jsonify({
"status": 200,
"data": {
"id": redflag_id,
"message": "Updated red-flag record's comment"
}
}), 200)
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,291 | antonnifo/iReporter | refs/heads/develop | /app/db_con.py | '''driver for interacting with PostgreSQL from the Python scripting language'''
import os
import psycopg2 as p
import psycopg2.extras
from werkzeug.security import generate_password_hash
DATABASE_URL = os.getenv('DATABASE_URL')
DATABASE_URL_TEST = os.getenv('DATABASE_URL_TEST')
def connection(url):
con = p.connect(DATABASE_URL)
return con
def create_tables():
'''A database cursor is an object that points to a
place in the database where we want to create, read,
update, or delete data.'''
con = connection(DATABASE_URL)
curr = con.cursor()
queries = tables()
for query in queries:
curr.execute(query)
con.commit()
def destroy_tables():
con = connection(DATABASE_URL_TEST)
curr = con.cursor()
users = "DROP TABLE IF EXISTS users CASCADE"
incidents = "DROP TABLE IF EXISTS incidents CASCADE"
queries = [incidents, users]
try:
for query in queries:
curr.execute(query)
con.commit()
print('Destroying test tables...Done ')
except:
print("Failed to Destroy tables")
def tables():
tbl1 = """CREATE TABLE IF NOT EXISTS incidents (
incidents_id serial PRIMARY KEY NOT NULL,
createdOn TIMESTAMP,
type character (64) NOT NULL,
title character (64) NOT NULL,
location character(64) NOT NULL,
Images VARCHAR(500) NULL,
status character (64) NOT NULL,
comment character (1000) NOT NULL,
createdBy INT NOT NULL
)"""
tbl2 = """create table IF NOT EXISTS users (
user_id serial PRIMARY KEY NOT NULL,
first_name character(50) NOT NULL,
last_name character(50),
email varchar(50) NOT NULL UNIQUE,
phone varchar(11),
isAdmin boolean NOT NULL,
registered TIMESTAMP,
password varchar(500) NOT NULL
)"""
queries = [tbl1, tbl2]
return queries
def super_user():
password = generate_password_hash("hello123")
user_admin = {
"first_name": "john",
"last_name": "doe",
"email": "johndoe@example.com",
"phone": "0707741793",
"isAdmin": True,
"registered": "Thu, 13 Dec 2018 21:00:00 GMT",
"password": password
}
query = """INSERT INTO users (first_name,last_name,email,phone,password,isAdmin,registered) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}');""".format(
user_admin['first_name'], user_admin['last_name'], user_admin['email'], user_admin['phone'], user_admin['password'], user_admin['isAdmin'], user_admin['registered'])
conn = connection(DATABASE_URL)
cursor = conn.cursor()
try:
cursor.execute(query)
conn.commit()
print('super user created')
except:
return "user already exists"
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,292 | antonnifo/iReporter | refs/heads/develop | /run.py | """Run docstring"""
import os
from flask import jsonify, make_response
from app import create_app
APP = create_app(os.getenv("FLASK_CONF") or 'default')
@APP.errorhandler(404)
def page_not_found(e):
"""error handler default method for error 404"""
return make_response(
jsonify(
{"message": "Oops! not found, check you have "
"right url or correct input type", "status": 404}
), 404
)
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,293 | antonnifo/iReporter | refs/heads/develop | /app/api/v2/incidents/views_redflags.py | """Views for Redflags"""
from flask import jsonify, make_response, request
from flask_restful import Resource
from app.api.v2.users.models import UserModel
from ..validators import (can_only_edit_draft, non_existance_incident,
only_admin_can_edit, only_creater_can_delete,
only_creater_can_edit)
from .models import IncidentModel
from app.api.v2.token_decorator import require_token
class Redflags(Resource):
"""docstring for redflags class"""
def __init__(self):
"""initiliase the redflags class"""
self.db = IncidentModel()
@require_token
def post(current_user, self):
"""docstring for saving a red-flag"""
incident = self.db.save(
current_user['user_id'], incident_type='red-flag')
return jsonify({
"status": 201,
"data": incident,
"message": "Created red-flag record"
})
@require_token
def get(current_user, self):
"""docstring for getting all the red-flags posted by users"""
self.db.find_by_type(incident_type='red-flag')
return make_response(jsonify({
"status": 200,
"data": self.db.find_by_type(incident_type='red-flag')
}), 200)
class Redflag(Resource):
"""docstring of a single redflag incident"""
def __init__(self):
"""initiliase the redflag class"""
self.db = IncidentModel()
@require_token
def get(current_user, self, incident_id):
"""method for getting a specific redflag record"""
incident = self.db.find_by_id_type(
incident_id, incident_type='red-flag')
if incident == "incident does not exit":
return non_existance_incident()
return make_response(jsonify({
"status": 200,
"data": incident
}), 200)
@require_token
def delete(current_user, self, incident_id):
"""docstring for deleting a redf;ag"""
incident = self.db.find_by_id_type(
incident_id, incident_type='red-flag')
if incident == "incident does not exit":
return non_existance_incident()
if current_user["user_id"] != incident["createdby"]:
return only_creater_can_delete()
if self.db.delete(incident_id, incident_type='red-flag') == "deleted":
return jsonify({
"status": 200,
"message": 'incident record has been deleted'
})
class UpdateRedflagLocation(Resource):
"""class to update red-flag incident location"""
def __init__(self):
"""initiliase the update location class"""
self.db = IncidentModel()
@require_token
def patch(current_user, self, incident_id):
"""method to update a red-flag incidents location"""
edit_status = self.db.edit_incident_location(
current_user['user_id'], incident_id, incident_type='red-flag')
if edit_status is None:
return non_existance_incident()
if edit_status is False:
return only_creater_can_edit()
if edit_status == 'Not Draft':
return can_only_edit_draft()
if edit_status == "location updated":
return jsonify({
"status": 200,
"data": {
"id": incident_id,
"message": "Updated red-flag record's location"
}
})
class UpdateRedflagComment(Resource):
"""docstring for patching a redflag comment"""
def __init__(self):
self.db = IncidentModel()
@require_token
def patch(current_user, self, incident_id):
"""method to update comment in a red-flag incident"""
incident = self.db.find_by_id_type(
incident_id, incident_type='red-flag')
if incident == "incident does not exit":
return non_existance_incident()
if current_user["user_id"] != incident['createdby']:
return only_creater_can_edit()
edit_status = self.db.edit_incident_comment(
incident_id, incident_type='red-flag')
if edit_status == "you cant edit this":
return can_only_edit_draft()
if edit_status == "comment updated":
return jsonify({
"status": 200,
"data": {
"id": incident_id,
"message": "Updated incident record's comment"
}
})
class UpdateRedflagStatus(Resource):
"""docstring for patching status of a redflag"""
def __init__(self):
self.db = IncidentModel()
@require_token
def patch(current_user, self, incident_id):
"""method to update status in an incident"""
if current_user['isadmin'] is False:
return only_admin_can_edit()
edit_status = self.db.edit_incident_status(
incident_id, incident_type='red-flag')
if edit_status == None:
return non_existance_incident()
if edit_status == "status updated":
return jsonify({
"status": 200,
"data": {
"id": incident_id,
"message": "Updated Redflag's status"
}
})
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,294 | antonnifo/iReporter | refs/heads/develop | /app/api/v2/token_decorator.py | import datetime
import os
from functools import wraps
import jwt
from flask import jsonify, make_response, request
from app.api.v2.users.models import UserModel
secret = os.getenv('SECRET_KEY')
def require_token(f):
@wraps(f)
def secure(*args, ** kwargs):
token = None
if 'token' in request.headers:
token = request.headers['token']
if not token:
return make_response(jsonify({
"message": "Token is missing"
}), 401)
try:
data = jwt.decode(token, secret)
current_user = UserModel().find_user_by_email(data['email'])
except:
return make_response(jsonify({
"message": "Token is invalid"
}), 401)
return f(current_user, *args, **kwargs)
return secure
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,295 | antonnifo/iReporter | refs/heads/develop | /app/tests/v2/testing_data.py | from werkzeug.security import generate_password_hash
password = generate_password_hash("hello123")
test_user = {
"first_name": "john",
"last_name": "doe",
"email": "johndoe@example.com",
"phone": "0707741793",
"isAdmin": True,
"registered": "Thu, 13 Dec 2018 21:00:00 GMT",
"password": password
}
user = {
"first_name" : "John",
"last_name" : "Doe",
"email" : "john@doe.com",
"phone" :"0727426274",
"password" : "hello123",
"isAdmin" : False
}
user2 = {
"first_name" : "John",
"last_name" : "Doe",
"email" : "john@doe.com",
"phone" : "0727426274",
"password" : "hello123",
"isAdmin" : False
}
user3 = {
"first_name" : "anthony",
"last_name" : "mwas",
"email" : "anthony@mwas.com",
"phone" : "0727426274",
"password" : "hello123",
"isAdmin" : False
}
user4 = {
"first_name" : "anthony",
"last_name" : "mwas",
"email" : "anthony@mwas.com",
"phoneNumber" : "0727426274",
"password" : "hello123",
"isAdmin" : True
}
data5 = {
"email" : "john@doe.com",
"password" : "hello123"
}
data6 = {
"email" : "john@doe.com",
"password" : "hello1234"
}
data7 = {
"email" : "john123@doe.com",
"password" : "hello123"
}
redflag_data = {
"createdOn": "Tue, 27 Nov 2018 21:18:13 GMT",
"createdBy": 1,
"type": "redflag",
"location": "-90.000, -180.0000",
"status": "draft",
"images": "",
"title": "Mercury in sugar",
"comment": "Lorem ipsum dolor sit amet."
}
redflag_data2 = {
"createdOn": "Tue, 27 Nov 2018 21:18:13 GMT",
"createdByfhh": 2,
"type": "redflag",
"location": "-90, -180",
"status": "draft",
"images": "",
"title": "Mercury in sugar",
"comment": "Lorem ipsum dolor sit amet."
}
redflag_data3 = {
"createdOn": "Tue, 27 Nov 2018 21:18:13 GMT",
"type": "redflag",
"location": "-90, -180",
"status": "draft",
"images": "",
"comment": "Lorem ipsum dolor sit amet."
}
intervention_data = {
"createdBy": 1,
"type": "intervention",
"location": "66, 12",
"status": "draft",
"title": "NYS scandal",
"comment": "act soon",
"createdon": "Thu, 13 Dec 2018 14:31:20 GMT"
} | {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,296 | antonnifo/iReporter | refs/heads/develop | /app/api/v2/validators.py | """for fields validations purposes"""
import re
from flask import jsonify, request
from flask_restful import reqparse
def validate_integer(value):
"""method to check for only integers"""
if not re.match(r"^[0-9]+$", value):
raise ValueError("Pattern not matched")
def validate_coordinates(value):
"""method to check for valid coordinates"""
if not re.match(r"^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$", value):
raise ValueError("Pattern not matched")
def validate_string(value):
"""method to check that the field takes only letters"""
if not re.match(r"[A-Za-z1-9]+", value):
raise ValueError("Pattern not matched")
def validate_password(value):
"""method to check if password contains more than 8 characters"""
if not re.match(r"^[A-Za-z0-9!@#$%^&+*=]{8,}$", value):
raise ValueError("Password should be at least 8 characters")
def validate_email(value):
"""method to check for valid email"""
if not re.match(r"^[^@]+@[^@]+\.[^@]+$", value):
raise ValueError("write a proper Email")
parser = reqparse.RequestParser(bundle_errors=True)
parser_edit_location = reqparse.RequestParser(bundle_errors=True)
parser_edit_comment = reqparse.RequestParser(bundle_errors=True)
parser_edit_status = reqparse.RequestParser(bundle_errors=True)
parser.add_argument('location',
type=validate_coordinates,
required=True,
trim=True,
nullable=False,
help="This field cannot be left blank or improperly formated"
)
parser_edit_location.add_argument('location',
type=validate_coordinates,
required=True,
trim=True,
nullable=False,
help="This field cannot be left blank or improperly formated"
)
parser.add_argument('comment',
type=validate_string,
required=True,
trim=True,
nullable=False,
help="This field cannot be left blank or should be properly formated"
)
parser_edit_comment.add_argument('comment',
type=validate_string,
required=True,
trim=True,
nullable=False,
help="This field cannot be left blank or should be properly formated"
)
parser_edit_status.add_argument('status',
type=str,
required=True,
trim=True,
nullable=False,
choices=(
"resolved", "under investigation", "rejected"),
help="This field cannot be left blank or should only be resolved ,under investigation or rejected"
)
parser.add_argument('title',
type=validate_string,
required=True,
trim=True,
nullable=False,
help="This field cannot be left blank or should be properly formated"
)
def non_existance_incident():
'''return message for an incident that does not exist'''
return jsonify({
"status": 404,
"error": "incident does not exist"
})
def only_creater_can_edit():
'''return message for only creater of an incident can patch it'''
return jsonify({
"status": 401,
"error": "sorry you can't edit an incident you din't create"
})
def only_admin_can_edit():
'''return message for only an admin can change status of an incident'''
return jsonify({
"status": 403,
"message": "sorry Only an admin can change the status of an incident"
})
def only_creater_can_delete():
'''return message that only create of an incident can delete it'''
return jsonify({
"status": 401,
"error": "sorry you can't delete an incident you din't create"
})
def can_only_edit_draft():
'''return message that u can patch an incident only on its draft state'''
return jsonify({
"status": 401,
"error": "You can't edit this due to it's state"
})
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,297 | antonnifo/iReporter | refs/heads/develop | /app/tests/v1/test_redflags.py | """Tests for redflags run with pytest"""
import json
import unittest
from ... import create_app
class RedFlagTestCase(unittest.TestCase):
"""
This class represents the redflag test cases
"""
def setUp(self):
APP = create_app("testing")
self.app = APP.test_client()
self.redflag = {
"createdBy": 5,
"type": "red-flag",
"location": "66, 12",
"status": "resolved",
"images": "",
"videos": "",
"title": "NYS scandal",
"comment": "53"
}
def test_get_all_redflags(self):
"""method to test get all"""
response = self.app.get("/api/v1/red-flags")
self.assertEqual(response.status_code, 200)
def test_post_redflag(self):
response = self.app.post("/api/v1/red-flags", headers={'Content-Type': 'application/json'},
data=json.dumps(self.redflag))
result = json.loads(response.data)
self.assertEqual(response.status_code, 201)
self.assertIn('Created red-flag record', str(result))
def test_get_specific_redflag(self):
"""method to test if one can get a specific redflag"""
self.app.post("/api/v1/red-flags",
headers={'Content-Type': 'application/json'}, data=json.dumps(self.redflag))
response = self.app.get("/api/v1/red-flags/1")
json.loads(response.data)
self.assertEqual(response.status_code, 200)
def test_delete_specific_redflag(self):
"""method to test if one can delete a redflag"""
self.app.post("/api/v1/red-flags",
headers={'Content-Type': 'application/json'}, data=json.dumps(self.redflag))
response = self.app.delete("/api/v1/red-flags/1")
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertIn('red-flag record has been deleted', str(result))
def test_update_location_of_specific_redflag(self):
"""method to test edit of location"""
self.app.post("/api/v1/red-flags/1/location",
headers={'Content-Type': 'application/json'}, data=json.dumps(self.redflag))
response = self.app.patch("/api/v1/red-flags/1/location", headers={
'Content-Type': 'application/json'}, data=json.dumps({"location": "24.0 , 12.0"}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertIn("Updated red-flag record's location", str(result))
def test_update_comment_of_specific_redflag(self):
"""method to test edit of comment"""
self.app.post("/api/v1/red-flags/1/comment",
headers={'Content-Type': 'application/json'}, data=json.dumps(self.redflag))
response = self.app.patch("/api/v1/red-flags/1/comment", headers={'Content-Type': 'application/json'},
data=json.dumps({"comment": "hello cohart 35"}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertIn("Updated red-flag record's comment",
str(result))
def test_redflag_not_found(self):
"""Test a redflag not found"""
response = self.app.get("/api/v1/red-flags/100")
result = json.loads(response.data)
self.assertEqual(response.status_code, 404)
self.assertEqual(
result['error'], "red flag does not exit")
def test_wrong_comment_key(self):
"""Test wrong comment key used in redflag"""
response = self.app.patch("/api/v1/red-flags/1/comment", headers={'Content-Type': 'application/json'},
data=json.dumps({"comment1": "hello pac"}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 500)
self.assertEqual(
result['error'], "KeyError Red-flag's comment not updated")
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,298 | antonnifo/iReporter | refs/heads/develop | /app/api/v2/incidents/models.py | """Incidents Models"""
import datetime
from flask import request
from flask_restful import reqparse
from app.db_con import connection
from app.db_con import DATABASE_URL as url
import re
import psycopg2.extras
from ..validators import parser, parser_edit_location, parser_edit_comment, parser_edit_status
class IncidentModel:
"""Class with methods to perform CRUD operations on the DB"""
def __init__(self):
self.db = connection(url)
def save(self, user_id, incident_type):
parser.parse_args()
data = {
'createdOn': datetime.datetime.utcnow(),
'createdBy': user_id,
'type': incident_type,
'location': request.json.get('location'),
'status': "draft",
'title': request.json.get('title'),
'comment': request.json.get('comment')
}
query = """INSERT INTO incidents (createdon,createdby,type,location,status,title,comment) VALUES('{0}',{1},'{2}','{3}','{4}','{5}','{6}');""".format(
data['createdOn'], data['createdBy'], data['type'], data['location'], data['status'], data['title'], data['comment'])
con = self.db
cursor = con.cursor()
cursor.execute(query)
con.commit()
return data
def find_status(self, incident_id):
"""method to find status of an incident"""
query = """SELECT status from incidents WHERE incidents_id={0} """.format(
incident_id)
con = self.db
cursor = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cursor.execute(query)
status = cursor.fetchone()
if cursor.rowcount == 0:
return 'incident does not exit'
return status
def find_by_type(self, incident_type):
query = """SELECT * from incidents WHERE type='{0}'""".format(
incident_type)
conn = self.db
cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cursor.execute(query)
results = cursor.fetchall()
return results
def find_by_id_type(self, incident_id, incident_type):
query = """SELECT * from incidents WHERE incidents_id={0} AND type='{1}'""".format(
incident_id, incident_type)
conn = self.db
cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cursor.execute(query)
result = cursor.fetchone()
if cursor.rowcount == 0:
return 'incident does not exit'
return result
def find_all(self):
"""method to find all incidents"""
query = """SELECT * from incidents"""
conn = self.db
cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cursor.execute(query)
incidents = cursor.fetchall()
return incidents
def edit_incident_status(self, incident_id, incident_type):
"Method to edit an incident's status"
parser_edit_status.parse_args()
status = request.json.get('status')
if self.find_by_id_type(incident_id, incident_type) == "incident does not exit":
return None
query = """UPDATE incidents SET status='{0}' WHERE incidents_id={1}""".format(
status, incident_id)
con = self.db
cursor = con.cursor()
cursor.execute(query)
con.commit()
return 'status updated'
def edit_incident_location(self, current_user_id, incident_id, incident_type):
"Method to edit an incident's location"
parser_edit_location.parse_args()
location = request.json.get('location')
incident = self.find_by_id_type(incident_id, incident_type)
if incident == "incident does not exit":
return None
if current_user_id != incident['createdby']:
return False
status = self.find_status(incident_id)
if status != {'status': 'draft '}:
return 'you cant edit this'
query = """UPDATE incidents SET location='{0}' WHERE incidents_id={1}""".format(
location, incident_id)
con = self.db
cursor = con.cursor()
cursor.execute(query)
con.commit()
return 'location updated'
def edit_incident_comment(self, incident_id, incident_type):
"Method to edit an incident's comment"
parser_edit_comment.parse_args()
comment = request.json.get('comment')
incident = self.find_by_id_type(incident_id, incident_type)
if incident == "incident does not exit":
return None
status = self.find_status(incident_id)
if status != {'status': 'draft '}:
return 'you cant edit this'
query = """UPDATE incidents SET comment='{0}' WHERE incidents_id={1}""".format(
comment, incident_id)
con = self.db
cursor = con.cursor()
cursor.execute(query)
con.commit()
return 'comment updated'
def delete(self, incident_id, incident_type):
"Method to delete an incident record by id"
incident = self.find_by_id_type(incident_id, incident_type)
if incident is None:
return None
query = """DELETE FROM incidents WHERE incidents_id={0}""".format(
incident_id)
con = self.db
cursor = con.cursor()
cursor.execute(query)
con.commit()
return 'deleted'
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,299 | antonnifo/iReporter | refs/heads/develop | /app/tests/v2/test_users.py | """Tests for users run with pytest"""
import unittest
import json
import jwt
import datetime
import os
from ... import create_app
from app.db_con import create_tables, super_user, destroy_tables
from app.tests.v2.testing_data import (
test_user, user, user2, user3, user4,data5, data6, data7)
secret = os.getenv('SECRET_KEY')
class UserTestCase(unittest.TestCase):
"""Class for User testcase"""
def setUp(self):
"""set up method initialising resused variables"""
APP = create_app(config_name="testing")
APP.testing = True
self.app = APP.test_client()
create_tables()
super_user()
self.test_user = test_user
payload = {
"email": self.test_user['email'],
"exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
}
token = jwt.encode(
payload=payload, key=secret, algorithm='HS256')
self.headers = {'Content-Type': 'application/json',
'token': token
}
self.data = user
self.data2 = user2
self.data3 = user3
self.data4 = user4
self.data5 = data5
self.data6 = data6
self.data7 = data7
def test_user_signup(self):
"""Test user signup"""
response = self.app.post(
"/api/v2/auth/signup", headers={'Content-Type': 'application/json'}, data=json.dumps(self.data))
print(response)
json.loads(response.data)
self.assertEqual(response.status_code, 200)
def test_user_signin(self):
"""Test post a user signin"""
self.app.post("/api/v2/auth/signup", headers={'Content-Type': 'application/json'},
data=json.dumps(self.data))
response = self.app.post(
"/api/v2/auth/signin", headers={'Content-Type': 'application/json'}, data=json.dumps(self.data5))
json.loads(response.data)
self.assertEqual(response.status_code, 200)
def test_user_signin_wrong_password(self):
"""Test post a user signin"""
self.app.post("/api/v2/auth/signup", headers={'Content-Type': 'application/json'}, data=json.dumps(self.data))
response = self.app.post("/api/v2/auth/signin", headers=self.headers, data=json.dumps(self.data6))
result = json.loads(response.data)
print(result)
self.assertEqual(response.status_code, 200)
self.assertEqual(result['message'], 'password or email is incorrect please try again')
def test_duplicate_user_email(self):
"""Test signup a user with existing email"""
self.app.post("/api/v2/auth/signup", headers={'Content-Type': 'application/json'},
data=json.dumps(self.data))
response = self.app.post(
"/api/v2/auth/signup", headers={'Content-Type': 'application/json'}, data=json.dumps(self.data))
result = json.loads(response.data)
self.assertEqual(result['status'], 400)
self.assertEqual(result['error'], "email already exists")
def test_get_users(self):
"""Test to get all users"""
response = self.app.get(
"/api/v2/users", headers=self.headers)
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
def test_get_specific_user(self):
"""Test get a specific redflag"""
self.app.post("/api/v2/auth/signup",
headers={'Content-Type': 'application/json'}, data=json.dumps(self.data))
response = self.app.get(
"/api/v2/users/john@doe.com", headers=self.headers)
self.assertEqual(response.status_code, 200)
def test_nonexistent_user(self):
"""Test to check a user who does not exist"""
response = self.app.get("/api/v2/users/kama@gmail.com", headers=self.headers)
self.assertEqual(response.status_code, 200)
result = json.loads(response.data)
self.assertEqual(result['message'], 'user does not exist')
def test_delete_specific_user(self):
"""Test delete a specific redflag"""
self.app.post("/api/v2/auth/signup", headers=self.headers, data=json.dumps(self.data))
response = self.app.delete("/api/v2/users/john@doe.com", headers=self.headers)
self.assertEqual(response.status_code, 200)
def test_update_user_status(self):
"""Test to update user admin status"""
self.app.post("/api/v2/auth/signup", headers=self.headers, data=json.dumps(self.data))
response = self.app.patch("/api/v2/users/john@doe.com/status", headers=self.headers, data=json.dumps({"isadmin":"False"}))
self.assertEqual(response.status_code, 200)
def tearDown(self):
destroy_tables() | {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,300 | antonnifo/iReporter | refs/heads/develop | /app/api/v2/users/models.py | '''model for users view file'''
import datetime
import psycopg2.extras
from flask import request
from flask_restful import reqparse
from werkzeug.security import check_password_hash, generate_password_hash
from app.db_con import connection
from app.db_con import DATABASE_URL as url
from ..validators import validate_email, validate_string, validate_integer, validate_password
parser = reqparse.RequestParser(bundle_errors=True)
parser.add_argument('first_name',
type=validate_string,
required=True,
nullable=False,
trim=True,
help="This field cannot be left blank or should be properly formated"
)
parser.add_argument('last_name',
type=validate_string,
required=True,
nullable=False,
help="This field cannot be left blank or should be properly formated"
)
parser.add_argument('email',
type=validate_email,
required=True,
nullable=False,
trim=True,
help="This field cannot be left blank or should be properly formated"
)
parser.add_argument('phone',
type=validate_integer,
required=False,
trim=True,
nullable=True,
help="This field cannot be left blank or should be properly formated"
)
parser.add_argument('password',
type=validate_password,
required=True,
nullable=False,
help="This field cannot be left blank or should be properly formated and should contain atleast 8 characters"
)
class UserModel:
"""class for manipulating user data"""
def __init__(self):
self.registered = datetime.datetime.utcnow()
self.isAdmin = False
self.db = connection(url)
def set_pswd(self, password):
'''salting the passwords '''
return generate_password_hash(password)
def check_pswd(self, password):
return check_password_hash(self.pwdhash, password)
def save(self):
parser.parse_args()
data = {
'first_name': request.json.get('first_name'),
'last_name': request.json.get('last_name'),
'email': request.json.get('email'),
'phone': request.json.get('phone'),
'password': self.set_pswd(request.json.get('password')),
'isAdmin': self.isAdmin
}
user_by_email = self.find_user_by_email(data['email'])
if user_by_email != None:
return 'email already exists'
query = """INSERT INTO users (first_name,last_name,email,phone,password,isAdmin) VALUES('{0}','{1}','{2}','{3}','{4}','{5}');""".format(
data['first_name'], data['last_name'], data['email'], data['phone'], data['password'], data['isAdmin'])
con = self.db
cursor = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cursor.execute(query)
con.commit()
return data
def find_user_by_email(self, email):
"Method to find a user by email"
query = """SELECT * from users WHERE email='{0}'""".format(email)
con = self.db
cursor = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cursor.execute(query)
row = cursor.fetchone()
if cursor.rowcount == 0:
return None
return row
def log_in(self):
data = {
'email': request.json.get('email'),
'password': request.json.get('password')
}
user = self.find_user_by_email(data['email'])
if user == None:
return None
if check_password_hash(user['password'], data['password']) == False:
return 'incorrect password'
return user['email']
def find_users(self):
"""method to find all users"""
query = """SELECT * from users"""
con = self.db
cursor = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cursor.execute(query)
rows = cursor.fetchall()
return rows
def edit_user_status(self, email):
"""method to update a user to an admin user"""
isAdmin = request.json.get('isadmin')
query = """UPDATE users SET isadmin={0} WHERE email='{1}'""".format(
isAdmin, email)
con = self.db
cursor = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cursor.execute(query)
con.commit()
return True
def delete_user(self, email):
"""method to delete a user record"""
query = """DELETE FROM users WHERE email='{0}'""".format(email)
con = self.db
cursor = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cursor.execute(query)
con.commit()
return True
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,301 | antonnifo/iReporter | refs/heads/develop | /app/api/v1/redflags/models.py | """model for view for incidents"""
import datetime
from flask import jsonify, make_response, request
from flask_restful import Resource, reqparse
from app.api.v2.validators import (
validate_integer, validate_coordinates, validate_string)
parser = reqparse.RequestParser(bundle_errors=True)
parser.add_argument('createdBy',
type=validate_integer,
required=True,
help="Value Must be an Interger as it is an ID or cant be left blank"
)
parser.add_argument('location',
type=validate_coordinates,
required=True,
help="This field cannot be left blank or improperly formated"
)
parser.add_argument('type',
type=str,
required=True,
choices=("red-flag", "intervention"),
help="This field cannot be left "
"blank or Bad choice: {error_msg}"
)
parser.add_argument('status',
type=str,
required=True,
choices=("resolved", "under investigation", "rejected"),
help="This field cannot be left blank or should only be resolved ,under investigation or rejected"
)
parser.add_argument('images',
action='append',
help="This field can be left blank!"
)
parser.add_argument('videos',
action='append',
help="This field can be left blank!"
)
parser.add_argument('comment',
type=validate_string,
required=True,
help="This field cannot be left blank or should be properly formated"
)
parser.add_argument('title',
type=validate_string,
required=True,
help="This field cannot be left blank or should be properly formated"
)
incidents = []
class RedFlagModel():
"""Class with methods to perform CRUD operations on the DB"""
def __init__(self):
self.db = incidents
if len(incidents) == 0:
self.id = 1
else:
self.id = incidents[-1]['id'] + 1
self.id = len(incidents) + 1
def save(self):
parser.parse_args()
data = {
'id': self.id,
'createdOn': datetime.datetime.utcnow(),
'createdBy': request.json.get('createdBy'),
'type': 'red-flags',
'location': request.json.get('location'),
'status': "under investigation",
'images': request.json.get('images'),
'videos': request.json.get('videos'),
'title': request.json.get('title'),
'comment': request.json.get('comment')
}
self.db.append(data)
return self.id
def find(self, redflag_id):
for incident in self.db:
if incident['id'] == redflag_id:
return incident
return "red flag does not exit"
def delete(self, incident):
self.db.remove(incident)
return "deleted"
def get_all(self):
return self.db
def edit_redflag_location(self, incident):
"Method to edit a redflag's location"
incident['location'] = request.json.get('location', 'keyerror')
if incident['location'] == 'keyerror':
return "keyerror"
return "updated"
def edit_redflag_comment(self, incident):
"Method to edit a redflag's comment"
incident['comment'] = request.json.get('comment', 'keyerror')
if incident['comment'] == 'keyerror':
return "keyerror"
return "updated"
def edit_redflag(self, incident):
"""Method to edit redflag fields"""
parser.parse_args()
incident['createdBy'] = request.json.get(
'createdBy', incident['createdBy'])
incident['location'] = request.json.get(
'location', incident['location'])
incident['status'] = request.json.get('status', incident['status'])
incident['images'] = request.json.get('images', incident['images'])
incident['videos'] = request.json.get('videos', incident['videos'])
incident['title'] = request.json.get('title', incident['title'])
incident['comment'] = request.json.get('comment', incident['comment'])
return "updated"
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,302 | antonnifo/iReporter | refs/heads/develop | /app/api/v1/routes.py | """all routes"""
from flask import Blueprint
from flask_restful import Api
from .redflags.views import RedFlag, RedFlags, UpdateComment, UpdateLocation
VERSION_UNO = Blueprint('api', __name__, url_prefix='/api/v1')
API = Api(VERSION_UNO)
API.add_resource(RedFlags, '/red-flags')
API.add_resource(RedFlag, '/red-flags/<int:redflag_id>')
API.add_resource(UpdateLocation, '/red-flags/<int:redflag_id>/location')
API.add_resource(UpdateComment, '/red-flags/<int:redflag_id>/comment')
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,303 | antonnifo/iReporter | refs/heads/develop | /app/api/v2/incidents/views_interventions.py | """Views for Interventions"""
from flask import jsonify, make_response, request
from flask_restful import Resource
from app.api.v2.users.models import UserModel
from ..validators import (can_only_edit_draft, non_existance_incident,
only_admin_can_edit, only_creater_can_delete,
only_creater_can_edit)
from .models import IncidentModel
from app.api.v2.token_decorator import require_token
class Interventions(Resource):
"""docstring for interventions class"""
def __init__(self):
"""initiliase the interventions class"""
self.db = IncidentModel()
@require_token
def post(current_user, self):
"""method for saving an intervention"""
incident = self.db.save(
current_user['user_id'], incident_type='intervention')
return jsonify({
"status": 201,
"data": incident,
"message": "Created intervention record"
})
@require_token
def get(current_user, self):
"""method for getting all the interventions posted by users"""
self.db.find_by_type(incident_type='intervention')
return jsonify({
"status": 200,
"data": self.db.find_by_type(incident_type='intervention')
})
class Intervention(Resource):
"""docstring of a single intervention"""
def __init__(self):
"""initiliase the intervention class"""
self.db = IncidentModel()
@require_token
def get(current_user, self, incident_id):
"""method for getting a specific intervention"""
incident = self.db.find_by_id_type(
incident_id, incident_type='intervention')
if incident == "incident does not exit":
return non_existance_incident()
return jsonify({
"status": 200,
"data": incident
})
@require_token
def delete(current_user, self, incident_id):
"""docstring for deleting an intervention"""
incident = self.db.find_by_id_type(
incident_id, incident_type='intervention')
if incident == "incident does not exit":
return non_existance_incident()
if current_user["user_id"] != incident["createdby"]:
return only_creater_can_delete()
if self.db.delete(incident_id, incident_type='intervention') == "deleted":
return jsonify({
"status": 200,
"message": 'incident record has been deleted'
})
class UpdateInterventionLocation(Resource):
"""class to update intervention location"""
def __init__(self):
"""initiliase the update location class of an intervention"""
self.database = IncidentModel()
@require_token
def patch(current_user, self, incident_id):
"""method to update an intervention location"""
edit_status = self.database.edit_incident_location(
current_user['user_id'],incident_id, incident_type='intervention')
if edit_status is None:
return non_existance_incident()
if edit_status is False:
return only_creater_can_edit()
if edit_status == 'you cant edit this':
return can_only_edit_draft()
if edit_status == "location updated":
return jsonify({
"status": 200,
"data": {
"id": incident_id,
"message": "Updated intervention record's location"
}
})
class UpdateInterventionComment(Resource):
"""docstring for patching an intervention comment"""
def __init__(self):
self.db = IncidentModel()
@require_token
def patch(current_user, self, incident_id):
"""method to update comment of an intervention"""
incident = self.db.find_by_id_type(
incident_id, incident_type='intervention')
if incident == "incident does not exit":
return non_existance_incident()
if current_user["user_id"] != incident['createdby']:
return only_creater_can_edit()
edit_status = self.db.edit_incident_comment(
incident_id, incident_type='intervention')
if edit_status == "you cant edit this":
return can_only_edit_draft()
if edit_status == "comment updated":
return jsonify({
"status": 200,
"data": {
"id": incident_id,
"message": "Updated incident record's comment"
}
})
class UpdateInterventionStatus(Resource):
"""docstring for patching status of an intervention"""
def __init__(self):
self.db = IncidentModel()
@require_token
def patch(current_user, self, incident_id):
"""method to update status of an intervention"""
if current_user['isadmin'] is False:
return only_admin_can_edit()
edit_status = self.db.edit_incident_status(
incident_id, incident_type='intervention')
if edit_status == None:
return non_existance_incident()
if edit_status == "status updated":
return jsonify({
"status": 200,
"data": {
"id": incident_id,
"message": "Updated intervention's status"
}
})
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,304 | antonnifo/iReporter | refs/heads/develop | /app/tests/v2/test_incidents.py | """Tests for incidents in v2 run with pytest"""
import datetime
import json
import os
import unittest
import jwt
from ... import create_app
from app.db_con import create_tables, super_user, destroy_tables
from app.tests.v2.testing_data import (
test_user, user, user2, user3, user4, redflag_data, redflag_data3, redflag_data2, data5, data6, data7, intervention_data)
secret = os.getenv('SECRET_KEY')
class IncidentTestCase(unittest.TestCase):
"""
This class represents the incident test cases
"""
def setUp(self):
APP = create_app(config_name="testing")
APP.testing = True
self.app = APP.test_client()
create_tables()
super_user()
self.test_user = test_user
payload = {
"email": self.test_user['email'],
"exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
}
assert "exp" in payload
token = jwt.encode(
payload=payload, key=secret, algorithm='HS256')
self.headers = {'Content-Type': 'application/json',
'token': token
}
self.headers_invalid = {
'Content-Type': 'application/json', 'token': 'Tokenmbaya'}
self.intervention = intervention_data
self.redflag = redflag_data
self.redflag_data2 = redflag_data2
self.redflag_data3 = redflag_data3
def test_get_all_redflags(self):
"""Test all redflags"""
response = self.app.get("/api/v2/redflags", headers=self.headers)
self.assertEqual(response.status_code, 200)
def test_get_all_interventions(self):
"""Test all redflags"""
response = self.app.get("/api/v2/interventions", headers=self.headers)
self.assertEqual(response.status_code, 200)
def test_get_all_interventions_no_token(self):
"""method to test get all incidents with no token"""
response = self.app.get("/api/v2/interventions")
result = json.loads(response.data)
self.assertEqual(response.status_code, 401)
self.assertEqual(result['message'], "Token is missing")
def test_get_all_redflags_no_token(self):
"""method to test get all incidents with no token"""
response = self.app.get("/api/v2/redflags")
result = json.loads(response.data)
self.assertEqual(response.status_code, 401)
self.assertEqual(result['message'], "Token is missing")
def test_get_all_intervention_invalid_token(self):
"""method to test get all incidents with invalid token"""
response = self.app.get(
"/api/v2/interventions", headers=self.headers_invalid)
result = json.loads(response.data)
self.assertEqual(response.status_code, 401)
self.assertEqual(result['message'], "Token is invalid")
def test_get_all_redflag_invalid_token(self):
"""method to test get all incidents with invalid token"""
response = self.app.get(
"/api/v2/redflags", headers=self.headers_invalid)
result = json.loads(response.data)
self.assertEqual(response.status_code, 401)
self.assertEqual(result['message'], "Token is invalid")
def test_get_specific_redflag(self):
"""Test get a specific redflag"""
self.app.post("/api/v2/redflags", headers=self.headers,
data=json.dumps(self.redflag))
response = self.app.get("/api/v2/redflag/1", headers=self.headers)
self.assertEqual(response.status_code, 200)
def test_get_specific_intervention(self):
"""Test get a specific intervention"""
self.app.post("/api/v2/interventions", headers=self.headers,
data=json.dumps(self.redflag))
response = self.app.get(
"/api/v2/intervention/1", headers=self.headers)
self.assertEqual(response.status_code, 200)
def test_post_redflag(self):
"""Test post a redflag"""
response = self.app.post(
"/api/v2/redflags", headers=self.headers, data=json.dumps(self.redflag))
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertEqual(result['status'], 201)
def test_post_intervention(self):
"""Test post a intervention"""
response = self.app.post(
"/api/v2/interventions", headers=self.headers, data=json.dumps(self.redflag))
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertEqual(result['status'], 201)
def test_update_status_of_nonexistent_redflag(self):
"""Test update status of a nonexistant redflag"""
response = self.app.patch(
"/api/v2/redflags/2/status", headers=self.headers, data=json.dumps({"status": "resolved"}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertEqual(result['error'], 'incident does not exist')
def test_update_status_of_redflag(self):
"""Test update status of a specific redflag"""
self.app.post(
"/api/v2/redflags", headers=self.headers, data=json.dumps(self.redflag))
response = self.app.patch(
"/api/v2/redflags/1/status", headers=self.headers, data=json.dumps({"status": "resolved"}))
json.loads(response.data)
self.assertEqual(response.status_code, 200)
def test_update_location_of_nonexistent_redflag(self):
"""Test update location of a specific redflag"""
response = self.app.patch(
"/api/v2/redflags/2/location", headers=self.headers, data=json.dumps({"location": "-75.0, -12.554334"}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertEqual(result['error'], 'incident does not exist')
def test_update_location_of_redflag(self):
"""Test update location of a specific redflag"""
self.app.post(
"/api/v2/redflags", headers=self.headers, data=json.dumps(self.redflag))
response = self.app.patch("/api/v2/redflags/1/location", headers=self.headers,
data=json.dumps({"location": "-75.0, -12.554334"}))
json.loads(response.data)
self.assertEqual(response.status_code, 200)
def test_update_comment_of_nonexistent_redflag(self):
"""Test update comment of a specific redflag"""
response = self.app.patch(
"/api/v2/redflags/2/comment", headers=self.headers, data=json.dumps({"comment": "You Only Live Once"}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertEqual(result['error'], 'incident does not exist')
def test_update_comment_of_redflag(self):
"""Test update comment of a specific redflag"""
self.app.post(
"/api/v2/redflags", headers=self.headers, data=json.dumps(self.redflag))
response = self.app.patch("/api/v2/redflags/1/comment", headers=self.headers,
data=json.dumps({"comment": "You Only Live Once"}))
json.loads(response.data)
self.assertEqual(response.status_code, 200)
def test_update_location_of_intervention(self):
"""Test update location of a specific intervention"""
self.app.post(
"/api/v2/interventions", headers=self.headers, data=json.dumps(self.redflag))
response = self.app.patch("/api/v2/interventions/1/location",
headers=self.headers, data=json.dumps({"location": "-75.0, -12.554334"}))
json.loads(response.data)
self.assertEqual(response.status_code, 200)
def test_update_comment_of_nonexistent_intervention(self):
"""Test update comment of a specific intervention"""
response = self.app.patch(
"/api/v2/interventions/254534423/comment", headers=self.headers, data=json.dumps({"comment": "You only live once"}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertEqual(result['error'], 'incident does not exist')
def test_update_comment_of_intervention(self):
"""Test update comment of a specific intervention"""
self.app.post(
"/api/v2/interventions", headers=self.headers, data=json.dumps(self.redflag))
response = self.app.patch("/api/v2/interventions/1/comment", headers=self.headers,
data=json.dumps({"comment": "Cartels are taking over Kenya"}))
json.loads(response.data)
self.assertEqual(response.status_code, 200)
def test_delete_intervention_withiout_ownership(self):
"""method to test if one can delete an incident"""
self.app.post("/api/v2/interventions",
headers=self.headers, data=json.dumps(self.intervention))
response = self.app.delete("/api/v2/intervention/1")
json.loads(response.data)
self.assertEqual(response.status_code, 401)
def test_delete_redflag_withiout_ownership(self):
"""method to test if one can delete an incident"""
self.app.post("/api/v2/interventions",
headers=self.headers, data=json.dumps(self.redflag))
response = self.app.delete("/api/v2/redflag/2")
json.loads(response.data)
self.assertEqual(response.status_code, 401)
def test_delete_intervention_withiout_token(self):
"""method to test if one can delete an incident"""
self.app.post("/api/v2/interventions",
data=json.dumps(self.intervention))
response = self.app.delete("/api/v2/intervention/1")
json.loads(response.data)
self.assertEqual(response.status_code, 401)
def test_delete_redflag_withiout_token(self):
"""method to test if one can delete an incident"""
self.app.post("/api/v2/interventions",
data=json.dumps(self.redflag))
response = self.app.delete("/api/v2/redflag/2")
json.loads(response.data)
self.assertEqual(response.status_code, 401)
def test_delete_intervention_with_invalid_token(self):
"""method to test if one can delete an incident"""
self.app.post("/api/v2/interventions",
headers=self.headers_invalid, data=json.dumps(self.intervention))
response = self.app.delete("/api/v2/intervention/1")
json.loads(response.data)
self.assertEqual(response.status_code, 401)
def test_delete_redflag_with_invalid_token(self):
"""method to test if one can delete an incident"""
self.app.post("/api/v2/interventions",
headers=self.headers_invalid, data=json.dumps(self.redflag))
response = self.app.delete("/api/v2/redflag/2")
json.loads(response.data)
self.assertEqual(response.status_code, 401)
def test_update_status_of_nonexistent_intervention(self):
"""Test update status of a nonexistant intervention"""
response = self.app.patch(
"/api/v2/interventions/266855866/status", headers=self.headers, data=json.dumps({"status": "resolved"}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertEqual(result['error'], 'incident does not exist')
def test_update_status_of_intervention(self):
"""Test update status of a specific intervention"""
self.app.post(
"/api/v2/interventions", headers=self.headers, data=json.dumps(self.redflag))
response = self.app.patch("/api/v2/interventions/1/status",
headers=self.headers, data=json.dumps({"status": "resolved"}))
json.loads(response.data)
self.assertEqual(response.status_code, 200)
def test_wrong_status_key_redflag(self):
"""Test wrong status key used in redflag"""
response = self.app.patch(
"/api/v2/redflags/1/status", headers=self.headers, data=json.dumps({"status1": "draft "}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 400)
self.assertEqual(result['message']['status'],
"This field cannot be left blank or should only be resolved ,under investigation or rejected")
def test_wrong_status_choice_in_redflag(self):
"""Test wrong status key used in redflag"""
response = self.app.patch(
"/api/v2/redflags/1/status", headers=self.headers, data=json.dumps({"status": "drafted"}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 400)
self.assertEqual(result['message']['status'],
"This field cannot be left blank or should only be resolved ,under investigation or rejected")
def test_wrong_location_key_redflag(self):
"""Test wrong location key used in redflag"""
response = self.app.patch("/api/v2/redflags/1/location",
headers=self.headers, data=json.dumps({"location1": "Mombao"}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 400)
self.assertEqual(result['message']['location'],
"This field cannot be left blank or improperly formated")
def test_wrong_status_key_intervention(self):
"""Test wrong status key used in intervention"""
response = self.app.patch("/api/v2/interventions/1/status",
headers=self.headers, data=json.dumps({"status1": "draft"}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 400)
self.assertEqual(result['message']['status'],
"This field cannot be left blank or should only be resolved ,under investigation or rejected")
def test_wrong_status_choice_in_intervention(self):
"""Test wrong status key used in intervention"""
response = self.app.patch("/api/v2/interventions/1/status",
headers=self.headers, data=json.dumps({"status": "drafted"}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 400)
self.assertEqual(result['message']['status'],
"This field cannot be left blank or should only be resolved ,under investigation or rejected")
def test_wrong_location_key_intervention(self):
"""Test wrong location key used in intervention"""
response = self.app.patch("/api/v2/interventions/1/location",
headers=self.headers, data=json.dumps({"location1": "Nairobi"}))
result = json.loads(response.data)
self.assertEqual(response.status_code, 400)
self.assertEqual(result['message']['location'],
"This field cannot be left blank or improperly formated")
def test_redflag_not_found(self):
"""Test a redflag not found"""
response = self.app.get("/api/v2/redflag/10000", headers=self.headers)
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertEqual(result['error'], "incident does not exist")
def test_intervention_not_found(self):
"""Test a redflag not found"""
response = self.app.get(
"/api/v2/intervention/10000", headers=self.headers)
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertEqual(result['error'], "incident does not exist")
def test_missing_key_redflag(self):
"""Test missing key in redflag"""
response = self.app.post(
"/api/v2/redflags", headers=self.headers, data=json.dumps(self.redflag_data3))
result = json.loads(response.data)
self.assertEqual(response.status_code, 400)
def test_missing_key_intervention(self):
"""Test missing key in intervention"""
response = self.app.post(
"/api/v2/interventions", headers=self.headers, data=json.dumps(self.redflag_data3))
result = json.loads(response.data)
self.assertEqual(response.status_code, 400)
def test_delete_specific_redflag(self):
"""Test delete a specific redflag"""
self.app.post("/api/v2/redflags", headers=self.headers,
data=json.dumps(self.redflag))
response = self.app.delete("/api/v2/redflag/1", headers=self.headers)
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertEqual(result['message'],
'incident record has been deleted')
def test_delete_specific_intervention(self):
"""Test delete a specific intervention"""
self.app.post("/api/v2/interventions", headers=self.headers,
data=json.dumps(self.redflag))
response = self.app.delete(
"/api/v2/intervention/1", headers=self.headers)
result = json.loads(response.data)
self.assertEqual(response.status_code, 200)
self.assertEqual(result['message'],
'incident record has been deleted')
def tearDown(self):
destroy_tables()
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,305 | antonnifo/iReporter | refs/heads/develop | /app/api/v2/routes.py | """all for version 2 routes"""
from flask import Blueprint
from flask_restful import Api
from .users.views import UserSignUp, UserSignIn, Users, Search, UserStatus
from .incidents.views_interventions import (Interventions, Intervention, UpdateInterventionLocation,
UpdateInterventionComment, UpdateInterventionStatus)
from .incidents.views_redflags import (
Redflags, Redflag, UpdateRedflagLocation, UpdateRedflagComment, UpdateRedflagStatus)
VERSION_TWO = Blueprint('apiv2', __name__, url_prefix='/api/v2')
API = Api(VERSION_TWO)
API.add_resource(UserSignUp, '/auth/signup')
API.add_resource(UserSignIn, '/auth/signin')
API.add_resource(Users, '/users')
API.add_resource(Search, '/users/<string:email>')
API.add_resource(UserStatus, '/users/<string:email>/status')
API.add_resource(Interventions, '/interventions')
API.add_resource(Intervention, '/intervention/<int:incident_id>')
API.add_resource(UpdateInterventionLocation,
'/interventions/<int:incident_id>/location')
API.add_resource(UpdateInterventionComment,
'/interventions/<int:incident_id>/comment')
API.add_resource(UpdateInterventionStatus,
'/interventions/<int:incident_id>/status')
API.add_resource(Redflags, '/redflags')
API.add_resource(Redflag, '/redflag/<int:incident_id>')
API.add_resource(UpdateRedflagLocation,
'/redflags/<int:incident_id>/location')
API.add_resource(UpdateRedflagComment,
'/redflags/<int:incident_id>/comment')
API.add_resource(UpdateRedflagStatus, '/redflags/<int:incident_id>/status')
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,306 | antonnifo/iReporter | refs/heads/develop | /app/api/v2/users/views.py | """Views for users"""
import os
import datetime
from flask import jsonify,request
from flask_restful import Resource
from app.api.v2.token_decorator import require_token
from app.api.v2.validators import only_admin_can_edit
import jwt
from .models import UserModel
secret = os.getenv('SECRET_KEY')
def nonexistent_user():
return jsonify({
"status": 404,
"message": "user does not exist"
})
def admin_user():
return jsonify({
"status": 403,
"message": "Only admin can access this route"
})
class UserSignUp(Resource):
"""Class with user signup post method"""
def __init__(self):
self.db = UserModel()
def post(self):
"""method to post user details"""
user = self.db.save()
if user == "email already exists":
return jsonify({
"status": 400,
"error": "email already exists"
})
payload = {
"email": user['email'],
"exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
}
token = jwt.encode(payload=payload, key=secret, algorithm='HS256')
user_details = {
"name": user['first_name']+' '+user['last_name'],
"email": user['email'],
"phone": user['phone']
}
return jsonify({
"status": 201,
"data": [
{
"account details": user_details,
"token": token.decode('UTF-8'),
"message": "You have created an account you can now post incidents"
}
]
})
class UserSignIn(Resource):
"""Class containing user login method"""
def __init__(self):
self.db = UserModel()
def post(self):
"""method to get a specific user"""
user = self.db.log_in()
if user is None:
return nonexistent_user()
if user == 'incorrect password':
return jsonify({
"status": 401,
"message": "password or email is incorrect please try again"
})
payload = {
"email": user,
"exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
}
token = jwt.encode(payload=payload, key=secret, algorithm='HS256')
return jsonify({
"status": 200,
"data": [
{
"token": token.decode('UTF-8'),
"user": user,
"message": "You are now signed in you can post an incident"
}
]
})
class Users(Resource):
"""Class with methods for dealing with all users"""
def __init__(self):
self.db = UserModel()
@require_token
def get(current_user, self):
"""method to get all users"""
if current_user['isadmin'] is False:
return admin_user()
return jsonify({
"status": 200,
"data": self.db.find_users()
})
class Search(Resource):
"""docstring filtering incidents by type"""
def __init__(self):
"""initiliase the incident class"""
self.db = UserModel()
@require_token
def get(current_user, self, email):
"""method for getting a specific user by email"""
if current_user['isadmin'] is False:
return admin_user()
user = self.db.find_user_by_email(email)
if user is None:
return nonexistent_user()
user_details = {
"name": user['first_name']+' '+user['last_name'],
"email": user['email'],
"phone": user['phone'],
"regestered":user['registered'],
"isAdmin":user['isadmin']
}
return jsonify({
"status": 200,
"data": user_details
})
@require_token
def delete(current_user, self, email):
"""method to delete a user"""
user = self.db.find_user_by_email(email)
if user is None:
return nonexistent_user()
if current_user['isadmin'] is not True:
return jsonify({
"status": 403,
"message": "Only an admin can delete a user"
})
delete_status = self.db.delete_user(email)
if delete_status is True:
return jsonify({
"status": 200,
"data": {
"email": email,
"message": "user record has been deleted"
}
})
class UserStatus(Resource):
"""Class with method for updating a specific user admin status"""
def __init__(self):
self.db = UserModel()
@require_token
def patch(current_user, self, email):
"""method to promote a user"""
user = self.db.find_user_by_email(email)
if user is None:
return nonexistent_user()
if current_user['isadmin'] is not True:
return jsonify({
"status": 403,
"message": "Only an admin can change the status of a user"
})
user_status_updated = self.db.edit_user_status(email)
if user_status_updated is True:
success_message = {
"email": email,
"message": "User status has been updated"
}
return jsonify({
"status": 200,
"data": success_message
}) | {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,307 | antonnifo/iReporter | refs/heads/develop | /app/__init__.py | from flask import Blueprint, Flask
from app.api.v1.routes import VERSION_UNO as v1
from app.api.v2.routes import VERSION_TWO as v2
from app.instance.config import APP_CONFIG
from app.db_con import create_tables, super_user, destroy_tables
def create_app(config_name):
'''The create_app function wraps the creation of a new Flask object,
and returns it after it's loaded up with configuration settings using
app.config '''
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(APP_CONFIG[config_name])
app.url_map.strict_slashes = False
destroy_tables()
# create_tables()
super_user()
app.register_blueprint(v1)
app.register_blueprint(v2)
return app
| {"/app/api/v1/redflags/views.py": ["/app/api/v1/redflags/models.py"], "/run.py": ["/app/__init__.py"], "/app/api/v2/incidents/views_redflags.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/api/v2/token_decorator.py": ["/app/api/v2/users/models.py"], "/app/tests/v1/test_redflags.py": ["/app/__init__.py"], "/app/api/v2/incidents/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/tests/v2/test_users.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/users/models.py": ["/app/db_con.py", "/app/api/v2/validators.py"], "/app/api/v1/redflags/models.py": ["/app/api/v2/validators.py"], "/app/api/v1/routes.py": ["/app/api/v1/redflags/views.py"], "/app/api/v2/incidents/views_interventions.py": ["/app/api/v2/users/models.py", "/app/api/v2/validators.py", "/app/api/v2/incidents/models.py", "/app/api/v2/token_decorator.py"], "/app/tests/v2/test_incidents.py": ["/app/__init__.py", "/app/db_con.py", "/app/tests/v2/testing_data.py"], "/app/api/v2/routes.py": ["/app/api/v2/users/views.py", "/app/api/v2/incidents/views_interventions.py", "/app/api/v2/incidents/views_redflags.py"], "/app/api/v2/users/views.py": ["/app/api/v2/token_decorator.py", "/app/api/v2/validators.py", "/app/api/v2/users/models.py"], "/app/__init__.py": ["/app/api/v1/routes.py", "/app/api/v2/routes.py", "/app/db_con.py"]} |
51,349 | brano2/vcd-parser | refs/heads/master | /tests/test_parser.py | from datetime import datetime
import pytest
import vcd_parser
from vcd_parser import VCD
def test_tokenize():
TOKENS = ['$keyword', '"', 'word', '123', '16/8/2048', '-0.42', '4:20', '#0', 'b001011"']
WHITESPACE = [' ', '\t', '\n', ' ', '\t\t\t', '\n\n\n', ' \t ', '\r\n', '\t \r\n \t \n\t']
class DummyFile:
def open(self):
for tok, sep in zip(TOKENS, WHITESPACE):
yield tok+sep
parsed_tokens = list(VCD._tokenize(DummyFile()))
assert parsed_tokens == TOKENS
ENDDEFS = ['$enddefinitions', '$end']
def make_mock_tokenize(monkeypatch, tokens):
def mock__tokenize(file):
yield from tokens
monkeypatch.setattr(VCD, '_tokenize', mock__tokenize)
def test_minimal_vcd(monkeypatch, tmp_path):
TOKENS = ENDDEFS
make_mock_tokenize(monkeypatch, TOKENS)
vcd = VCD(tmp_path)
assert vcd._headers_complete
assert vcd.comments == []
assert vcd.date == None
assert vcd.version == None
assert vcd.vars == {}
def test_enddefs_extra_token(monkeypatch, tmp_path):
TOKENS = [ENDDEFS[0], 'tok', ENDDEFS[1]]
make_mock_tokenize(monkeypatch, TOKENS)
with pytest.raises(vcd_parser.vcd.VcdSyntaxError):
vcd = VCD(tmp_path)
@pytest.mark.xfail(raises=StopIteration)
def test_empty(monkeypatch, tmp_path):
TOKENS = []
make_mock_tokenize(monkeypatch, TOKENS)
with pytest.raises(vcd_parser.vcd.VcdSyntaxError):
vcd = VCD(tmp_path)
@pytest.mark.xfail(raises=StopIteration)
def test_missing_end(monkeypatch, tmp_path):
TOKENS = ['$comment', 'a', 'b']
make_mock_tokenize(monkeypatch, TOKENS)
with pytest.raises(vcd_parser.vcd.VcdSyntaxError):
vcd = VCD(tmp_path)
@pytest.mark.xfail(raises=StopIteration)
def test_missing_end_upscope(monkeypatch, tmp_path):
TOKENS = ['$upscope']
make_mock_tokenize(monkeypatch, TOKENS)
with pytest.raises(vcd_parser.vcd.VcdSyntaxError):
vcd = VCD(tmp_path)
@pytest.mark.xfail(raises=StopIteration)
def test_missing_end_enddefs(monkeypatch, tmp_path):
TOKENS = [ENDDEFS[0]]
make_mock_tokenize(monkeypatch, TOKENS)
with pytest.raises(vcd_parser.vcd.VcdSyntaxError):
vcd = VCD(tmp_path)
@pytest.mark.xfail(raises=KeyError)
def test_unknown_keyword(monkeypatch, tmp_path):
TOKENS = ['$unknown', '$end'] + ENDDEFS
make_mock_tokenize(monkeypatch, TOKENS)
with pytest.raises(vcd_parser.vcd.VcdSyntaxError):
vcd = VCD(tmp_path)
assert list(vcd._token_stream) == ['$end'] + ENDDEFS
def test_comment(monkeypatch, tmp_path):
TOKENS = ['$comment', 'Hello,', 'world!', '$end'] + ENDDEFS
make_mock_tokenize(monkeypatch, TOKENS)
vcd = VCD(tmp_path)
assert vcd.comments == ['Hello, world!']
assert vcd.date == None
assert vcd.version == None
assert vcd.vars == {}
def test_empty_comment(monkeypatch, tmp_path):
TOKENS = ['$comment', '$end'] + ENDDEFS
make_mock_tokenize(monkeypatch, TOKENS)
vcd = VCD(tmp_path)
assert vcd.comments == ['']
assert vcd.date == None
assert vcd.version == None
assert vcd.vars == {}
def test_comment(monkeypatch, tmp_path):
TOKENS = ['$comment', 'Hello,', 'world!', '$end',
'$comment', '$end',
'$comment', 'comment3', '$end'] + ENDDEFS
make_mock_tokenize(monkeypatch, TOKENS)
vcd = VCD(tmp_path)
assert vcd.comments == ['Hello, world!', '', 'comment3']
assert vcd.date == None
assert vcd.version == None
assert vcd.vars == {}
def test_version(monkeypatch, tmp_path):
TOKENS = ['$version', 'test', 'v0.0.1', '$end'] + ENDDEFS
make_mock_tokenize(monkeypatch, TOKENS)
vcd = VCD(tmp_path)
assert vcd.comments == []
assert vcd.date == None
assert vcd.version == 'test v0.0.1'
assert vcd.vars == {}
def test_version_empty(monkeypatch, tmp_path):
TOKENS = ['$version', '$end'] + ENDDEFS
make_mock_tokenize(monkeypatch, TOKENS)
vcd = VCD(tmp_path)
assert vcd.comments == []
assert vcd.date == None
assert vcd.version == ''
assert vcd.vars == {}
def test_date(monkeypatch, tmp_path):
t = datetime.now()
TOKENS = ['$date', t.isoformat(), '$end'] + ENDDEFS
make_mock_tokenize(monkeypatch, TOKENS)
vcd = VCD(tmp_path)
assert vcd.comments == []
assert vcd.date == t
assert vcd.version == None
assert vcd.vars == {}
def test_date_unparseable(monkeypatch, tmp_path):
TOKENS = ['$date', 'unparseable', 'date', '$end'] + ENDDEFS
make_mock_tokenize(monkeypatch, TOKENS)
vcd = VCD(tmp_path)
assert vcd.comments == []
assert vcd.date == 'unparseable date'
assert vcd.version == None
assert vcd.vars == {}
| {"/tests/test_parser.py": ["/vcd_parser/__init__.py"], "/demo/demo.py": ["/vcd_parser/__init__.py"], "/vcd_parser/__init__.py": ["/vcd_parser/vcd.py"]} |
51,350 | brano2/vcd-parser | refs/heads/master | /demo/demo.py | from vcd_parser import VCD
# Open the file and parse its contents
vcd1 = VCD('data.vcd')
# Display the parsed data
print('VCD header data:')
print('\tComments:')
for comment in vcd1.comments:
print('\t\t' + comment)
print('\tDate: ' + vcd1.date.isoformat())
print('\tVersion: ' + vcd1.version)
print(f'\tTimescale: {vcd1.timescale}s')
print()
print('Variables and value changes:')
for v in vcd1.vars.values():
var = v.copy()
del var['vals']
del var['timestamps']
var['num_vals'] = len(v['vals'])
var['num_timestamps'] = len(v['timestamps'])
print(var)
| {"/tests/test_parser.py": ["/vcd_parser/__init__.py"], "/demo/demo.py": ["/vcd_parser/__init__.py"], "/vcd_parser/__init__.py": ["/vcd_parser/vcd.py"]} |
51,351 | brano2/vcd-parser | refs/heads/master | /vcd_parser/vcd.py | from pathlib import Path
from typing import Callable, ClassVar, Dict, List, Union
from warnings import warn
from dateutil.parser import parse as parse_datetime
class VcdSyntaxError(Exception):
pass
END = '$end'
class VCD:
KEYWORD_PARSERS: ClassVar[Dict[str, Callable[['VCD'], None]]]
def __init__(self, file: Union[Path, str]) -> None:
self._file = Path(file)
self._token_stream = VCD._tokenize(self._file)
self._current_scope_type = None # Change to stacks to allow nested scopes
self._current_scope = None # (I'm not sure if nested scopes are part of the VCD spec.)
self._headers_complete = False # A flag to indicate that all headers have been parsed
self.comments = []
self.date = None
self.version = None
self.vars = {}
while not self._headers_complete:
token = next(self._token_stream)
self.KEYWORD_PARSERS[token](self)
self._parse_value_changes()
@staticmethod
def _tokenize(file: Path):
for line in file.open():
for token in line.split():
yield token
def _get_inner_tokens(self) -> List[str]:
"""Retrieves inner tokens of a section and consumes the closing $end token."""
tokens = []
for token in self._token_stream:
if token != END:
tokens.append(token)
else:
break
return tokens
def _parse_text(self) -> str:
"""Joins all tokens into a single string using spaces until an $end token is found."""
tokens = self._get_inner_tokens()
text = ' '.join(tokens)
return text
def _parse_comment(self):
comment = self._parse_text()
self.comments.append(comment)
def _parse_date(self):
date = self._parse_text()
try:
self.date = parse_datetime(date)
except:
self.date = date
def _parse_version(self):
self.version = self._parse_text()
def _parse_timescale(self):
tokens = self._get_inner_tokens()
if len(tokens) != 2:
raise VcdSyntaxError('The $timescale section should contain exactly two tokens. ' +
f"Expected '<time_number> <time_unit>' but found {tokens}.")
UNIT_MULTIPLIERS = dict(s=1.0, ms=1e-3, us=1e-6, ns=1e-9, ps=1e-12, fs=1e-15)
value = int(tokens[0])
unit = tokens[1]
if value not in [1, 10, 100] or unit not in UNIT_MULTIPLIERS:
raise VcdSyntaxError(f"Timescale value must be 1, 10 or 100. Was {value}." +
f"The unit must be s, ms, us, ns, ps or fs. Was '{unit}'.")
self.timescale = value*UNIT_MULTIPLIERS[unit]
def _parse_scope(self):
tokens = self._get_inner_tokens()
if len(tokens) != 2:
raise VcdSyntaxError('The $scope section should contain exactly two tokens. ' +
f"Expected '<scope_type> <identifier>' but found {tokens}.")
SCOPE_TYPES = ['begin', 'fork', 'function', 'module', 'task']
if tokens[0] not in SCOPE_TYPES:
warn(f"Unknown scope type '{tokens[0]}'. Should be one of: {SCOPE_TYPES}")
self._current_scope_type = tokens[0] # Push onto a stack to allow nested scopes
self._current_scope = tokens[1]
def _parse_upscope(self):
token = next(self._token_stream)
if token != END:
raise VcdSyntaxError(f"Non-empty $upscope section. Found '{token}' after '$upscope'")
self._current_scope_type = None # Pop from a stack to allow nested scopes
self._current_scope = None
def _parse_var(self):
tokens = self._get_inner_tokens()
if len(tokens) != 4:
raise VcdSyntaxError('The $scope section should contain exactly four tokens. ' +
f"Expected '<var_type> <size> <identifier> <reference>' but found {tokens}.")
VAR_TYPES = ['event', 'integer', 'parameter', 'real', 'reg', 'supply0', 'supply1', 'time',
'tri', 'triand', 'trior', 'trireg', 'tri0', 'tri1', 'wand', 'wire', 'wor']
if tokens[0] not in VAR_TYPES:
warn(f"Unknown variable type '{tokens[0]}'. Should be one of: {VAR_TYPES}")
self.vars[tokens[2]] = dict(scope_type=self._current_scope_type,
scope=self._current_scope,
type=tokens[0],
size=int(tokens[1]),
id=tokens[2],
name=tokens[3],
vals=[], timestamps=[])
def _parse_enddefinitions(self):
token = next(self._token_stream)
if token != END:
raise VcdSyntaxError(
f"Non-empty $enddefinitions section. Found '{token}' after '$enddefinitions'")
self._headers_complete = True
def _parse_value_changes(self):
current_timestamp = None
for token in self._token_stream:
if token.startswith('#'):
current_timestamp = int(token[1:])
else:
value, var_id = int(token[0]), token[1] # Assuming all vars are single bit for now
self.vars[var_id]['vals'].append(value)
self.vars[var_id]['timestamps'].append(current_timestamp)
VCD.KEYWORD_PARSERS = {
'$comment': VCD._parse_comment,
'$date': VCD._parse_date,
'$enddefinitions': VCD._parse_enddefinitions,
'$scope': VCD._parse_scope,
'$timescale': VCD._parse_timescale,
'$upscope': VCD._parse_upscope,
'$var': VCD._parse_var,
'$version': VCD._parse_version,
}
| {"/tests/test_parser.py": ["/vcd_parser/__init__.py"], "/demo/demo.py": ["/vcd_parser/__init__.py"], "/vcd_parser/__init__.py": ["/vcd_parser/vcd.py"]} |
51,352 | brano2/vcd-parser | refs/heads/master | /vcd_parser/__init__.py | from .vcd import VCD
| {"/tests/test_parser.py": ["/vcd_parser/__init__.py"], "/demo/demo.py": ["/vcd_parser/__init__.py"], "/vcd_parser/__init__.py": ["/vcd_parser/vcd.py"]} |
51,353 | brano2/vcd-parser | refs/heads/master | /setup.py | from pathlib import Path
from setuptools import find_packages, setup
BASEDIR = Path(__file__).parent
setup(
name='vcd-parser',
version='0.0.2',
description='A parser for Value Change Dump (VCD) files (generated by PulseView)',
long_description=(BASEDIR/'README.md').read_text(),
long_description_content_type="text/markdown",
url='https://github.com/brano2/vcd-parser',
author='Branislav Pilnan',
author_email='b.pilnan@gmail.com',
license='MIT',
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: Scientific/Engineering",
"Topic :: Software Development :: Embedded Systems",
"Topic :: Utilities",
],
packages=find_packages(exclude=('tests',)),
include_package_data=True,
install_requires=(BASEDIR/'requirements.txt').read_text().splitlines(),
extras_require={
'tests': (BASEDIR/'requirements-tests.txt').read_text().splitlines()
},
zip_safe=False
)
| {"/tests/test_parser.py": ["/vcd_parser/__init__.py"], "/demo/demo.py": ["/vcd_parser/__init__.py"], "/vcd_parser/__init__.py": ["/vcd_parser/vcd.py"]} |
51,365 | dineshdb/ocr | refs/heads/master | /train.py | import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
from keras.models import load_model
import glob
#CNN model
def Model():
# create model
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(1, 28, 28), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(15, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
#training the dataset
#although the main directory contains datasets for digits, but this model trains only the characters.
directory = str() #provide the main directory
main_path = glob.glob(directory)
p = str()
csv_dataset = []
label = 0
total = 0
for x in main_path:
path = glob.glob(x+'/*')
for addrs in path:
addrs = glob.glob(addrs+'/*')
for addr in addrs:
img = misc.imread(addr,flatten=True)
img_array= misc.imresize(img,(28,28))
img_data = img_array.reshape(784)
record = np.append(label,img_data)
csv_dataset.append(record)
total+=1
label+=1
label = 0
#saving the dataset image arrays in csv file
array_of_csv_dataset = np.array(csv_dataset)
array_of_csv_dataset = array_of_csv_dataset.reshape((total,785))
np.random.shuffle(array_of_csv_dataset)
np.savetxt("dataset.csv",array_of_csv_dataset,fmt = '%d',delimiter = ',',newline = ' \n')
#csv dataset of 74K samples
dataset_file = open("dataset.csv",'r')
dataset_list = dataset_file.readlines()
dataset_file.close()
#training dataset and test dataset in ratio 8:2
training_dataset_list = dataset_list[0:int(0.8*len(dataset_list))]
test_dataset_list = dataset_list[int(0.8*len(dataset_list))+1:]
X_train = []
Y_train = []
X_test = []
Y_test = []
for record in training_dataset_list:
all_values = record.split(',')
inputs = (np.asfarray(all_values[1:]))
X_train.append(inputs.reshape(28,28))
Y_train.append((all_values[0]))
X_train = np.array(X_train)
X_train = X_train.reshape(X_train.shape[0],28,28)
Y_train = np.array(Y_train)
X_test = []
Y_test = []
for record in test_dataset_list:
all_values = record.split(',')
inputs = (np.asfarray(all_values[1:]))
X_test.append(inputs.reshape(28,28))
Y_test.append(np.asfarray(all_values[0]))
X_test = np.array(X_test)
Y_test = np.array(Y_test)
K.set_image_dim_ordering('th')
# fix random seed for reproducibility
seed = 7
np.random.seed(seed)
# reshape to be [samples][pixels][width][height]
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32')
# normalize inputs from 0-255 to 0-1//
X_train = X_train / 255
X_test = X_test / 255
# one hot encode outputs
Y_train = np_utils.to_categorical(Y_train)
Y_test = np_utils.to_categorical(Y_test)
num_classes = Y_test.shape[1]
#defining the model
model = Model()
#fitting the dataset in model
epoch = 10
model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=epoch, batch_size=200)
# Final evaluation of the model
scores = model.evaluate(X_test, Y_test, verbose=0)
print("Large CNN Error: %.2f%%" % (100-scores[1]*100))
model.save('my_model.h5')
del model
| {"/web.py": ["/predictor.py"]} |
51,366 | dineshdb/ocr | refs/heads/master | /predictor.py | import os
import sys
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
import cv2
import numpy as np
from keras.models import load_model
import scipy.special
import scipy.misc as misc
# Create MSER (Maximally Stable External Regions) object
mser = cv2.MSER_create()
#pre_trained model with accuracy 83%
model = load_model('my_model.h5')
model._make_predict_function()
graph = tf.get_default_graph()
#get the label from index
def get_label(index):
if index < 26:
label = index + 65
else:
index=index%26
label = index + 97
return chr(label)
#predictor function
def predict(addr):
img = misc.imread(addr,flatten=True)
img_array= misc.imresize(img,(28,28))
img = img_array.reshape(1,28,28)
new = [img]*2
new = np.array(new)
out = model.predict(new)
prediction = get_label((np.argmax(out,axis=1))[0])
return prediction
def find_texts(url, min, max):
thres = cv2.imread(url, 0)
# thres = cv2.GaussianBlur(thres, (5, 5), 0)
# thres = cv2.adaptiveThreshold(thres,255,1,1,11,2)
#thres = cv2.adaptiveThreshold(thres, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, 11, 2)
# Mask and remove all non-text contents
mask = np.zeros((thres.shape[0], thres.shape[1], 1), dtype=np.uint8)
thres = cv2.bitwise_not(thres, thres, mask=mask)
mser.setMaxArea(max)
mser.setMinArea(min)
regions, bboxes = mser.detectRegions(thres)
res = []
# contour_sizes = [(cv2.contourArea(contour), contour) for contour in regions]
# biggest_contour = max(contour_sizes, key=lambda x: x[0])[1]
for coor in regions:
bbox = cv2.boundingRect(coor)
x, y, w, h = bbox
cv2.rectangle(thres, (x, y), (x+w, y+h), (255, 0, 0), 1)
letter = thres[y:y+h, x:x+w]
resized = cv2.resize(letter,(28,28), interpolation=cv2.INTER_AREA)
# resized = cv2.bitwise_not(resized, resized, mask= mask)
img_array = np.array(resized)
new = img_array.reshape(1, 1,28,28)
# img = resized.reshape(1,28,28)
# new = [img]*2
new = np.array(new)
with graph.as_default():
label = model.predict(new)
prediction = get_label(np.argmax(label,axis=1)[0])
res.append({"coor" : bbox, "label": prediction})
# cv2.imshow("resu;t", thres)
# cv2.waitKey(0)
print(str(res))
return res
| {"/web.py": ["/predictor.py"]} |
51,367 | dineshdb/ocr | refs/heads/master | /web.py | from flask import Flask, render_template, request, redirect, url_for, send_from_directory, flash, Response, jsonify
from werkzeug.utils import secure_filename
import os
from predictor import find_texts
UPLOAD_FOLDER = "./public/uploads/"
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
@app.route('/<path:path>')
def send_css(path):
return send_from_directory('public', path)
@app.route('/')
def get_home():
return send_from_directory('public', 'index.html')
@app.route('/', methods=['POST'])
def home():
# 1. load the template for homepage containing - done
# 2. form for file upload and submit/predict button - done
# 3. upload the file and save in the (-database)/file - done
# 4. use POST method to take the file - done
# 5. Return predicted values
# 6. Display values
# 7. Readjust parameters for rescan
if request.method == 'POST':
# check if the post request has the file part
if 'files' not in request.files:
return Response("{'id':'" + str(request.form) + "'}", status=401, mimetype='application/json')
file = request.files['files']
file_id = request.form['id']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
return Response("{}", status=201, mimetype='application/json')
print(file_id, file, file.filename)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_id))
return jsonify({"id": file_id }), 200
return jsonify({"error":"Could not handle that request"}), 305
@app.route('/predict/<id>')
def predict_id(id):
path = os.path.join(app.config['UPLOAD_FOLDER'], id)
min = request.args.get('min')
max = request.args.get('max')
max = int(float(max))
min = int(float(min))
result = find_texts(path, min, max)
return jsonify({"data" : result, "min" : min, "max" : max}), 200
if __name__ == '__main__':
app.run(debug=True)
| {"/web.py": ["/predictor.py"]} |
51,374 | Phelimb/bigsi-ebi-api | refs/heads/master | /bigsi_aggregator/constants.py | SEQUENCE_QUERY_KEY = "seq"
THRESHOLD_KEY = "threshold"
SCORE_KEY = "score"
COMPLETED_BIGSI_QUERIES_COUNT_KEY = "completed_bigsi_queries"
TOTAL_BIGSI_QUERIES_COUNT_KEY = "total_bigsi_queries"
RESULTS_KEY = "results"
| {"/bigsi_aggregator/tasks.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/models.py"], "/bigsi_aggregator/helpers.py": ["/bigsi_aggregator/tasks.py"], "/bigsi_aggregator/__init__.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/views.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/models.py": ["/bigsi_aggregator/__init__.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/views.py": ["/bigsi_aggregator/helpers.py", "/bigsi_aggregator/settings.py", "/bigsi_aggregator/models.py", "/bigsi_aggregator/__init__.py"]} |
51,375 | Phelimb/bigsi-ebi-api | refs/heads/master | /bigsi_aggregator/extensions.py | """Flask and other extensions instantiated here.
To avoid circular imports with views and create_app(), extensions are instantiated here. They will be initialized
(calling init_app()) in application.py.
"""
from flask_celery import Celery
# from flask.ext.redis import Redis
celery = Celery()
# redis = Redis()
| {"/bigsi_aggregator/tasks.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/models.py"], "/bigsi_aggregator/helpers.py": ["/bigsi_aggregator/tasks.py"], "/bigsi_aggregator/__init__.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/views.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/models.py": ["/bigsi_aggregator/__init__.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/views.py": ["/bigsi_aggregator/helpers.py", "/bigsi_aggregator/settings.py", "/bigsi_aggregator/models.py", "/bigsi_aggregator/__init__.py"]} |
51,376 | Phelimb/bigsi-ebi-api | refs/heads/master | /bigsi_aggregator/tasks.py | import requests
import json
from flask_celery import single_instance
from bigsi_aggregator.extensions import celery
from bigsi_aggregator.models import SequenceSearch
class BigsiClient:
def __init__(self, url):
self.base_url = url
def search(self, seq, threshold, score):
url = "{base_url}/search".format(base_url=self.base_url)
results = requests.post(
url,
data={"seq": seq, "threshold": int(threshold) / 100, "score": int(score)},
).json()
return results
@celery.task(name="search_bigsi_and_update_results")
def search_bigsi_and_update_results(url, sequence_search_id):
print(url, sequence_search_id)
sequence_search = SequenceSearch.get_by_id(sequence_search_id)
bigsi_client = BigsiClient(url)
bigsi_search_results = bigsi_client.search(
sequence_search.seq, sequence_search.threshold, sequence_search.score
)
sequence_search.add_results(bigsi_search_results["results"])
| {"/bigsi_aggregator/tasks.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/models.py"], "/bigsi_aggregator/helpers.py": ["/bigsi_aggregator/tasks.py"], "/bigsi_aggregator/__init__.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/views.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/models.py": ["/bigsi_aggregator/__init__.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/views.py": ["/bigsi_aggregator/helpers.py", "/bigsi_aggregator/settings.py", "/bigsi_aggregator/models.py", "/bigsi_aggregator/__init__.py"]} |
51,377 | Phelimb/bigsi-ebi-api | refs/heads/master | /bigsi_aggregator/settings.py | import os
BIGSI_URLS = os.environ.get("BIGSI_URLS", "http://localhost:8000").split()
REDIS_IP = os.environ.get("REDIS_IP", "localhost")
| {"/bigsi_aggregator/tasks.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/models.py"], "/bigsi_aggregator/helpers.py": ["/bigsi_aggregator/tasks.py"], "/bigsi_aggregator/__init__.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/views.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/models.py": ["/bigsi_aggregator/__init__.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/views.py": ["/bigsi_aggregator/helpers.py", "/bigsi_aggregator/settings.py", "/bigsi_aggregator/models.py", "/bigsi_aggregator/__init__.py"]} |
51,378 | Phelimb/bigsi-ebi-api | refs/heads/master | /bigsi_aggregator/helpers.py | from bigsi_aggregator.tasks import search_bigsi_and_update_results
class BigsiAggregator:
def __init__(self, bigsi_urls):
self.bigsi_urls = bigsi_urls
def search_and_aggregate(self, sequence_search):
for url in self.bigsi_urls:
result = search_bigsi_and_update_results.delay(url, sequence_search.id)
| {"/bigsi_aggregator/tasks.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/models.py"], "/bigsi_aggregator/helpers.py": ["/bigsi_aggregator/tasks.py"], "/bigsi_aggregator/__init__.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/views.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/models.py": ["/bigsi_aggregator/__init__.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/views.py": ["/bigsi_aggregator/helpers.py", "/bigsi_aggregator/settings.py", "/bigsi_aggregator/models.py", "/bigsi_aggregator/__init__.py"]} |
51,379 | Phelimb/bigsi-ebi-api | refs/heads/master | /bigsi_aggregator/__init__.py | from flask import Flask
from flask_cors import CORS
from flask_restful import Api
from bigsi_aggregator.extensions import celery
from bigsi_aggregator.views import SequenceSearchListResource
from bigsi_aggregator.views import SequenceSearchResource
from bigsi_aggregator.settings import REDIS_IP
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
api = Api(app)
api.add_resource(SequenceSearchListResource, "/api/v1/searches/")
api.add_resource(SequenceSearchResource, "/api/v1/searches/<sequence_search_id>")
app.config.update(
CELERY_BROKER_URL="redis://{redis_ip}:6379/1".format(redis_ip=REDIS_IP),
CELERY_RESULT_BACKEND="redis://{redis_ip}:6379/1".format(redis_ip=REDIS_IP),
CELERY_TRACK_STARTED=True,
CELERY_SEND_EVENTS=True,
)
celery.init_app(app)
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
| {"/bigsi_aggregator/tasks.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/models.py"], "/bigsi_aggregator/helpers.py": ["/bigsi_aggregator/tasks.py"], "/bigsi_aggregator/__init__.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/views.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/models.py": ["/bigsi_aggregator/__init__.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/views.py": ["/bigsi_aggregator/helpers.py", "/bigsi_aggregator/settings.py", "/bigsi_aggregator/models.py", "/bigsi_aggregator/__init__.py"]} |
51,380 | Phelimb/bigsi-ebi-api | refs/heads/master | /bigsi_aggregator/models.py | import redis
import json
from bigsi_aggregator import constants
from bigsi_aggregator.settings import REDIS_IP
import hashlib
DEFAULT_SEARCH_RESULTS_TTL = 48 * 60 * 60 # 2 days
def generate_search_key(_id):
return "sequence_search:%s" % _id
def generate_search_results_key(_id):
return "sequence_search_results:%s" % _id
r = redis.StrictRedis(REDIS_IP, decode_responses=True)
# class SequenceSearchResult:
# def __init__(self, percent_kmers_found, ):
# self.percent_kmers_found=percent_kmers_found
# self.num_kmers=percent_kmers_found
# self.num_kmers_found=percent_kmers_found
# self.sample_name=percent_kmers_found
class SequenceSearch:
def __init__(
self,
seq,
threshold,
score,
total_bigsi_queries,
results=[],
completed_bigsi_queries=0,
ttl=DEFAULT_SEARCH_RESULTS_TTL,
):
self.seq = seq
self.threshold = threshold
self.score = bool(int(score))
self.total_bigsi_queries = total_bigsi_queries
self._id = self.generate_id()
self.ttl = ttl
self.completed_bigsi_queries = completed_bigsi_queries
self.results = results
self.citation = "http://dx.doi.org/10.1038/s41587-018-0010-1"
@classmethod
def create(cls, seq, threshold, score, total_bigsi_queries):
sequence_search = cls(seq, threshold, score, total_bigsi_queries)
if r.exists(generate_search_key(sequence_search.id)):
return cls.get_by_id(sequence_search.id)
else:
sequence_search.create_cache()
sequence_search.set_ttl()
return sequence_search
@classmethod
def get_by_id(cls, _id):
search_params = r.hgetall(generate_search_key(_id))
results = r.hgetall(generate_search_results_key(_id))
results = [json.loads(s) for s in results.values()]
sequence_search = cls(**search_params, results=results)
sequence_search.set_ttl()
return sequence_search
def __dict__(self):
return {
constants.SEQUENCE_QUERY_KEY: self.seq,
constants.THRESHOLD_KEY: self.threshold,
constants.SCORE_KEY: self.score,
constants.COMPLETED_BIGSI_QUERIES_COUNT_KEY: self.completed_bigsi_queries,
constants.TOTAL_BIGSI_QUERIES_COUNT_KEY: self.total_bigsi_queries,
constants.RESULTS_KEY: self.results,
}
@property
def search_key(self):
return generate_search_key(self.id)
@property
def id(self):
return self._id
@property
def in_progress(self):
return self.completed_bigsi_queries < self.total_bigsi_queries
@property
def search_results_key(self):
return generate_search_results_key(self.id)
@property
def status(self):
if self.completed_bigsi_queries < self.total_bigsi_queries:
return "INPROGRESS"
else:
return "COMPLETE"
def set_ttl(self, ttl=DEFAULT_SEARCH_RESULTS_TTL):
r.expire(self.search_results_key, ttl)
r.expire(self.search_key, ttl)
def progress(self):
return self.completed_bigsi_queries / self.total_bigsi_queries
def create_cache(self):
search_params_key = generate_search_key(self.id)
r.hset(search_params_key, constants.SEQUENCE_QUERY_KEY, self.seq)
r.hset(search_params_key, constants.THRESHOLD_KEY, self.threshold)
r.hset(search_params_key, constants.SCORE_KEY, int(self.score))
r.hset(search_params_key, constants.COMPLETED_BIGSI_QUERIES_COUNT_KEY, 0)
r.hset(
search_params_key,
constants.TOTAL_BIGSI_QUERIES_COUNT_KEY,
self.total_bigsi_queries,
)
def generate_id(self):
string = "{seq}{threshold}{score}{total_bigsi_queries}".format(
seq=self.seq,
threshold=self.threshold,
score=int(self.score),
total_bigsi_queries=self.total_bigsi_queries,
)
_hash = hashlib.sha224(string.encode("utf-8")).hexdigest()[:24]
return _hash
def add_results(self, results):
search_results_key = generate_search_results_key(self.id)
for res in results:
r.hset(self.search_results_key, res["sample_name"], json.dumps(res))
self.incr_completed_queries()
self.set_ttl()
def incr_completed_queries(self):
r.hincrby(self.search_key, constants.COMPLETED_BIGSI_QUERIES_COUNT_KEY, 1)
| {"/bigsi_aggregator/tasks.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/models.py"], "/bigsi_aggregator/helpers.py": ["/bigsi_aggregator/tasks.py"], "/bigsi_aggregator/__init__.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/views.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/models.py": ["/bigsi_aggregator/__init__.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/views.py": ["/bigsi_aggregator/helpers.py", "/bigsi_aggregator/settings.py", "/bigsi_aggregator/models.py", "/bigsi_aggregator/__init__.py"]} |
51,381 | Phelimb/bigsi-ebi-api | refs/heads/master | /bigsi_aggregator/views.py | from flask import redirect
from flask_restful import Resource
from flask_restful import reqparse
from flask_restful import fields, marshal_with, marshal
from bigsi_aggregator.helpers import BigsiAggregator
from bigsi_aggregator.settings import BIGSI_URLS
from bigsi_aggregator.models import SequenceSearch
from bigsi_aggregator import constants
parser = reqparse.RequestParser()
parser.add_argument("seq", type=str, help="The sequence query")
parser.add_argument(
"threshold", type=int, help="The percent k-mer presence result", default=100
)
parser.add_argument("score", type=bool, help="Score the search results", default=False)
bigsi_aggregator = BigsiAggregator(BIGSI_URLS)
search_results_fields = {
"sample_name": fields.String,
"percent_kmers_found": fields.Integer,
"num_kmers_found": fields.String,
"num_kmers": fields.String,
"score": fields.Float,
"mismatches": fields.Float,
"nident": fields.Float,
"pident": fields.Float,
"length": fields.Float,
"evalue": fields.Float,
"pvalue": fields.Float,
"log_evalue": fields.Float,
"log_pvalue": fields.Float,
"kmer-presence": fields.String,
# "metadata": fields.String, ## In future, metadata associated with 'sampled_name' will be returned
}
search_fields = {
"id": fields.String,
constants.SEQUENCE_QUERY_KEY: fields.String,
constants.THRESHOLD_KEY: fields.Integer,
constants.SCORE_KEY: fields.Boolean,
constants.COMPLETED_BIGSI_QUERIES_COUNT_KEY: fields.Integer,
constants.TOTAL_BIGSI_QUERIES_COUNT_KEY: fields.Integer,
constants.RESULTS_KEY: fields.Nested(search_results_fields),
"status": fields.String,
"citation": fields.String,
}
class SequenceSearchListResource(Resource):
def post(self):
args = parser.parse_args()
sequence_search = SequenceSearch.create(
**args, total_bigsi_queries=len(BIGSI_URLS)
)
## results are stored in the sequence search object
bigsi_aggregator.search_and_aggregate(sequence_search)
return marshal(sequence_search, search_fields), 201
class SequenceSearchResource(Resource):
@marshal_with(search_fields)
def get(self, sequence_search_id):
return SequenceSearch.get_by_id(sequence_search_id)
| {"/bigsi_aggregator/tasks.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/models.py"], "/bigsi_aggregator/helpers.py": ["/bigsi_aggregator/tasks.py"], "/bigsi_aggregator/__init__.py": ["/bigsi_aggregator/extensions.py", "/bigsi_aggregator/views.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/models.py": ["/bigsi_aggregator/__init__.py", "/bigsi_aggregator/settings.py"], "/bigsi_aggregator/views.py": ["/bigsi_aggregator/helpers.py", "/bigsi_aggregator/settings.py", "/bigsi_aggregator/models.py", "/bigsi_aggregator/__init__.py"]} |
51,385 | FDUSoftware2020/backend | refs/heads/master | /issue/migrations/0001_initial.py | # Generated by Django 3.0.3 on 2020-04-30 08:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('account', '0004_auto_20200430_1627'),
]
operations = [
migrations.CreateModel(
name='Issue',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Type', models.IntegerField(choices=[(0, 'Issue'), (1, 'Article')])),
('title', models.CharField(max_length=100)),
('pub_date', models.DateTimeField()),
('content', models.TextField()),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='account.User')),
('liker', models.ManyToManyField(related_name='issue_liker', to='account.User')),
],
),
migrations.CreateModel(
name='IssueCollection',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('collector', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='account.User')),
('issue', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='issue.Issue')),
],
),
migrations.CreateModel(
name='Answer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('pub_date', models.DateTimeField()),
('content', models.TextField()),
('issue', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='issue.Issue')),
('liker', models.ManyToManyField(related_name='answer_liker', to='account.User')),
('replier', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='account.User')),
],
),
]
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,386 | FDUSoftware2020/backend | refs/heads/master | /issue/migrations/0003_auto_20200505_1435.py | # Generated by Django 3.0.3 on 2020-05-05 06:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0004_auto_20200430_1627'),
('issue', '0002_auto_20200430_2111'),
]
operations = [
migrations.AlterField(
model_name='answer',
name='likers',
field=models.ManyToManyField(related_name='like_answer', to='account.User'),
),
migrations.AlterField(
model_name='issue',
name='collectors',
field=models.ManyToManyField(related_name='collect_issue', to='account.User'),
),
migrations.AlterField(
model_name='issue',
name='likers',
field=models.ManyToManyField(related_name='like_issue', to='account.User'),
),
]
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,387 | FDUSoftware2020/backend | refs/heads/master | /account/models.py | from django.db import models
# Create your models here.
class User(models.Model):
''' 用户类
'''
username = models.CharField(max_length=100, unique=True) # 用户名
email = models.CharField(max_length=100, unique=True) # 学邮
password = models.CharField(max_length=100, default="") # 密码
cookie_value = models.CharField(max_length=200 , default="") # cookie值
signature = models.TextField(default="他(她)什么也没留下~") # 个性签名
contribution = models.PositiveIntegerField(default=0) # 贡献值
def __str__(self):
return self.username
class VerificationCode(models.Model):
''' 验证码类
'''
email = models.CharField(max_length=100, unique=True) # 邮箱
code = models.CharField(max_length=4, default="") # 验证码
make_time = models.DateTimeField() # 验证码生成时刻
def __str__(self):
return str(self.id)
class Message(models.Model):
''' 消息通知类
'''
class MsgType(models.IntegerChoices):
AnswerToIssue = 0
CommentToArticle = 1
CommentToAnswer = 2
Type = models.IntegerField(choices=MsgType.choices)
issue_id = models.IntegerField()
answer_id = models.IntegerField()
parent_comment_id = models.IntegerField()
comment_id = models.IntegerField()
from_uname = models.CharField(max_length=100, default="无名氏")
receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rec_msg')
pub_date = models.DateTimeField()
content = models.TextField()
IsReading = models.BooleanField(default=False)
def __str__(self):
return str(self.id) | {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,388 | FDUSoftware2020/backend | refs/heads/master | /issue/admin.py | from django.contrib import admin
from .models import Issue, Answer
# Register your models here.
class AnswerInline(admin.TabularInline):
model = Answer
fields = ['replier', 'pub_date', 'content']
extra = 0
class IssueAdmin(admin.ModelAdmin):
# add list at the admin site
list_display = ('Type', 'title', 'author', 'pub_date')
# add search option at the admin site
search_fields = ['title']
# classify the infomation of articles
fieldsets = [
('Basic Information', {'fields': ['Type', 'title', 'author', 'pub_date']}),
('Content information', {'fields': ['content'], 'classes': ['collapse']}),
]
# add choices at the bottom
inlines = [AnswerInline]
# register Article
admin.site.register(Issue, IssueAdmin) | {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,389 | FDUSoftware2020/backend | refs/heads/master | /image/urls.py | from django.urls import path
from . import views
app_name = 'image'
urlpatterns = [
# ex: /image/upload/
path('upload/', views.upload, name='upload'),
] | {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,390 | FDUSoftware2020/backend | refs/heads/master | /issue/migrations/0004_auto_20200505_1445.py | # Generated by Django 3.0.3 on 2020-05-05 06:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('account', '0004_auto_20200430_1627'),
('issue', '0003_auto_20200505_1435'),
]
operations = [
migrations.AlterField(
model_name='issue',
name='author',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='create_issue', to='account.User'),
),
]
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,391 | FDUSoftware2020/backend | refs/heads/master | /comment/urls.py | from django.urls import path
from . import views
app_name = 'comment'
urlpatterns = [
# ex: /comment/create/
path('create/', views.comment_create, name='comment_create'),
# ex: /comment/2/delete/
path('<int:comment_id>/delete/', views.comment_delete, name='comment_delete'),
# ex: /comment/2/detail/
path('<int:comment_id>/detail/', views.comment_detail, name='comment_detail'),
# ex: /comment/list/
path('list/', views.comment_list, name='comment_list'),
# ex: /comment/3/like/
path('<int:comment_id>/like/', views.comment_like, name='comment_like'),
] | {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,392 | FDUSoftware2020/backend | refs/heads/master | /issue/models.py | from django.db import models
# Create your models here.
class Issue(models.Model):
''' 定义Issue类
'''
class IssueType(models.IntegerChoices):
ISSUE = 0
ARTICLE = 1
Type = models.IntegerField(choices=IssueType.choices) # 类型, issue or article
title = models.CharField(max_length=100) # 标题
author = models.ForeignKey('account.User', on_delete=models.CASCADE, related_name='create_issue') # 作者
pub_date = models.DateTimeField() # 发布时间
content = models.TextField() # 详细内容
collectors = models.ManyToManyField('account.User', related_name='collect_issue') # 收藏者
likers = models.ManyToManyField('account.User', related_name='like_issue') # 点赞者
def __str__(self):
return str(self.id)
class Answer(models.Model):
''' 定义Answer类,即对Issue的回答
'''
issue = models.ForeignKey(Issue, on_delete=models.CASCADE) # 回答的Isssue
replier = models.ForeignKey('account.User', on_delete=models.CASCADE) # 回答者
pub_date = models.DateTimeField() # 回答时间
content = models.TextField() # 回答的内容
likers = models.ManyToManyField('account.User', related_name='like_answer') # 点赞者
def __str__(self):
return str(self.id)
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,393 | FDUSoftware2020/backend | refs/heads/master | /account/migrations/0003_auto_20200424_1657.py | # Generated by Django 3.0.3 on 2020-04-24 08:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0002_auto_20200327_1541'),
]
operations = [
migrations.AddField(
model_name='user',
name='contribution',
field=models.PositiveIntegerField(default=0),
),
migrations.AddField(
model_name='user',
name='signature',
field=models.TextField(default='他/她什么也没留下~'),
),
]
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,394 | FDUSoftware2020/backend | refs/heads/master | /issue/urls.py | from django.urls import path
from . import views
app_name = 'issue'
urlpatterns = [
# ex: /issue/create/
path('create/', views.issue_create, name='issue_create'),
# ex: /issue/2/delete/
path('<int:issue_id>/delete/', views.issue_delete, name='issue_delete'),
# ex: /issue/2/detail/
path('<int:issue_id>/detail/', views.issue_detail, name='issue_detail'),
# ex: /issue/search/
path('search/', views.issue_search, name='issue_search'),
# ex: /issue/2/collect/
path('<int:issue_id>/collect/', views.issue_collect, name='issue_collect'),
# ex: /issue/collection_list/
path('collection_list/', views.issue_collection_list, name='issue_collection_list'),
# ex: /issue/publication_list/
path('publication_list/', views.issue_publication_list, name='issue_publication_list'),
# ex: /issue/2/like/
path('<int:issue_id>/like/', views.issue_like, name='issue_like'),
# ex: /issue/2/answer/create/
path('<int:issue_id>/answer/create/', views.answer_create, name='answer_create'),
# ex: /issue/answer/3/delete/
path('answer/<int:answer_id>/delete/', views.answer_delete, name='answer_delete'),
# ex: /issue/answer/3/detail/
path('answer/<int:answer_id>/detail/', views.answer_detail, name='answer_detail'),
# ex: /issue/2/answer_list/
path('<int:issue_id>/answer_list/', views.answer_list, name='answer_list'),
# ex: /issue/answer/3/like/
path('answer/<int:answer_id>/like/', views.answer_like, name='answer_like'),
] | {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,395 | FDUSoftware2020/backend | refs/heads/master | /comment/models.py | from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
# Create your models here.
class Comment(models.Model):
"""
Define Comment Model, Level 1.
"""
from_id = models.ForeignKey('account.User', on_delete=models.CASCADE, related_name="from_user")
to_id = models.ForeignKey('account.User', on_delete=models.CASCADE, related_name="to_user")
pub_date = models.DateTimeField() # comment publish time
content = models.TextField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # the type of the object it belongs to.
object_id = models.PositiveIntegerField() # answer id / article id / issue id
content_object = GenericForeignKey('content_type', 'object_id')
parent_comment = models.ForeignKey('self', on_delete=models.CASCADE, null=True) #record the parent comment. if it's level 1 comment. it should be null.
likers = models.ManyToManyField('account.User', related_name='comment_liker')
def __str__(self):
return str(self.id) | {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,396 | FDUSoftware2020/backend | refs/heads/master | /account/migrations/0004_auto_20200430_1627.py | # Generated by Django 3.0.3 on 2020-04-30 08:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0003_auto_20200424_1657'),
]
operations = [
migrations.AlterField(
model_name='user',
name='signature',
field=models.TextField(default='他(她)什么也没留下~'),
),
]
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,397 | FDUSoftware2020/backend | refs/heads/master | /image/views.py | import os
import json
from django.utils import timezone
from django.http import HttpResponse
from django.utils import timezone
from django.conf import settings
from account.models import User
# Create your views here.
# HOST = "http://127.0.0.1:8000"
HOST = "http://182.92.131.202:8000"
def upload(request):
''' 图片上传
'''
if request.method == "POST":
user = backend_ask_login_user(request)
if not user:
response_content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
files_list = request.FILES
index_list = files_list.keys()
url_list = {}
for img_index in index_list:
img_file = files_list[img_index]
img_name = timezone.now().strftime('%Y%M%d%H%M%S%f') + ".jpg"
if all([img_index, img_file]):
f = open(os.path.join(settings.UPLOAD_ROOT, img_name), 'wb')
for i in img_file.chunks():
f.write(i)
f.close()
img_url = HOST + "/uploads/" + img_name
url_list[img_index] = img_url
response_content = {"err_code":0, "message":"图片上传成功", "data":url_list}
else:
response_content = {"err_code":-1, "message":"请求方式错误", "data":None}
return HttpResponse(json.dumps(response_content))
# some assist functions
def backend_ask_login_user(request):
''' 查询当前登录用户,仅用于后端处理
Return:
已登录时,返回登录对象即an object of class User;
未登录时,返回None
'''
cookie_value = request.COOKIES.get("cookie_value")
if not cookie_value:
return None
else:
if not User.objects.filter(cookie_value=cookie_value).exists():
return None
else:
return User.objects.filter(cookie_value=cookie_value)[0]
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,398 | FDUSoftware2020/backend | refs/heads/master | /account/migrations/0002_auto_20200327_1541.py | # Generated by Django 3.0.3 on 2020-03-27 07:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='VerificationCode',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('email', models.CharField(max_length=100, unique=True)),
('code', models.CharField(default='', max_length=4)),
('make_time', models.DateTimeField()),
],
),
migrations.AlterField(
model_name='user',
name='email',
field=models.CharField(max_length=100, unique=True),
),
migrations.AlterField(
model_name='user',
name='password',
field=models.CharField(default='', max_length=100),
),
migrations.AlterField(
model_name='user',
name='username',
field=models.CharField(max_length=100, unique=True),
),
]
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,399 | FDUSoftware2020/backend | refs/heads/master | /account/migrations/0005_message.py | # Generated by Django 3.0.3 on 2020-06-07 06:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('account', '0004_auto_20200430_1627'),
]
operations = [
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Type', models.IntegerField(choices=[(0, 'Answertoissue'), (1, 'Commenttoarticle'), (2, 'Commenttoanswer')])),
('issue_id', models.IntegerField()),
('answer_id', models.IntegerField()),
('parent_comment_id', models.IntegerField()),
('comment_id', models.IntegerField()),
('from_uname', models.CharField(default='无名氏', max_length=100)),
('pub_date', models.DateTimeField()),
('content', models.TextField()),
('IsReading', models.BooleanField(default=False)),
('receiver', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rec_mes', to='account.User')),
],
),
]
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,400 | FDUSoftware2020/backend | refs/heads/master | /issue/views.py | import json
from django.http import HttpResponse
from django.utils import timezone
from .models import Issue, Answer
from account.models import User, Message
from comment.models import Comment
from account.utils.message import create_message
# Create your views here.
def issue_create(request):
''' 创建一个新Issue
'''
if request.method == "POST":
data = json.loads(request.body)
Type = int(data.get("type"))
title = data.get("title")
author = backend_ask_login_user(request)
pub_date = timezone.now()
content = data.get("content")
if not author:
response_content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
issue = Issue(Type=Type, title=title, author=author, pub_date=pub_date, content=content)
issue.save()
response_content = {"err_code":0, "message":"发布成功", "data":issue.id}
else:
response_content = {"err_code":-1, "message":"请求方式错误", "data":None}
return HttpResponse(json.dumps(response_content))
def issue_delete(request, issue_id):
''' 删除某个Issue
'''
user = backend_ask_login_user(request)
if not user:
response_content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
try:
issue = Issue.objects.get(id=issue_id)
if issue.author == user:
issue.delete()
response_content = {"err_code":0, "message":"删除成功", "data":None}
else:
response_content = {"err_code":-1, "message":"您不是发布者,无法删除", "data":None}
except Issue.DoesNotExist:
response_content = {"err_code":-1, "message":"该问题/文章不存在", "data":None}
return HttpResponse(json.dumps(response_content))
def issue_detail(request, issue_id):
''' 显示某个Issue的详细内容
'''
try:
issue = Issue.objects.get(id=issue_id)
user = backend_ask_login_user(request)
obj = conduct_issue(issue, user)
response_content = {"err_code":0, "message":"查询成功", "data":obj}
except Issue.DoesNotExist:
response_content = {"err_code":-1, "message":"该问题/文章不存在", "data":None}
return HttpResponse(json.dumps(response_content))
def issue_search(request):
''' 搜寻Issue
'''
if request.method == "POST":
data = json.loads(request.body)
keyword = data.get("keyword")
issue_list = Issue.objects.filter(title__icontains=keyword).order_by('title')
user = backend_ask_login_user(request)
obj_list = []
for issue in issue_list:
obj = conduct_issue(issue, user, brief=True)
obj_list.append(obj)
response_content = {"err_code":0, "message":"查询成功", "data":obj_list}
else:
response_content = {"err_code":-1, "message":"请求方式错误", "data":None}
return HttpResponse(json.dumps(response_content))
def issue_collect(request, issue_id):
'''收藏或取消收藏某个Issue
'''
user = backend_ask_login_user(request)
if not user:
response_content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
try:
issue = Issue.objects.get(id=issue_id)
if len(issue.collectors.filter(id=user.id)) != 0:
issue.collectors.remove(user)
response_content = {"err_code":0, "message":"已取消收藏", "data":None}
else:
issue.collectors.add(user)
response_content = {"err_code":0, "message":"收藏成功", "data":None}
except Issue.DoesNotExist:
response_content = {"err_code":-1, "message":"该问题/文章不存在", "data":None}
return HttpResponse(json.dumps(response_content))
def issue_collection_list(request):
''' 获取登录用户的收藏列表
'''
user = backend_ask_login_user(request)
if not user:
response_content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
obj_list = []
for issue in user.collect_issue.all().order_by('title'):
obj = conduct_issue(issue, user, brief=True)
obj_list.append(obj)
response_content = {"err_code":0, "message":"查询成功", "data":obj_list}
return HttpResponse(json.dumps(response_content))
def issue_publication_list(request):
''' 获取登录用户的发布列表
'''
user = backend_ask_login_user(request)
if not user:
response_content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
obj_list = []
for issue in user.create_issue.all().order_by('title'):
obj = conduct_issue(issue, user, brief=True)
obj_list.append(obj)
response_content = {"err_code":0, "message":"查询成功", "data":obj_list}
return HttpResponse(json.dumps(response_content))
def issue_like(request, issue_id):
''' 对某个Issue点赞/取消点赞
'''
user = backend_ask_login_user(request)
if not user:
response_content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
try:
issue = Issue.objects.get(id=issue_id)
if len(issue.likers.filter(id=user.id)) != 0:
issue.likers.remove(user)
response_content = {"err_code":0, "message":"已取消点赞", "data":None}
else:
issue.likers.add(user)
response_content = {"err_code":0, "message":"点赞成功", "data":None}
except Issue.DoesNotExist:
response_content = {"err_code":-1, "message":"该问题/文章不存在", "data":None}
return HttpResponse(json.dumps(response_content))
def answer_create(request, issue_id):
''' 对某个Issue新建一个回答
'''
if request.method == "POST":
data = json.loads(request.body)
content = data.get("content")
user = backend_ask_login_user(request)
if not user:
response_content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
try:
issue = Issue.objects.get(id=issue_id)
if issue.Type != Issue.IssueType.ISSUE:
response_content = {"err_code":-1, "message":"无法对文章进行回答", "data":None}
else:
answer = Answer(issue=issue, replier=user, pub_date=timezone.now(), content=content)
answer.save()
create_message(Message.MsgType.AnswerToIssue, answer)
response_content = {"err_code":0, "message":"回答已发布", "data":None}
except Issue.DoesNotExist:
response_content = {"err_code":-1, "message":"该问题不存在", "data":None}
else:
response_content = {"err_code":-1, "message":"请求方式错误", "data":None}
return HttpResponse(json.dumps(response_content))
def answer_delete(request, answer_id):
''' 删除某个answer
'''
user = backend_ask_login_user(request)
if not user:
response_content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
try:
answer = Answer.objects.get(id=answer_id)
if answer.replier == user:
answer.delete()
response_content = {"err_code":0, "message":"回答已删除", "data":None}
else:
response_content = {"err_code":-1, "message":"您不是该回答的发布者,无法删除", "data":None}
except Answer.DoesNotExist:
response_content = {"err_code":-1, "message":"该回答不存在", "data":None}
return HttpResponse(json.dumps(response_content))
def answer_detail(request, answer_id):
''' 获取某个Answer的详细数据
'''
try:
answer = Answer.objects.get(id=answer_id)
user = backend_ask_login_user(request)
obj = conduct_detail_answer(answer, user)
response_content = {"err_code":0, "message":"查询成功", "data":obj}
except Answer.DoesNotExist:
response_content = {"err_code":-1, "message":"该回答不存在", "data":None}
return HttpResponse(json.dumps(response_content))
def answer_list(request, issue_id):
''' 获取某个Issue的回答列表
'''
try:
issue = Issue.objects.get(id=issue_id)
user = backend_ask_login_user(request)
obj_list = []
for answer in issue.answer_set.all().order_by("-pub_date"):
obj = conduct_detail_answer(answer, user)
obj_list.append(obj)
response_content = {"err_code":0, "message":"查询成功", "data":obj_list}
except Issue.DoesNotExist:
response_content = {"err_code":-1, "message":"该问题不存在", "data":None}
return HttpResponse(json.dumps(response_content))
def answer_like(request, answer_id):
''' 对某个回答点赞/取消点赞
'''
try:
answer = Answer.objects.get(id=answer_id)
user = backend_ask_login_user(request)
if not user:
response_content = {"err_code":-1, "message":"当前未登录", "data":None}
elif len(answer.likers.filter(id=user.id)) == 0 :
answer.likers.add(user)
response_content = {"err_code":0, "message":"点赞成功", "data":None}
else:
answer.likers.remove(user)
response_content = {"err_code":0, "message":"已取消点赞", "data":None}
except Answer.DoesNotExist:
response_content = {"err_code":-1, "message":"该回答不存在", "data":None}
return HttpResponse(json.dumps(response_content))
# some assist functions
def backend_ask_login_user(request):
''' 查询当前登录用户,仅用于后端处理
Return:
已登录时,返回登录对象即an object of class User;
未登录时,返回None
'''
cookie_value = request.COOKIES.get("cookie_value")
if not cookie_value:
return None
else:
if not User.objects.filter(cookie_value=cookie_value).exists():
return None
else:
return User.objects.filter(cookie_value=cookie_value)[0]
def conduct_issue(issue, user, brief=False):
''' 构造Issue实例,其中brief控制是否是简洁版
'''
# static data
ID = issue.id
Type = issue.Type
title = issue.title
author = issue.author.username
pub_date = str(issue.pub_date)[0:16]
if brief:
content = issue.content[0:50] + "......"
else:
content = issue.content
collect_num = issue.collectors.count()
like_num = issue.likers.count()
# dynamic data
if not user:
IsCollecting = False
IsLiking = False
else:
IsCollecting = not (len(issue.collectors.filter(id=user.id)) == 0)
IsLiking = not (len(issue.likers.filter(id=user.id)) == 0)
return {"id":ID, "type":Type, "title":title, "author":author, "pub_date":pub_date, "content":content, \
"collect_num":collect_num, "like_num":like_num, "IsCollecting":IsCollecting, "IsLiking":IsLiking}
def compute_comment_num_of_answer(answer):
''' 统计an answer下的评论数目
'''
C1_list = Comment.objects.filter(object_id=answer.id)
comment_num = len(C1_list)
for c1 in C1_list:
comment_num += Comment.objects.filter(parent_comment=c1.id).count()
return comment_num
def conduct_detail_answer(answer, user):
''' 构造详细版Answer实例
'''
ID = answer.id
author = answer.replier.username
pub_date = str(answer.pub_date)[0:16]
content = answer.content
like_num = answer.likers.count()
if not user:
IsLiking = False
else:
IsLiking = not (len(answer.likers.filter(id=user.id)) == 0)
comment_num = compute_comment_num_of_answer(answer)
return {"id":ID, "author":author, "pub_date":pub_date, "content":content, \
"like_num":like_num, "IsLiking":IsLiking, "comment_num":comment_num} | {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,401 | FDUSoftware2020/backend | refs/heads/master | /account/urls.py | from django.urls import path
from . import views
app_name = 'account'
urlpatterns = [
# ex: /account/register
path('register/', views.register, name='register'),
# ex: /account/login
path('login/', views.login, name='login'),
# ex: /account/logout
path('logout/', views.logout, name='logout'),
# ex: /account/verify
path('verify/', views.verify, name='verify'),
# ex: /account/modify_password
path('modify_password/', views.modify_password, name='modify_password'),
# ex: /account/modify_username
path('modify_username/', views.modify_username, name='modify_username'),
# ex: /account/modify_signature
path('modify_signature/', views.modify_signature, name='modify_signature'),
# ex: /account/ask_login_user
path('ask_login_user/', views.ask_login_user, name='ask_login_user'),
# ex: /account/ask_user
path('ask_user/', views.ask_user, name='ask_user'),
# ex: /account/message/list
path('message/list/', views.message_list, name='msg_list'),
# ex: /account/message/3/read
path('message/<int:msg_id>/read/', views.message_read, name='msg_read'),
# ex: /account/message/4/delete
path('message/<int:msg_id>/delete/', views.message_delete, name='msg_del'),
] | {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,402 | FDUSoftware2020/backend | refs/heads/master | /account/migrations/0006_auto_20200607_1455.py | # Generated by Django 3.0.3 on 2020-06-07 06:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('account', '0005_message'),
]
operations = [
migrations.AlterField(
model_name='message',
name='receiver',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rec_msg', to='account.User'),
),
]
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,403 | FDUSoftware2020/backend | refs/heads/master | /account/utils/verification.py | from ..models import VerificationCode
def make_verification_code():
''' 随机生成4位验证码
'''
code = ""
for i in range(4):
code += str(random.randint(0, 9))
return code
def save_verification_code(email, code):
''' 保存验证码,email不可为空
'''
if not VerificationCode.objects.filter(email=email).exists():
VerificationCode.objects.create(email=email, code=code, make_time=timezone.now())
else:
obj = VerificationCode.objects.filter(email=email)[0]
obj.code = code
obj.make_time = timezone.now()
obj.save()
def check_verification_code(email, code):
''' 核对验证码
Returns:
If the code is error or out of date, return false; otherwise, return true
'''
if not VerificationCode.objects.filter(email=email).exists():
return False
else:
obj = VerificationCode.objects.filter(email=email)[0]
if obj.code != code or timezone.now() > obj.make_time + datetime.timedelta(minutes=10):
return False
else:
return True
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,404 | FDUSoftware2020/backend | refs/heads/master | /issue/migrations/0002_auto_20200430_2111.py | # Generated by Django 3.0.3 on 2020-04-30 13:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0004_auto_20200430_1627'),
('issue', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='answer',
old_name='liker',
new_name='likers',
),
migrations.RenameField(
model_name='issue',
old_name='liker',
new_name='likers',
),
migrations.AddField(
model_name='issue',
name='collectors',
field=models.ManyToManyField(related_name='issue_collector', to='account.User'),
),
migrations.DeleteModel(
name='IssueCollection',
),
]
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,405 | FDUSoftware2020/backend | refs/heads/master | /comment/migrations/0001_initial.py | # Generated by Django 3.0.4 on 2020-05-04 09:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('account', '0004_auto_20200430_1627'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('pub_date', models.DateTimeField()),
('content', models.TextField()),
('object_id', models.PositiveIntegerField()),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
('from_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='from_user', to='account.User')),
('likers', models.ManyToManyField(related_name='comment_liker', to='account.User')),
('parent_comment', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='comment.Comment')),
('to_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='to_user', to='account.User')),
],
),
]
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,406 | FDUSoftware2020/backend | refs/heads/master | /account/utils/message.py | from ..models import User, Message
from issue.models import Issue, Answer
from comment.models import Comment
def create_message(Type, obj):
''' 创建message,有如下三大类情况:
1)问题新增回答:obj是Answer实例
2)文章新增评论:obj是Comment实例
3)回答新增评论:obj是Comment实例
'''
if Type == Message.MsgType.AnswerToIssue:
content = "在帖子<" + str(obj.issue.title) + '>下,新增一条回答'
Message.objects.create(Type=Message.MsgType.AnswerToIssue, \
issue_id=obj.issue.id, answer_id=obj.id, parent_comment_id=-1, comment_id=-1, \
from_uname = obj.replier.username, receiver=obj.issue.author, \
pub_date=obj.pub_date, content=content, IsReading=False)
elif Type == Message.MsgType.CommentToArticle:
if not obj.parent_comment:
issue = obj.content_object
content = "在文章<" + str(issue.title) + ">下,新增一条评论"
Message.objects.create(Type=Message.MsgType.CommentToArticle, \
issue_id=issue.id, answer_id=-1, parent_comment_id=-1, comment_id=obj.id, \
from_uname = obj.from_id.username, receiver=obj.to_id, \
pub_date=obj.pub_date, content=content, IsReading=False)
else:
issue = obj.parent_comment.content_object
content = "在文章<" + str(issue.title) + '>下,对您的评论新增回复'
Message.objects.create(Type=Message.MsgType.CommentToArticle, \
issue_id=issue.id, answer_id=-1, parent_comment_id=obj.parent_comment.id, comment_id=obj.id, \
from_uname = obj.from_id.username, receiver=obj.to_id, \
pub_date=obj.pub_date, content=content, IsReading=False)
elif Type == Message.MsgType.CommentToAnswer:
if not obj.parent_comment:
answer = obj.content_object
content = "在帖子<" + str(answer.issue.title) + '>的回答下,新增一条评论'
Message.objects.create(Type=Message.MsgType.CommentToAnswer, \
issue_id=answer.issue.id, answer_id=answer.id, parent_comment_id=-1, comment_id=obj.id, \
from_uname=obj.from_id.username, receiver=obj.to_id, \
pub_date=obj.pub_date, content=content, IsReading=False)
else:
answer = obj.parent_comment.content_object
content = "在帖子<" + str(answer.issue.title) + '>的回答下,对您的评论新增回复'
Message.objects.create(Type=Message.MsgType.CommentToAnswer, \
issue_id=answer.issue.id, answer_id=answer.id, parent_comment_id=obj.parent_comment.id, comment_id=obj.id, \
from_uname=obj.from_id.username, receiver=obj.to_id, \
pub_date=obj.pub_date, content=content, IsReading=False)
def conduct_message(msg):
''' 从真实的Message实例中,构造反馈给前端的消息体obj
'''
return {"msg_id":msg.id, "type":msg.Type, \
"issue_id":msg.issue_id, "answer_id":msg.answer_id, \
"parent_comment_id":msg.parent_comment_id, "comment_id":msg.comment_id, \
"from":msg.from_uname, "pub_date":str(msg.pub_date)[0:16], \
"content":msg.content, "IsReading":msg.IsReading}
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,407 | FDUSoftware2020/backend | refs/heads/master | /comment/views.py | from django.shortcuts import render
import json
from django.http import HttpResponse
from django.utils import timezone
from django.contrib.contenttypes.models import ContentType
from account.models import User, Message
from issue.models import Issue, Answer
from .models import Comment
from account.utils.message import create_message
# Create your views here.
def comment_create(request):
"""
new comment.
"""
if request.method == "POST":
data = json.loads(request.body)
from_user = backend_ask_login_user(request)
pub_date = timezone.now()
if not from_user:
response_content = {"err_code": -1, "message": "当前未登录", "data": None}
else:
type = int(data.get("target_type"))
object_id = int(data.get("target_id"))
to_user = None
content_object = None
parent_comment_id = int(data.get("parent_comment_id"))
if parent_comment_id == -1:
parent_comment = None
else:
parent_comment = Comment.objects.get(id=parent_comment_id)
if type == 1: # article
content_object = Issue.objects.get(id=object_id)
to_user = content_object.author
elif type == 2: # answer
content_object = Answer.objects.get(id=object_id)
to_user = content_object.replier
elif type == 3:
content_object = Comment.objects.get(id=object_id)
to_user = content_object.from_id
content = data.get("content")
comment = Comment(from_id=from_user, to_id=to_user, pub_date=pub_date, content=content,
content_object=content_object, parent_comment=parent_comment)
comment.save()
create_message_for_comment(type, comment)
response_content = {"err_code": 0, "message": "发布成功", "data": None}
else:
response_content = {"err_code": -1, "message": "请求方式错误", "data": None}
return HttpResponse(json.dumps(response_content))
def comment_delete(request, comment_id):
"""
delete one comment by id
:param request:
:param comment_id:
:return:
"""
user = backend_ask_login_user(request)
if not user:
response_content = {"err_code": -1, "message": "当前未登录", "data": None}
else:
try:
comment = Comment.objects.get(id=comment_id)
if comment.from_id == user:
comment.delete()
response_content = {"err_code": 0, "message": "删除成功", "data": None}
else:
response_content = {"err_code": -1, "message": "您不是发布者,无法删除", "data": None}
except Comment.DoesNotExist:
response_content = {"err_code": -1, "message": "该评论不存在", "data": None}
return HttpResponse(json.dumps(response_content))
def comment_detail(request, comment_id):
"""
Display the detail of a comment.
:param request:
:param comment_id:
:return:
"""
try:
comment = Comment.objects.get(id=comment_id)
user = backend_ask_login_user(request)
obj = conduct_detail_comment(comment, user)
response_content = {"err_code": 0, "message": "查询成功", "data": obj}
except Comment.DoesNotExist:
response_content = {"err_code": -1, "message": "该评论不存在", "data": None}
return HttpResponse(json.dumps(response_content))
def comment_list(request):
"""
fetch all comments of a target(article, answer, even comment)
:param request:
:param target_id:
:return:
"""
if request.method == "POST":
data = json.loads(request.body)
target_type = int(data.get("target_type"))
target_id = int(data.get("target_id"))
issue_ct = ContentType.objects.get_for_model(Issue)
answer_ct = ContentType.objects.get_for_model(Answer)
if target_type == 1:
try:
user = backend_ask_login_user(request)
obj_list = []
for comment in Comment.objects.filter(content_type=issue_ct, object_id=target_id).order_by("-pub_date"):
obj = conduct_detail_comment(comment, user)
obj_list.append(obj)
response_content = {"err_code": 0, "message": "查询成功", "data": obj_list}
except Issue.DoesNotExist:
response_content = {"err_code": -1, "message": "该文章不存在", "data": None}
elif target_type == 2:
try:
user = backend_ask_login_user(request)
obj_list = []
for comment in Comment.objects.filter(content_type=answer_ct, object_id=target_id).order_by("-pub_date"):
obj = conduct_detail_comment(comment, user)
obj_list.append(obj)
response_content = {"err_code": 0, "message": "查询成功", "data": obj_list}
except Answer.DoesNotExist:
response_content = {"err_code": -1, "message": "该回答不存在", "data": None}
elif target_type == 3:
try:
user = backend_ask_login_user(request)
obj_list = []
for comment in Comment.objects.filter(parent_comment=target_id).order_by("-pub_date"):
obj = conduct_detail_comment(comment, user)
obj_list.append(obj)
response_content = {"err_code": 0, "message": "查询成功", "data": obj_list}
except Comment.DoesNotExist:
response_content = {"err_code": -1, "message": "该评论不存在", "data": None}
else:
response_content = {"err_code": -1, "message": "查询错误", "data": None}
else:
response_content = {"err_code": -1, "message": "请求方式错误", "data": None}
return HttpResponse(json.dumps(response_content))
def comment_like(request, comment_id):
"""
like or dislike a comment
:param request:
:param comment_id:
:return:
"""
try:
comment = Comment.objects.get(id=comment_id)
user = backend_ask_login_user(request)
if not user:
response_content = {"err_code": -1, "message": "当前未登录", "data": None}
elif len(comment.likers.filter(id=user.id)) == 0:
comment.likers.add(user)
response_content = {"err_code": 0, "message": "点赞成功", "data": None}
else:
comment.likers.remove(user)
response_content = {"err_code": 0, "message": "已取消点赞", "data": None}
except Comment.DoesNotExist:
response_content = {"err_code": -1, "message": "该评论不存在", "data": None}
return HttpResponse(json.dumps(response_content))
# some assist functions
def backend_ask_login_user(request):
''' 查询当前登录用户,仅用于后端处理
Return:
已登录时,返回登录对象即an object of class User;
未登录时,返回None
'''
cookie_value = request.COOKIES.get("cookie_value")
if not cookie_value:
return None
else:
if not User.objects.filter(cookie_value=cookie_value).exists():
return None
else:
return User.objects.filter(cookie_value=cookie_value)[0]
def conduct_detail_comment(comment, user):
"""
Conduct detail comment instance.
:param comment:
:param user:
:return:
"""
id = comment.id
from_user_name = comment.from_id.username
to_user_name = comment.to_id.username
pub_date = str(comment.pub_date)
content = comment.content
like_num = comment.likers.count()
if not user:
IsLiking = False
else:
IsLiking = not (len(comment.likers.filter(id=user.id)) == 0)
return {
"id": id,
"from": from_user_name,
"to": to_user_name,
"pub_date": pub_date,
"content": content,
"like_num": like_num,
"IsLiking": IsLiking,
}
def create_message_for_comment(Type, comment):
''' 为评论新建通知消息
Arguments:
Type: 1, 对文章添加评论;2,对回答添加评论;3,对评论添加评论
'''
issue_ct = ContentType.objects.get_for_model(Issue)
answer_ct = ContentType.objects.get_for_model(Answer)
if comment.content_type == issue_ct:
create_message(Message.MsgType.CommentToArticle, comment)
elif comment.content_type == answer_ct:
create_message(Message.MsgType.CommentToAnswer, comment)
elif comment.parent_comment:
if comment.parent_comment.content_type == issue_ct:
create_message(Message.MsgType.CommentToArticle, comment)
elif comment.parent_comment.content_type == answer_ct:
create_message(Message.MsgType.CommentToAnswer, comment)
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,408 | FDUSoftware2020/backend | refs/heads/master | /account/views.py | import json, random, datetime
from django.shortcuts import render
from django.http import HttpResponse
from django.core.mail import send_mail
from django.utils import timezone
from .models import User, VerificationCode, Message
from .utils.verification import make_verification_code, check_verification_code, save_verification_code
from .utils.message import conduct_message
# Create your views here.
def register(request):
''' 实现用户注册功能,须以POST方式
Arguments:
request: It should contains {"username":<str>, "email":<str>, "password":<str>, "verification":<str>} in the body.
Return:
An HttpRepsonse, which contains {"err_code":<int>, "message":<str>, "data":None}
'''
if request.method == "POST":
data = json.loads(request.body)
username = data.get("username")
email = data.get("email")
password = data.get("password")
code = data.get("verification")
# try registering
if username == "" or email == "" or password == "" or code == "":
content = {"err_code":-1, "message":"用户名、邮箱、密码或验证码为空", "data":None}
elif User.objects.filter(username=username).exists():
content = {"err_code":-1, "message":"该用户名已存在", "data":None}
elif User.objects.filter(email=email).exists():
content = {"err_code":-1, "message":"该邮箱已被注册", "data":None}
elif not check_verification_code(email, code):
content = {"err_code":-1, "message":"验证码错误或已过期", "date":None}
else:
User.objects.create(username=username, email=email, password=password)
content = {"err_code":0, "message":"注册成功", "data":None}
else:
content = {"err_code":-1, "message":"请求方式错误", "data":None}
return HttpResponse(json.dumps(content))
def login(request):
''' 实现登录功能,须以POST方式. If successful, cookie would be set.
Arguments:
request: It should contains {"username":<str>, "password":<str>} in the body.
Return:
An HttpRepsonse, which contains {"err_code":<int>, "message":<str>, "data":None}
'''
if request.method == "POST":
data = json.loads(request.body)
username = data.get("username")
password = data.get("password")
user = backend_ask_user(username, password)
if backend_ask_login_user(request):
content = {"err_code":-1, "message":"当前已登录,请先退出登录", "data":None}
return HttpResponse(json.dumps(content))
elif not user:
content = {"err_code":-1, "message":"用户名或密码错误", "data":None}
return HttpResponse(json.dumps(content))
else:
cookie_value = make_cookie()
# save cookie_value in user
user.cookie_value = cookie_value
user.save()
# conduct response
content = {"err_code":0, "message":"登录成功", "data":None}
response = HttpResponse(json.dumps(content))
response.set_cookie("cookie_value", cookie_value, max_age=6*60*60)
return response
else:
content = {"err_code":-1, "message":"请求方式错误", "data":None}
return HttpResponse(json.dumps(content))
def logout(request):
''' 退出登录. If successful, cookie would be deleted.
Arguments:
request: no data in the body
Return:
An HttpRepsonse, which contains {"err_code":<int>, "message":<str>, "data":None}
'''
if not backend_ask_login_user(request):
content = {"err_code":-1, "message":"当前未登录", "data":None}
return HttpResponse(json.dumps(content))
else:
content = {"err_code":0, "message":"成功退出登录", "data":None}
response = HttpResponse(json.dumps(content))
response.delete_cookie("cookie_value")
return response
def verify(request):
''' 进行验证, 须以POST方式
Arguments:
request: It should contains {"email":<str>} in the body.
Return:
An HttpRepsonse, which contains {"err_code":<int>, "message":<str>, "data":None}
'''
if request.method == "POST":
data = json.loads(request.body)
email = data.get("email")
if email == "":
content = {"err_code":-1, "message":"邮箱为空", "data":None}
else:
code = make_verification_code()
# save verification code
save_verification_code(email, code)
# send verification email
subject = "FSDN论坛"
message = "欢迎使用FSDN论坛!您本次操作的验证码是{}。此验证码10分钟内有效。".format(code)
send_mail(subject, message, "fdc_forum@163.com", [email], fail_silently=False)
# conduct the content
content = {"err_code":0, "message":"成功发送验证码", "data":None}
else:
content = {"err_code":-1, "message":"请求方式错误", "data":None}
return HttpResponse(json.dumps(content))
def modify_password(request):
''' 修改密码, 须以POST方式
Arguments:
request: It should contains {"email":<str>, "password":<str>, "verification":<str>} in the body.
Return:
An HttpRepsonse, which contains {"err_code":<int>, "message":<str>, "data":None}
'''
if request.method == "POST":
data = json.loads(request.body)
email = data.get("email")
password = data.get("password")
code = data.get("verification")
if email == "" or password == "" or code == "":
content = {"err_code":-1, "message":"邮箱、密码或验证码为空", "data":None}
elif not check_verification_code(email, code):
content = {"err_code":-1, "message":"验证码错误或过期", "data":None}
else:
if not User.objects.filter(email=email).exists():
content = {"err_code":-1, "message":"该邮箱无对应用户", "data":None}
else:
user = User.objects.filter(email=email)[0]
user.password = password
user.save()
content = {"err_code":0, "message":"密码修改成功", "data":None}
else:
content = {"err_code":-1, "message":"请求方式错误", "data":None}
return HttpResponse(json.dumps(content))
def modify_username(request):
''' 修改用户名, 须以POST方式
Arguments:
request: It should contains {"username":<str>} in the body.
Return:
An HttpRepsonse, which contains {"err_code":<int>, "message":<str>, "data":None}
'''
if request.method == "POST":
data = json.loads(request.body)
username = data.get("username")
user = backend_ask_login_user(request)
if not user:
content = {"err_code":-1, "message":"当前未登录", "data":None}
elif username == "":
content = {"err_code":-1, "message":"用户名为空", "data":None}
elif User.objects.filter(username=username).exists():
content = {"err_code":-1, "message":"该用户名已存在", "data":None}
else:
user.username = username
user.save()
content = {"err_code":0, "message":"用户名修改成功", "data":None}
else:
content = {"err_code":-1, "message":"请求方式错误", "data":None}
return HttpResponse(json.dumps(content))
def modify_signature(request):
''' 个性签名, 须以POST方式
Arguments:
request: It should contains {"signature":<str>} in the body.
Return:
An HttpRepsonse, which contains {"err_code":<int>, "message":<str>, "data":None}
'''
if request.method == "POST":
content = json.loads(request.body)
signature = content.get("signature")
user = backend_ask_login_user(request)
if not user:
content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
user.signature = signature
user.save()
content = {"err_code":0, "message":"个性签名修改成功", "data":None}
else:
content = {"err_code":-1, "message":"请求方式错误", "data":None}
return HttpResponse(json.dumps(content))
def ask_user(request):
''' 查询用户信息,仅返回非安全相关信息
Arguments:
request: It should contains {"username":<str>} in the body.
Return:
An HttpRepsonse, which contains {"err_code":<int>, "message":<str>, "data":user}
'''
if request.method == "POST":
data = json.loads(request.body)
username = data.get("username")
if not User.objects.filter(username=username).exists():
content = {"err_code":-1, "message":"该用户名不存在", "data":None}
else:
obj = User.objects.filter(username=username)[0]
user = {"username":obj.username, "email":obj.email, "signature":obj.signature, "contribution":obj.contribution}
content = {"err_code":0, "message":"成功查询用户信息", "data":user}
else:
content = {"err_code":-1, "message":"请求方式错误", "data":None}
return HttpResponse(json.dumps(content))
def ask_login_user(request):
''' 查询当前登录用户,仅用于前端处理
Return:
An HttpRepsonse, which contains {"err_code":<int>, "message":<str>, "data":user or None}
'''
obj = backend_ask_login_user(request)
if not obj:
content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
content = {"err_code":0, "message":"查询成功", "data":obj.username}
return HttpResponse(json.dumps(content))
def message_list(request):
''' 获取消息通知列表,兼具删除过期通知消息
'''
user = backend_ask_login_user(request)
if not user:
content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
obj_list = user.rec_msg.all().order_by('-pub_date')
msg_list = []
for o in obj_list:
# 超过30天则自动删除
if timezone.now() > o.pub_date + datetime.timedelta(days=30):
o.delete()
# 已读且超过7天则自动删除
elif o.IsReading and timezone.now() > o.pub_date + datetime.timedelta(days=7):
o.delete()
else:
msg = conduct_message(o)
msg_list.append(msg)
content = {"err_code":0, "message":"消息获取成功", "data":msg_list}
return HttpResponse(json.dumps(content))
def message_read(request, msg_id):
''' 将某条消息标记为已读
'''
user = backend_ask_login_user(request)
if not user:
response_content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
try:
msg = Message.objects.get(id=msg_id)
if msg.receiver == user:
msg.IsReading = True
msg.save()
response_content = {"err_code":0, "message":"成功标记已读", "data":None}
else:
response_content = {"err_code":-1, "message":"您不是该通知消息的接收者,无法标记", "data":None}
except Message.DoesNotExist:
response_content = {"err_code":-1, "message":"该通知消息不存在", "data":None}
return HttpResponse(json.dumps(response_content))
def message_delete(request, msg_id):
''' 删除某条消息
'''
user = backend_ask_login_user(request)
if not user:
response_content = {"err_code":-1, "message":"当前未登录", "data":None}
else:
try:
msg = Message.objects.get(id=msg_id)
if msg.receiver == user:
msg.delete()
response_content = {"err_code":0, "message":"消息已删除", "data":None}
else:
response_content = {"err_code":-1, "message":"您不是该消息的接收者,无法删除", "data":None}
except Message.DoesNotExist:
response_content = {"err_code":-1, "message":"该消息不存在", "data":None}
return HttpResponse(json.dumps(response_content))
# some assist functions
def make_cookie():
''' 随机生成长度为50的cookie value
'''
cookie_value = ""
for i in range(50):
cookie_value += str(random.randint(0, 9))
return cookie_value
def backend_ask_login_user(request):
''' 查询当前登录用户,仅用于后端处理
Return:
已登录时,返回登录对象即an object of class User;
未登录时,返回None
'''
cookie_value = request.COOKIES.get("cookie_value")
if not cookie_value:
return None
else:
if not User.objects.filter(cookie_value=cookie_value).exists():
return None
else:
return User.objects.filter(cookie_value=cookie_value)[0]
def backend_ask_user(username, password):
''' 若存在返回相应的用户,否则返回None
Arguments:
username: 用户名或邮箱地址
password: 密码
'''
if User.objects.filter(username=username, password=password).exists():
return User.objects.filter(username=username, password=password)[0]
elif User.objects.filter(email=username, password=password).exists():
return User.objects.filter(email=username, password=password)[0]
else:
return None
| {"/issue/admin.py": ["/issue/models.py"], "/image/views.py": ["/account/models.py"], "/issue/views.py": ["/issue/models.py", "/account/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/utils/verification.py": ["/account/models.py"], "/account/utils/message.py": ["/account/models.py", "/issue/models.py", "/comment/models.py"], "/comment/views.py": ["/account/models.py", "/issue/models.py", "/comment/models.py", "/account/utils/message.py"], "/account/views.py": ["/account/models.py", "/account/utils/verification.py", "/account/utils/message.py"]} |
51,426 | blorenz/braner | refs/heads/master | /cmsplugin_video_gallery/admin.py | from inline_ordering.admin import OrderableStackedInline
import forms
import models
class VideoInline(OrderableStackedInline):
model = models.Video
form = forms.VideoForm
# gallery = models.ForeignKey(VideoGalleryPlugin, verbose_name=_("Gallery"))
# src = models.ImageField(_("Poster image file"), upload_to=get_media_path,
# height_field='src_height',
# width_field='src_width')
# src_height = models.PositiveSmallIntegerField(_("Poster image height"), editable=False, null=True)
# src_width = models.PositiveSmallIntegerField(_("Poster image height"), editable=False, null=True)
# title = models.CharField(_("Title"), max_length=255, blank=True, null=True)
# alt = models.TextField(_("Alt text"), blank=True, null=True)
# link = models.CharField(_("Link"), max_length=255, blank=True, null=True)
# extended_content = models.TextField(_("Extended Content"), blank=True, null=True)
# video_duration = models.CharField(max_length=20, null=True, blank=True)
#
# video_id = models.CharField(_('video id'), max_length=60)
#
# autoplay = models.BooleanField(
# _('autoplay'),
# default=settings.CMS_VIMEO_DEFAULT_AUTOPLAY
# )
#
# width = models.IntegerField(_('width'),
# default=settings.CMS_VIMEO_DEFAULT_WIDTH)
# height = models.IntegerField(_('height'),
# default=settings.CMS_VIMEO_DEFAULT_HEIGHT)
# border = models.BooleanField(_('border'),
# default=settings.CMS_VIMEO_DEFAULT_BORDER)
#
# loop = models.BooleanField(_('loop'),
# default=settings.CMS_VIMEO_DEFAULT_LOOP)
fieldsets = (
(None,
{
'fields': ( 'src','title',),
}
),
('Info', {
'fields': ('extended_content',),
'classes': ('collapse',),
}),
('Video', {
'fields': ('video_id', 'autoplay', 'width', 'height', 'video_duration', 'border', 'loop'),
'classes': ('collapse',),
}),
('Advanced',
{
'fields': ('alt','link','inline_ordering_position',),
'classes': ('collapse',),
}
)
)
class Media:
js = ('js/jqueryFix.js','js/jquery-ui-1.10.3.custom.min.js',)
css = {
"all": ("css/jquery-ui-1.10.3.custom.min.css",)
}
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'src' or db_field.name == 'poster_src':
kwargs.pop('request', None)
kwargs['widget'] = forms.AdminImageWidget
return db_field.formfield(**kwargs)
return super(VideoInline, self).\
formfield_for_dbfield(db_field, **kwargs)
| {"/braner/settings/__init__.py": ["/braner/settings/basesettings.py"]} |
51,427 | blorenz/braner | refs/heads/master | /cmsplugin_video_gallery/settings.py | from django.conf import settings
# Autoplay
CMS_VIMEO_DEFAULT_AUTOPLAY = getattr(settings, 'CMS_VIMEO_DEFAULT_AUTOPLAY', True)
# Width & Height
CMS_VIMEO_DEFAULT_WIDTH = getattr(settings, 'CMS_VIMEO_DEFAULT_WIDTH', 640)
CMS_VIMEO_DEFAULT_HEIGHT = getattr(settings, 'CMS_VIMEO_DEFAULT_HEIGHT', 420)
# Border
CMS_VIMEO_DEFAULT_BORDER = getattr(settings, 'CMS_VIMEO_DEFAULT_BORDER', False)
# Loop
CMS_VIMEO_DEFAULT_LOOP = getattr(settings, 'CMS_VIMEO_DEFAULT_LOOP', False) | {"/braner/settings/__init__.py": ["/braner/settings/basesettings.py"]} |
51,428 | blorenz/braner | refs/heads/master | /cmsplugin_video_gallery/models.py | import threading
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from inline_ordering.models import Orderable
from cmsplugin_video_gallery import settings
import utils
localdata = threading.local()
localdata.TEMPLATE_CHOICES = utils.autodiscover_templates()
TEMPLATE_CHOICES = localdata.TEMPLATE_CHOICES
class VideoGalleryPlugin(CMSPlugin):
title = models.CharField(_("Gallery Title"), max_length=255)
def copy_relations(self, oldinstance):
for video in oldinstance.video_set.all():
new_img = Video()
new_img.gallery=self
new_img.src = video.src
new_img.src_height = video.src_height
new_img.src_width = video.src_width
# new_img.poster_src = video.poster_src
# new_img.poster_src_height = video.poster_src_height
# new_img.poster_src_width = video.poster_src_width
new_img.title = video.title
new_img.alt = video.alt
new_img.link = video.link
new_img.extended_content = video.extended_content
# new_img.mp4_file = video.mp4_file
# new_img.ogv_file = video.ogv_file
# new_img.webm_file = video.webm_file
# new_img.video_width = video.video_width
# new_img.video_height = video.video_height
new_img.video_id = video.video_id
new_img.autoplay = video.autoplay
new_img.width = video.width
new_img.height = video.height
new_img.border = video.border
new_img.loop = video.loop
new_img.video_duration = video.video_duration
new_img.save()
template = models.CharField(max_length=255,
choices=TEMPLATE_CHOICES,
default='cmsplugin_video_gallery/gallery.html',
editable=len(TEMPLATE_CHOICES) > 1)
def __unicode__(self):
return _(u'%(count)d video(s) in gallery') % {'count': self.video_set.count()}
class Video(Orderable):
def get_media_path(self, filename):
pages = self.gallery.placeholder.page_set.all()
return pages[0].get_media_path(filename)
gallery = models.ForeignKey(VideoGalleryPlugin, verbose_name=_("Gallery"))
src = models.ImageField(_("Poster image file"), upload_to=get_media_path,
height_field='src_height',
width_field='src_width')
src_height = models.PositiveSmallIntegerField(_("Poster image height"), editable=False, null=True)
src_width = models.PositiveSmallIntegerField(_("Poster image height"), editable=False, null=True)
title = models.CharField(_("Title"), max_length=255, blank=True, null=True)
alt = models.TextField(_("Alt text"), blank=True, null=True)
link = models.CharField(_("Link"), max_length=255, blank=True, null=True)
extended_content = models.TextField(_("Extended Content"), blank=True, null=True)
# poster_src = models.ImageField(_("Poster image file"), upload_to=get_media_path,
# height_field='src_height',
# width_field='src_width', blank=True, null=True)
# poster_src_height = models.PositiveSmallIntegerField(_("Poster image height"), editable=False, null=True, blank=True)
# poster_src_width = models.PositiveSmallIntegerField(_("Poster image height"), editable=False, null=True, blank=True)
# mp4_file = models.FileField(_("MP4 video file"), upload_to=get_media_path, null=True, blank=True)
# ogv_file = models.FileField(_("Ogg video file"), upload_to=get_media_path, null=True, blank=True)
# webm_file = models.FileField(_("WebM video file"), upload_to=get_media_path, null=True, blank=True)
# video_width = models.PositiveSmallIntegerField(_("Video width"), null=True, blank=True)
# video_height = models.PositiveSmallIntegerField(_("Video height"), null=True, blank=True)
video_duration = models.CharField(max_length=20, null=True, blank=True)
video_id = models.CharField(_('video id'), max_length=60)
autoplay = models.BooleanField(
_('autoplay'),
default=settings.CMS_VIMEO_DEFAULT_AUTOPLAY
)
width = models.IntegerField(_('width'),
default=settings.CMS_VIMEO_DEFAULT_WIDTH)
height = models.IntegerField(_('height'),
default=settings.CMS_VIMEO_DEFAULT_HEIGHT)
border = models.BooleanField(_('border'),
default=settings.CMS_VIMEO_DEFAULT_BORDER)
loop = models.BooleanField(_('loop'),
default=settings.CMS_VIMEO_DEFAULT_LOOP)
def __unicode__(self):
return self.title or self.alt or str(self.pk)
| {"/braner/settings/__init__.py": ["/braner/settings/basesettings.py"]} |
51,429 | blorenz/braner | refs/heads/master | /braner_plugins/cmsplugin_custom_contact/forms.py | from django import forms
from cmsplugin_contact.forms import ContactForm
class CustomContactForm(forms.Form):
email = forms.EmailField()
content = forms.CharField(widget=forms.Textarea())
name = forms.CharField()
company = forms.CharField()
phone = forms.CharField() | {"/braner/settings/__init__.py": ["/braner/settings/basesettings.py"]} |
51,430 | blorenz/braner | refs/heads/master | /cmsplugin_video_gallery/cms_plugins.py | from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext_lazy as _
import admin
import models
class CMSVideoGalleryPlugin(CMSPluginBase):
model = models.VideoGalleryPlugin
inlines = [admin.VideoInline, ]
name = _('Video gallery')
render_template = 'cmsplugin_video_gallery/gallery.html'
def render(self, context, instance, placeholder):
context.update({
'videos': instance.video_set.all(),
'gallery': instance,
})
self.render_template = instance.template
return context
plugin_pool.register_plugin(CMSVideoGalleryPlugin)
| {"/braner/settings/__init__.py": ["/braner/settings/basesettings.py"]} |
51,431 | blorenz/braner | refs/heads/master | /braner_plugins/cmsplugin_custom_contact/models.py | from django.db import models
from cmsplugin_contact.models import BaseContact
from django.utils.translation import ugettext_lazy as _
class CustomContact(BaseContact):
phone_label = models.CharField(
_('Phone label'),
default=_('Phone'), max_length=20)
name_label = models.CharField(
_('Name label'),
default=_('Name'), max_length=20)
company_label = models.CharField(
_('Company label'),
default=_('Company'), max_length=20)
| {"/braner/settings/__init__.py": ["/braner/settings/basesettings.py"]} |
51,432 | blorenz/braner | refs/heads/master | /braner/settings/basesettings.py | """
Django settings for braner project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/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__))
# -*- coding: utf-8 -*-
import os
gettext = lambda s: s
PROJECT_PATH = os.path.split(os.path.abspath(os.path.dirname(__file__)))[0]
# Take it from the Braner app to the project path because of the settings file
# is now in its own directory
PROJECT_PATH = os.path.join(PROJECT_PATH, '..')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'x0bu$1_hi_ugp-of%%zd(xrq78&4f#y(d3jm6d0-p(-vpbgpv!'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
SITE_ID = 1
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
# my own
'braner',
'cms',
'mptt',
'menus',
'south',
'sekizai',
'cms_redirects',
'tinymce',
# 'cms.plugins.flash',
'braner_plugins.googlemap',
'cms.plugins.link',
# 'cms.plugins.snippet',
'cms.plugins.text',
# 'cms.plugins.twitter',
'filer',
'easy_thumbnails',
'cmsplugin_filer_file',
'cmsplugin_filer_folder',
'cmsplugin_filer_image',
'cmsplugin_filer_teaser',
'cmsplugin_filer_video',
'cmsplugin_gallery',
'cmsplugin_video_gallery',
'cmsplugin_file_gallery',
'cmsplugin_contact',
'braner_plugins.cmsplugin_custom_contact',
'reversion',
'inline_ordering',
'gunicorn',
'widget_tweaks',
'cmsplugin_vimeo',
)
THUMBNAIL_PROCESSORS = (
'easy_thumbnails.processors.colorspace',
'easy_thumbnails.processors.autocrop',
#'easy_thumbnails.processors.scale_and_crop',
'filer.thumbnail_processors.scale_and_crop_with_subject_location',
'easy_thumbnails.processors.filters',
)
MIDDLEWARE_CLASSES = (
'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',
'django.middleware.locale.LocaleMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.toolbar.ToolbarMiddleware',
'cms.middleware.language.LanguageCookieMiddleware',
'cms_redirects.middleware.RedirectFallbackMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'django.core.context_processors.static',
'cms.context_processors.media',
'sekizai.context_processors.sekizai',
)
STATIC_ROOT = os.path.join(PROJECT_PATH, "static")
STATIC_URL = "/static/"
MEDIA_ROOT = os.path.join(PROJECT_PATH, "media")
MEDIA_URL = "/media/"
TEMPLATE_DIRS = (
# The docs say it should be absolute path: PROJECT_PATH is precisely one.
# Life is wonderful!
os.path.join(PROJECT_PATH, "templates"),
)
CMS_TEMPLATES = (
('home.html', 'Home Page Template'),
('products_overview.html', 'Products Overview Template'),
('products_features.html', 'Products Features Template'),
('products_installations.html', 'Products Installations Template'),
('products_movies.html', 'Products Movies Template'),
('products_articles.html', 'Products Articles Template'),
('services.html', 'Services Template'),
('contact.html', 'Contact Template'),
)
LANGUAGES = [
('en', gettext('English')),
('es', gettext('Spanish')),
]
CMS_LANGUAGES = LANGUAGES
CMS_HIDE_UNTRANSLATED = True
CMS_LANGUAGE_CONF = {
'es': ['en',],
}
ROOT_URLCONF = 'braner.urls'
WSGI_APPLICATION = 'braner.wsgi.application'
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
CMS_MENU_TITLE_OVERWRITE = True
CMS_SEO_FIELDS = True
CMS_REDIRECTS = True
THUMBNAIL_PROCESSORS = (
'easy_thumbnails.processors.colorspace',
'easy_thumbnails.processors.autocrop',
#'easy_thumbnails.processors.scale_and_crop',
'filer.thumbnail_processors.scale_and_crop_with_subject_location',
'easy_thumbnails.processors.filters',
)
# 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.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
AUTH_USER_MODEL = 'auth.User'
# TINYMCE_JS_URL = '//tinymce.cachefly.net/4.0/tinymce.min.js'
TINYMCE_DEFAULT_CONFIG = {
'plugins': "fullscreen,table,spellchecker,paste,searchreplace",
'toolbar': "fullscreen",
'theme': "advanced",
'theme_advanced_buttons3_add' : "fullpage",
'cleanup_on_startup': True,
'custom_undo_redo_levels': 10,
'relative_urls': False,
'content_css' : "/static/css/tinymce.css",
}
TINYMCE_SPELLCHECKER = True
TINYMCE_COMPRESSOR = True | {"/braner/settings/__init__.py": ["/braner/settings/basesettings.py"]} |
51,433 | blorenz/braner | refs/heads/master | /cmsplugin_video_gallery/migrations/0004_auto__del_field_video_video_width__del_field_video_video_height__del_f.py | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Video.video_width'
db.delete_column(u'cmsplugin_video_gallery_video', 'video_width')
# Deleting field 'Video.video_height'
db.delete_column(u'cmsplugin_video_gallery_video', 'video_height')
# Deleting field 'Video.mp4_file'
db.delete_column(u'cmsplugin_video_gallery_video', 'mp4_file')
# Deleting field 'Video.poster_src_width'
db.delete_column(u'cmsplugin_video_gallery_video', 'poster_src_width')
# Deleting field 'Video.webm_file'
db.delete_column(u'cmsplugin_video_gallery_video', 'webm_file')
# Deleting field 'Video.ogv_file'
db.delete_column(u'cmsplugin_video_gallery_video', 'ogv_file')
# Deleting field 'Video.poster_src_height'
db.delete_column(u'cmsplugin_video_gallery_video', 'poster_src_height')
# Deleting field 'Video.poster_src'
db.delete_column(u'cmsplugin_video_gallery_video', 'poster_src')
# Adding field 'Video.video_id'
db.add_column(u'cmsplugin_video_gallery_video', 'video_id',
self.gf('django.db.models.fields.CharField')(default='89298139', max_length=60),
keep_default=False)
# Adding field 'Video.autoplay'
db.add_column(u'cmsplugin_video_gallery_video', 'autoplay',
self.gf('django.db.models.fields.BooleanField')(default=True),
keep_default=False)
# Adding field 'Video.width'
db.add_column(u'cmsplugin_video_gallery_video', 'width',
self.gf('django.db.models.fields.IntegerField')(default=640),
keep_default=False)
# Adding field 'Video.height'
db.add_column(u'cmsplugin_video_gallery_video', 'height',
self.gf('django.db.models.fields.IntegerField')(default=420),
keep_default=False)
# Adding field 'Video.border'
db.add_column(u'cmsplugin_video_gallery_video', 'border',
self.gf('django.db.models.fields.BooleanField')(default=False),
keep_default=False)
# Adding field 'Video.loop'
db.add_column(u'cmsplugin_video_gallery_video', 'loop',
self.gf('django.db.models.fields.BooleanField')(default=False),
keep_default=False)
def backwards(self, orm):
# Adding field 'Video.video_width'
db.add_column(u'cmsplugin_video_gallery_video', 'video_width',
self.gf('django.db.models.fields.PositiveSmallIntegerField')(null=True, blank=True),
keep_default=False)
# Adding field 'Video.video_height'
db.add_column(u'cmsplugin_video_gallery_video', 'video_height',
self.gf('django.db.models.fields.PositiveSmallIntegerField')(null=True, blank=True),
keep_default=False)
# Adding field 'Video.mp4_file'
db.add_column(u'cmsplugin_video_gallery_video', 'mp4_file',
self.gf('django.db.models.fields.files.FileField')(max_length=100, null=True, blank=True),
keep_default=False)
# Adding field 'Video.poster_src_width'
db.add_column(u'cmsplugin_video_gallery_video', 'poster_src_width',
self.gf('django.db.models.fields.PositiveSmallIntegerField')(null=True, blank=True),
keep_default=False)
# Adding field 'Video.webm_file'
db.add_column(u'cmsplugin_video_gallery_video', 'webm_file',
self.gf('django.db.models.fields.files.FileField')(max_length=100, null=True, blank=True),
keep_default=False)
# Adding field 'Video.ogv_file'
db.add_column(u'cmsplugin_video_gallery_video', 'ogv_file',
self.gf('django.db.models.fields.files.FileField')(max_length=100, null=True, blank=True),
keep_default=False)
# Adding field 'Video.poster_src_height'
db.add_column(u'cmsplugin_video_gallery_video', 'poster_src_height',
self.gf('django.db.models.fields.PositiveSmallIntegerField')(null=True, blank=True),
keep_default=False)
# Adding field 'Video.poster_src'
db.add_column(u'cmsplugin_video_gallery_video', 'poster_src',
self.gf('django.db.models.fields.files.ImageField')(max_length=100, null=True, blank=True),
keep_default=False)
# Deleting field 'Video.video_id'
db.delete_column(u'cmsplugin_video_gallery_video', 'video_id')
# Deleting field 'Video.autoplay'
db.delete_column(u'cmsplugin_video_gallery_video', 'autoplay')
# Deleting field 'Video.width'
db.delete_column(u'cmsplugin_video_gallery_video', 'width')
# Deleting field 'Video.height'
db.delete_column(u'cmsplugin_video_gallery_video', 'height')
# Deleting field 'Video.border'
db.delete_column(u'cmsplugin_video_gallery_video', 'border')
# Deleting field 'Video.loop'
db.delete_column(u'cmsplugin_video_gallery_video', 'loop')
models = {
'cms.cmsplugin': {
'Meta': {'object_name': 'CMSPlugin'},
'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}),
'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
},
'cms.placeholder': {
'Meta': {'object_name': 'Placeholder'},
'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'})
},
u'cmsplugin_video_gallery.video': {
'Meta': {'ordering': "('inline_ordering_position',)", 'object_name': 'Video'},
'alt': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'autoplay': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'border': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'extended_content': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'gallery': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cmsplugin_video_gallery.VideoGalleryPlugin']"}),
'height': ('django.db.models.fields.IntegerField', [], {'default': '344'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'inline_ordering_position': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'link': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'loop': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'src': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}),
'src_height': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
'src_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'video_duration': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}),
'video_id': ('django.db.models.fields.CharField', [], {'max_length': '60'}),
'width': ('django.db.models.fields.IntegerField', [], {'default': '425'})
},
u'cmsplugin_video_gallery.videogalleryplugin': {
'Meta': {'object_name': 'VideoGalleryPlugin', 'db_table': "u'cmsplugin_videogalleryplugin'", '_ormbases': ['cms.CMSPlugin']},
u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
'template': ('django.db.models.fields.CharField', [], {'default': "'cmsplugin_video_gallery/gallery.html'", 'max_length': '255'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
}
}
complete_apps = ['cmsplugin_video_gallery'] | {"/braner/settings/__init__.py": ["/braner/settings/basesettings.py"]} |
51,434 | blorenz/braner | refs/heads/master | /braner/settings/__init__.py | from .basesettings import *
from .localsettings import * | {"/braner/settings/__init__.py": ["/braner/settings/basesettings.py"]} |
51,435 | blorenz/braner | refs/heads/master | /braner/views.py | from django.http import HttpResponseRedirect
def home(request):
return HttpResponseRedirect("/en/")
| {"/braner/settings/__init__.py": ["/braner/settings/basesettings.py"]} |
51,446 | namanchikara/Voice-based-email-system-for-visually-challenged | refs/heads/master | /voicemail/__init__.py | import sys
from pathlib import Path
from config import MailConfig
from mail.Mail import Mail
from mail.Recipient import Recipient
sys.path.extend([str(Path(sys.argv[0]).parent), str(Path(sys.argv[0]).parent.parent)])
from voicemail.Audio import Audio
from voicemail.SpeechToText import SpeechToText
from voicemail.TextToSpeech import TextToSpeech
__all__ = [
Audio,
SpeechToText,
TextToSpeech
]
def loop():
print("Welcome to voice based email")
TextToSpeech("Welcome to voice based email").speak_out_loud()
print("To whom do you want to send an email?")
TextToSpeech("To whom do you want to send an email?").speak_out_loud()
recipient = Recipient().get_recipient()
if recipient is not None:
Mail(MailConfig.email, MailConfig.password, recipient).send_mail()
else:
loop()
if __name__ == '__main__':
loop()
| {"/voicemail/__init__.py": ["/voicemail/Audio.py", "/voicemail/SpeechToText.py", "/voicemail/TextToSpeech.py"]} |
51,447 | namanchikara/Voice-based-email-system-for-visually-challenged | refs/heads/master | /voicemail/config/LanguageConfig.py | text_to_speech_english = 'en'
speech_to_text_english = 'en-IN' | {"/voicemail/__init__.py": ["/voicemail/Audio.py", "/voicemail/SpeechToText.py", "/voicemail/TextToSpeech.py"]} |
51,448 | namanchikara/Voice-based-email-system-for-visually-challenged | refs/heads/master | /voicemail/SpeechToText.py | import speech_recognition as sr
from enum import Enum
from config import LanguageConfig
from TextToSpeech import TextToSpeech
class SpeechToText:
def __init__(self, audio, language=LanguageConfig.speech_to_text_english):
self.r = sr.Recognizer()
self.audio = audio
self.message = None
self.language = language
def convert_to_text(self):
try:
self.message = self.r.recognize_google(self.audio, language=self.language)
return self.message + ' '
except sr.UnknownValueError:
print("Sorry, I didn't understand what you said, Please say again.")
TextToSpeech("Sorry, I didn't understand what you said, Please say again.").speak_out_loud()
return SpeechError.UNKNOWN_VALUE_ERROR
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
TextToSpeech("Could not request results from Google Speech Recognition service; {0}".format(e)).speak_out_loud()
return SpeechError.REQUEST_ERROR
class SpeechError(Enum):
UNKNOWN_VALUE_ERROR = 1
REQUEST_ERROR = 2
| {"/voicemail/__init__.py": ["/voicemail/Audio.py", "/voicemail/SpeechToText.py", "/voicemail/TextToSpeech.py"]} |
51,449 | namanchikara/Voice-based-email-system-for-visually-challenged | refs/heads/master | /voicemail/Audio.py | import speech_recognition as sr
from TextToSpeech import TextToSpeech
class Audio:
def __init__(self):
self.r = sr.Recognizer()
self.audio = None
def record(self):
with sr.Microphone() as source:
print("I'm listening, Go on")
TextToSpeech("I'm listening, Go on").speak_out_loud()
self.audio = self.r.listen(source)
return self.audio
| {"/voicemail/__init__.py": ["/voicemail/Audio.py", "/voicemail/SpeechToText.py", "/voicemail/TextToSpeech.py"]} |
51,450 | namanchikara/Voice-based-email-system-for-visually-challenged | refs/heads/master | /voicemail/TextToSpeech.py | import hashlib
import os
import tempfile
import time
import pyglet
import pyttsx3
from gtts import gTTS
from config import LanguageConfig
class TextToSpeech:
def __init__(self, text, language=LanguageConfig.text_to_speech_english) -> None:
self.text = text
self.lang = language
self.file_address = self.__build_file_address()
self.tts = gTTS(text=self.text, lang=self.lang)
self.__save_to_file()
speech = self.__to_speech()
speech.play()
time.sleep(speech.duration)
# # self.tts.setProperty('voice', self.voices[1].id)
# self.tts = pyttsx3.init()
# # self.voices = self.tts.getProperty('voices') # getting details of current voice
# self.tts.say(self.text)
# self.tts.runAndWait()
def __build_file_address(self):
return os.path.join(
tempfile.gettempdir(),
hashlib.md5(self.text.encode()).hexdigest() + '.mp3'
)
def __to_speech(self):
return pyglet.media.load(self.file_address, streaming=False)
def speak_out_loud(self):
pass
def __save_to_file(self):
if not os.path.exists(self.file_address):
self.tts.save(self.file_address)
| {"/voicemail/__init__.py": ["/voicemail/Audio.py", "/voicemail/SpeechToText.py", "/voicemail/TextToSpeech.py"]} |
51,451 | namanchikara/Voice-based-email-system-for-visually-challenged | refs/heads/master | /voicemail/mail/Compose.py | from TextToSpeech import TextToSpeech
from Audio import Audio
from SpeechToText import SpeechToText
from config import LanguageConfig
from difflib import SequenceMatcher
class Compose:
def __init__(self, language=LanguageConfig.speech_to_text_english):
self.subject = ''
self.body = ''
self.language = language
self.options = ["retry", "continue", "append"]
print("What is the Subject of this e-mail?")
TextToSpeech("What is the Subject of this e-mail?").speak_out_loud()
self.prepare_subject()
print("What is the body of the email?")
TextToSpeech("What is the body of the email?").speak_out_loud()
self.get_user_input_for_body()
self.validate_email()
def prepare_subject(self):
self.get_user_input_for_subject()
def get_user_input_for_subject(self):
response = self.get_text_response_via_speech_recognition()
print("You said : " + str(response))
TextToSpeech("You said : " + str(response)).speak_out_loud()
self.validate_choice_for_subject(response)
def validate_choice_for_subject(self, response):
print("Do you want to continue? retry? append?")
TextToSpeech("Do you want to continue? retry? append?").speak_out_loud()
choice = self.get_text_response_via_speech_recognition()
if choice is None:
self.validate_choice_for_subject(response)
else:
validated_choice = self.validate_choice_of_subject_for(choice)
if validated_choice is True:
choice = self.similar(choice)
self.take_action_for_subject_on(choice, response)
if validated_choice is False:
print("Invalid choice :" + choice)
self.validate_choice_for_subject(response)
def get_user_input_for_body(self):
response = self.get_text_response_via_speech_recognition()
print("You said : " + response)
TextToSpeech("You said : " + response).speak_out_loud()
self.validate_choice_for_body(response)
def validate_choice_for_body(self, response):
print("Do you want to continue? retry? append?")
TextToSpeech("Do you want to continue? retry? append?").speak_out_loud()
choice = self.get_text_response_via_speech_recognition()
if choice is None:
TextToSpeech("I didn't get what you said, Say again").speak_out_loud()
print("I didn't get what you said, Say again")
self.validate_choice_for_body(response)
else:
validated_choice_boolean = self.validate_choice_of_body_for(choice)
if validated_choice_boolean is True:
choice = self.similar(choice)
validated_choice_boolean = self.take_action_for_body_on(choice, response)
if validated_choice_boolean is False:
TextToSpeech("I didn't get what you said, Say again").speak_out_loud()
print("I didn't get what you said, Say again")
self.validate_choice_for_body(response)
def get_text_response_via_speech_recognition(self):
response = SpeechToText(Audio().record(), language=self.language).convert_to_text()
if isinstance(response, str) and not None:
return response.strip()
print("Something went wrong, retrying.")
return self.get_text_response_via_speech_recognition()
def validate_choice_of_subject_for(self, choice):
# if choice.strip().lower() in self.options:
# return True
# return False
if self.similar(choice) is not False:
return True
return False
def take_action_for_subject_on(self, choice, response):
if choice == "retry":
self.get_user_input_for_subject()
elif choice == "continue":
self.subject += response
return
elif choice == "append":
self.subject += response
self.get_user_input_for_subject()
def validate_choice_of_body_for(self, choice):
return self.validate_choice_of_subject_for(choice)
def take_action_for_body_on(self, choice, response):
if choice == "retry":
self.get_user_input_for_body()
elif choice == "continue":
self.body += response
return
elif choice == "append":
self.body += response
self.get_user_input_for_body()
else:
return False
def validate_email(self):
print("Before sending the email do you want to listen it out? Say yes or no")
TextToSpeech("Before sending the email do you want to listen it out? Say yes or no").speak_out_loud()
bool_response = self.get_boolean_response()
if self.validate_choice_for_confirmation(bool_response) is True:
print("Subject is :")
TextToSpeech("Subject is : " + self.subject, language=self.language).speak_out_loud()
print("Body is :")
TextToSpeech("Body is :" + self.body, language=self.language).speak_out_loud()
def validate_choice_for_confirmation(self, bool_response):
if bool_response is not None:
if bool_response.lower() == "yes":
return True
elif bool_response.lower() == "no":
return False
print("I didn't get what you said, Say again")
TextToSpeech("I didn't get what you said, Say again").speak_out_loud()
self.validate_choice_for_confirmation(self.get_boolean_response())
def get_boolean_response(self):
response = self.get_text_response_via_speech_recognition()
if response.lower() in ["yes", "no"]:
return response
return self.get_boolean_response()
def similar(self, choice):
for option in self.options:
if SequenceMatcher(None, choice, option).ratio() > 0.6:
return option
return False
| {"/voicemail/__init__.py": ["/voicemail/Audio.py", "/voicemail/SpeechToText.py", "/voicemail/TextToSpeech.py"]} |
51,452 | namanchikara/Voice-based-email-system-for-visually-challenged | refs/heads/master | /voicemail/mail/Recipient.py | from TextToSpeech import TextToSpeech
from SpeechToText import SpeechToText
from Audio import Audio
from difflib import SequenceMatcher
class Recipient:
def __init__(self):
self.email_addresses = {
"Naman": "singhnamanchikara@gmail.com",
"Shantanu": "shantanublahblah@gmail.com",
"exit": "exit"
}
def get_recipient(self):
recipient_choice = self.__get_text_response_via_speech_recognition()
if recipient_choice is None:
self.get_recipient()
print("Recipient " + recipient_choice)
if self.similar(recipient_choice) is False:
print("I didn't understand the name, Say again from one of the following names:" +
str(self.email_addresses.keys()))
TextToSpeech("I didn't understand the name, Say again from one of the following names:" +
str(self.email_addresses.keys())).speak_out_loud()
self.get_recipient()
else:
if self.similar(recipient_choice) == "exit":
return None
print("Do you want to send email to " + self.email_addresses[self.similar(recipient_choice)] +
" Say yes or no")
TextToSpeech("Do you want to send email to " + self.email_addresses[self.similar(recipient_choice)] +
" Say yes or no").speak_out_loud()
boolean_response = self.__get_boolean_response()
if boolean_response.lower() == "yes":
return self.email_addresses[self.similar(recipient_choice)]
self.get_recipient()
def __get_text_response_via_speech_recognition(self):
response = SpeechToText(Audio().record()).convert_to_text()
if isinstance(response, str) and not None:
return response.strip()
print("Something went wrong, retrying.")
return self.__get_text_response_via_speech_recognition()
def similar(self, choice):
if choice is None:
return False
for option in self.email_addresses.keys():
if SequenceMatcher(None, choice.strip().lower(), option.lower()).ratio() > 0.6:
return option
return False
def __get_boolean_response(self):
response = self.__get_text_response_via_speech_recognition()
if response.lower() in ["yes", "no"]:
return response
return self.__get_boolean_response()
| {"/voicemail/__init__.py": ["/voicemail/Audio.py", "/voicemail/SpeechToText.py", "/voicemail/TextToSpeech.py"]} |
51,453 | namanchikara/Voice-based-email-system-for-visually-challenged | refs/heads/master | /voicemail/mail/Mail.py | import smtplib
from TextToSpeech import TextToSpeech
from mail.Compose import Compose
from SpeechToText import SpeechToText
from Audio import Audio
class Mail:
def __init__(self, email, password, to_mail):
self.email_address = email
self.password = password
self.email = Compose()
self.to_email_address = to_mail
def send_mail(self):
print("Do you want to send this email? Say yes or no")
TextToSpeech("Do you want to send this email? Say yes or no")
via_speech_recognition = self.__get_text_response_via_speech_recognition()
if via_speech_recognition == "yes":
print("Sending mail")
TextToSpeech("Sending mail").speak_out_loud()
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login(self.email_address, self.password)
msg = 'Subject: {}\n\n{}'.format(self.email.subject, self.email.body)
mail.sendmail(self.email_address, self.to_email_address, msg)
print("Your mail has been sent.")
TextToSpeech("Your mail has been sent.").speak_out_loud()
mail.close()
else:
print("Mail discarded.")
TextToSpeech("Mail discarded.").speak_out_loud()
def __get_text_response_via_speech_recognition(self):
response = SpeechToText(Audio().record()).convert_to_text()
if isinstance(response, str) and not None:
return response.strip()
print("Something went wrong, retrying.")
return self.__get_text_response_via_speech_recognition()
| {"/voicemail/__init__.py": ["/voicemail/Audio.py", "/voicemail/SpeechToText.py", "/voicemail/TextToSpeech.py"]} |
51,456 | cdbethune/sloth-d3m-wrapper | refs/heads/master | /SlothD3MWrapper/__init__.py | from SlothD3MWrapper.Storc import Storc
__version__ = '2.0.1'
__all__ = [
"Storc"
] | {"/SlothD3MWrapper/__init__.py": ["/SlothD3MWrapper/Storc.py"]} |
51,457 | cdbethune/sloth-d3m-wrapper | refs/heads/master | /setup.py | from distutils.core import setup
setup(name='SlothD3MWrapper',
version='2.0.1',
description='A thin wrapper for interacting with New Knowledge time series tool library Sloth',
packages=['SlothD3MWrapper'],
install_requires=["Sloth==2.0.2"],
dependency_links=[
"git+https://github.com/NewKnowledge/sloth@fafa4857f02c91c36c22e0d3efb16ab90d47e62d#egg=Sloth-2.0.2"
],
entry_points = {
'd3m.primitives': [
'distil.Sloth.cluster = SlothD3MWrapper:Storc'
],
},
)
| {"/SlothD3MWrapper/__init__.py": ["/SlothD3MWrapper/Storc.py"]} |
51,458 | cdbethune/sloth-d3m-wrapper | refs/heads/master | /SlothD3MWrapper/Storc.py | import sys
import os.path
import numpy as np
import pandas
from Sloth import Sloth
from tslearn.datasets import CachedDatasets
from d3m.primitive_interfaces.transformer import TransformerPrimitiveBase
from d3m.primitive_interfaces.base import CallResult
from d3m import container, utils
from d3m.container import DataFrame as d3m_DataFrame
from d3m.metadata import hyperparams, base as metadata_base
from d3m.primitives.datasets import DatasetToDataFrame
from common_primitives import utils as utils_cp
from timeseriesloader.timeseries_loader import TimeSeriesLoaderPrimitive
__author__ = 'Distil'
__version__ = '2.0.1'
Inputs = container.pandas.DataFrame
Outputs = container.pandas.DataFrame
class Hyperparams(hyperparams.Hyperparams):
algorithm = hyperparams.Enumeration(default = 'GlobalAlignmentKernelKMeans',
semantic_types = ['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
values = ['GlobalAlignmentKernelKMeans', 'TimeSeriesKMeans', 'DBSCAN', 'HDBSCAN'],
description = 'type of clustering algorithm to use')
nclusters = hyperparams.UniformInt(lower=1, upper=sys.maxsize, default=3, semantic_types=
['https://metadata.datadrivendiscovery.org/types/TuningParameter'], description = 'number of clusters \
to user in kernel kmeans algorithm')
eps = hyperparams.Uniform(lower=0, upper=sys.maxsize, default = 0.5, semantic_types =
['https://metadata.datadrivendiscovery.org/types/TuningParameter'],
description = 'maximum distance between two samples for them to be considered as in the same neigborhood, \
used in DBSCAN algorithm')
min_samples = hyperparams.UniformInt(lower=1, upper=sys.maxsize, default = 5, semantic_types =
['https://metadata.datadrivendiscovery.org/types/TuningParameter'],
description = 'number of samples in a neighborhood for a point to be considered as a core point, \
used in DBSCAN and HDBSCAN algorithms')
pass
class Storc(TransformerPrimitiveBase[Inputs, Outputs, Hyperparams]):
"""
Produce primitive's best guess for the cluster number of each series.
"""
metadata = metadata_base.PrimitiveMetadata({
# Simply an UUID generated once and fixed forever. Generated using "uuid.uuid4()".
'id': "77bf4b92-2faa-3e38-bb7e-804131243a7f",
'version': __version__,
'name': "Sloth",
# Keywords do not have a controlled vocabulary. Authors can put here whatever they find suitable.
'keywords': ['Time Series','Clustering'],
'source': {
'name': __author__,
'uris': [
# Unstructured URIs.
"https://github.com/NewKnowledge/sloth-d3m-wrapper",
],
},
# A list of dependencies in order. These can be Python packages, system packages, or Docker images.
# Of course Python packages can also have their own dependencies, but sometimes it is necessary to
# install a Python package first to be even able to run setup.py of another package. Or you have
# a dependency which is not on PyPi.
'installation': [{
'type': metadata_base.PrimitiveInstallationType.PIP,
'package': 'cython',
'version': '0.28.5',
},{
'type': metadata_base.PrimitiveInstallationType.PIP,
'package_uri': 'git+https://github.com/NewKnowledge/sloth-d3m-wrapper.git@{git_commit}#egg=SlothD3MWrapper'.format(
git_commit=utils.current_git_commit(os.path.dirname(__file__)),
),
}],
# The same path the primitive is registered with entry points in setup.py.
'python_path': 'd3m.primitives.distil.Sloth.cluster',
# Choose these from a controlled vocabulary in the schema. If anything is missing which would
# best describe the primitive, make a merge request.
'algorithm_types': [
metadata_base.PrimitiveAlgorithmType.SPECTRAL_CLUSTERING,
],
'primitive_family': metadata_base.PrimitiveFamily.TIME_SERIES_SEGMENTATION,
})
def __init__(self, *, hyperparams: Hyperparams, random_seed: int = 0)-> None:
super().__init__(hyperparams=hyperparams, random_seed=random_seed)
def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> CallResult[Outputs]:
"""
Parameters
----------
inputs : Input pandas frame where each row is a series. Series timestamps are store in the column names.
Returns
-------
Outputs
The output is a dataframe containing a single column where each entry is the associated series' cluster number.
"""
# setup model up
sloth = Sloth()
# set number of clusters for k-means
if self.hyperparams['algorithm'] == 'TimeSeriesKMeans':
# enforce default value
if not self.hyperparams['nclusters']:
nclusters = 4
else:
nclusters = self.hyperparams['nclusters']
labels = sloth.ClusterSeriesKMeans(inputs.values, nclusters, 'TimeSeriesKMeans')
elif self.hyperparams['algorithm'] == 'DBSCAN':
# enforce default value
if not self.hyperparams['eps']:
nclusters = 0.5
else:
eps = self.hyperparams['eps']
if not self.hyperparams['min_samples']:
min_samples = 5
else:
min_samples = self.hyperparams['min_samples']
SimilarityMatrix = sloth.GenerateSimilarityMatrix(inputs.values)
nclusters, labels, cnt = sloth.ClusterSimilarityMatrix(SimilarityMatrix, eps, min_samples)
elif self.hyperparams['algorithm'] == 'HDBSCAN':
# enforce default value
if not self.hyperparams['min_samples']:
min_samples = 5
else:
min_samples = self.hyperparams['min_samples']
SimilarityMatrix = sloth.GenerateSimilarityMatrix(inputs.values)
nclusters, labels, cnt = sloth.HClusterSimilarityMatrix(SimilarityMatrix, min_samples)
else:
# enforce default value
if not self.hyperparams['nclusters']:
nclusters = 4
else:
nclusters = self.hyperparams['nclusters']
labels = sloth.ClusterSeriesKMeans(inputs.values, nclusters, 'GlobalAlignmentKernelKMeans')
# add metadata to output
out_df_sloth = pandas.DataFrame(labels)
out_df_sloth.columns = ['labels']
# initialize the output dataframe as input dataframe (results will be appended to it)
# out_df = d3m_DataFrame(inputs)
sloth_df = d3m_DataFrame(out_df_sloth)
# first column ('labels')
col_dict = dict(sloth_df.metadata.query((metadata_base.ALL_ELEMENTS, 0)))
col_dict['structural_type'] = type("1")
col_dict['name'] = 'labels'
col_dict['semantic_types'] = ('http://schema.org/Integer', 'https://metadata.datadrivendiscovery.org/types/PredictedTarget')
sloth_df.metadata = sloth_df.metadata.update((metadata_base.ALL_ELEMENTS, 0), col_dict)
# concatentate final output frame -- not real consensus from program, so commenting out for now
# out_df = utils_cp.append_columns(out_df, sloth_df)
return CallResult(sloth_df)
if __name__ == '__main__':
# Load data and preprocessing
input_dataset = container.Dataset.load('file:///data/home/jgleason/D3m/datasets/seed_datasets_current/66_chlorineConcentration/66_chlorineConcentration_dataset/datasetDoc.json')
ds2df_client = DatasetToDataFrame(hyperparams = {"dataframe_resource":"1"})
df = d3m_DataFrame(ds2df_client.produce(inputs = input_dataset).value)
ts_loader = TimeSeriesLoaderPrimitive(hyperparams = {"time_col_index":0, "value_col_index":1,"file_col_index":1})
metadata_dict = dict(df.metadata.query_column(ts_loader.hyperparams['file_col_index']))
metadata_dict['semantic_types'] = ('https://metadata.datadrivendiscovery.org/types/FileName', 'https://metadata.datadrivendiscovery.org/types/Timeseries')
metadata_dict['media_types'] = ('text/csv',)
metadata_dict['location_base_uris'] = ('file:///data/home/jgleason/D3m/datasets/seed_datasets_current/66_chlorineConcentration/66_chlorineConcentration_dataset/timeseries/',)
df.metadata = df.metadata.update_column(ts_loader.hyperparams['file_col_index'], metadata_dict)
ts_values = ts_loader.produce(inputs = df)
#storc_client = Storc(hyperparams={'algorithm':'GlobalAlignmentKernelKMeans','nclusters':4})
storc_client = Storc(hyperparams={'algorithm':'DBSCAN','eps':0.5, 'min_samples':5})
#frame = pandas.read_csv("path/csv_containing_one_series_per_row.csv",dtype=str)
result = storc_client.produce(inputs = ts_values.value.head(100))
print(result.value)
| {"/SlothD3MWrapper/__init__.py": ["/SlothD3MWrapper/Storc.py"]} |
51,459 | nirvguy/pyS | refs/heads/master | /pyS/S/language.py | from .datatypes import SInt, STuple, SList
from . import RT
class SInstruction(SInt):
"""S Instruction
"""
def __init__(self, z):
SInt.__init__(self, z)
def decode(self):
"""Decodes S Instruction into a S Runtime Instruction
"""
(a, y) = STuple(self.z).decode()
(b, c) = STuple(y).decode()
return RT.Instruction(label = a if not a == 0 else None,
nvar = c + 1,
instr_t = RT.InstructionType(b)
if b <= 2 else \
RT.InstructionType.Goto,
glabel = b-2 if b > 2 else None)
@staticmethod
def encode(rt_inst):
"""Encodes RT.Instruction into a SInstruction
Attributes:
rt_inst (RT.Instruction) : Runtime Instruction to encode
"""
a = rt_inst.label if rt_inst.label is not None else 0
c = rt_inst.nvar - 1
if rt_inst.instr_t == RT.InstructionType.Goto:
b = rt_inst.glabel + 2
else:
b = rt_inst.instr_t.value
return SInstruction(STuple.encode((a, STuple.encode((b, c)).z)))
class SProgram(SList):
"""S Code
"""
def __init__(self, z):
SList.__init__(self, z)
def decode(self):
"""Decodes SProgram into a list of RT.Instruction
Yields:
Runtime Instruction per line
"""
return (SInstruction(i).decode() for i in super(SProgram, self).decode())
@staticmethod
def encode(rits):
"""Encodes list of RT.Instruction into a SProgram
Attributes:
rits (iterable of RT.Instruction): Runtime Instructions
"""
return SProgram(SList.encode([SInstruction.encode(rit).z for rit in rits]))
def __str__(self):
return "\n".join(map(str, self.decode()))
| {"/pyS/S/language.py": ["/pyS/S/datatypes.py"], "/pyS/S/interp.py": ["/pyS/S/language.py", "/pyS/S/RT.py"], "/pyS/parser/parser.py": ["/pyS/S/language.py"], "/pyS/parser/lexer_rules.py": ["/pyS/parser/tokens.py"], "/pyS/Sdbg.py": ["/pyS/S/language.py", "/pyS/S/interp.py"], "/pyS/Srun.py": ["/pyS/S/language.py", "/pyS/S/interp.py"], "/pyS/S/datatypes.py": ["/pyS/S/math.py"], "/testing/test_datatypes.py": ["/pyS/S/datatypes.py"], "/pyS/parser/parser_rules.py": ["/pyS/parser/tokens.py"]} |
51,460 | nirvguy/pyS | refs/heads/master | /pyS/S/RT.py | from enum import Enum
class InstructionType(Enum):
"""Enum for the instruction types
"""
Assign=0
Increment=1
Decrement=2
Goto=3
class Instruction:
"""Runtime S Instruction
Attributes:
label (int): Label number at the instruction
or None if instruction is not labeled
nvar (int): Variable number
instr_t (RT.InstructionType): Type of instruction
glabel (int): Jump label number of goto instruction
"""
def __init__(self, label, nvar, instr_t, glabel):
"""
Constructor
"""
self.label = label
self.nvar = nvar
self.instr_t = instr_t
self.glabel = glabel
def __str__(self):
ret = ''
if self.label is not None:
ret += 'E_{0}: '.format(self.label)
if self.instr_t == InstructionType.Assign:
ret += 'V_{0} <- V_{0}'.format(self.nvar)
elif self.instr_t == InstructionType.Increment:
ret += 'V_{0} <- V_{0} + 1'.format(self.nvar)
elif self.instr_t == InstructionType.Decrement:
ret += 'V_{0} <- V_{0} - 1'.format(self.nvar)
else:
ret += 'IF V_{0} =/= 0 GOTO E_{1}'.format(self.nvar,self.glabel)
return ret
| {"/pyS/S/language.py": ["/pyS/S/datatypes.py"], "/pyS/S/interp.py": ["/pyS/S/language.py", "/pyS/S/RT.py"], "/pyS/parser/parser.py": ["/pyS/S/language.py"], "/pyS/parser/lexer_rules.py": ["/pyS/parser/tokens.py"], "/pyS/Sdbg.py": ["/pyS/S/language.py", "/pyS/S/interp.py"], "/pyS/Srun.py": ["/pyS/S/language.py", "/pyS/S/interp.py"], "/pyS/S/datatypes.py": ["/pyS/S/math.py"], "/testing/test_datatypes.py": ["/pyS/S/datatypes.py"], "/pyS/parser/parser_rules.py": ["/pyS/parser/tokens.py"]} |
51,461 | nirvguy/pyS | refs/heads/master | /pyS/S/interp.py | #!/usr/bin/env
from .language import SProgram
from .RT import InstructionType
class StopProgram(Exception):
pass
class Variables:
def __init__(self):
self._vars = {}
def set(self, nvar, value):
if value <= 0:
self._vars.pop(nvar, None)
else:
self._vars[nvar] = value
def get(self, nvar):
return self._vars.get(nvar, 0)
class SInterp:
def __init__(self, code, args={}):
self._instrlist = list(SProgram(code).decode())
self._vars = Variables()
self._lines_by_label = {}
self._pos = 0
# Process labels
last_label = None
for lineno, rt_inst in enumerate(self._instrlist):
if rt_inst.label is not None and \
rt_inst.label != last_label:
last_label = rt_inst.label
self._lines_by_label[last_label] = lineno
# Process arguments
for nvar, value in args.items():
self._vars.set(value)
def rewind(self, args):
self._pos = 0
self._vars = Variables()
# Process arguments
for nvar, value in args.items():
self._vars.set(nvar, value)
def lines(self):
return len(self._instrlist)
def pos(self):
return self._pos
def list(self, line, n=1):
if line >= len(self._instrlist) or line < 0:
raise StopProgram
start = max(line - n//2, 0)
end = min(start + n, len(self._instrlist))
return ((i, self._instrlist[i]) for i in range(start, end))
def step(self):
if self._pos >= len(self._instrlist):
raise StopProgram
rt_inst = self._instrlist[self._pos]
if rt_inst.instr_t == InstructionType.Goto and \
self._vars.get(rt_inst.nvar) != 0:
if rt_inst.glabel not in self._lines_by_label:
self._pos = len(it_instr)
raise StopProgram
else:
self._pos = self._lines_by_label[rt_inst.glabel]
return
elif rt_inst.instr_t == InstructionType.Increment:
self._vars.set(rt_inst.nvar, self._vars.get(rt_inst.nvar) + 1)
elif rt_inst.instr_t == InstructionType.Decrement:
self._vars.set(rt_inst.nvar, self._vars.get(rt_inst.nvar) - 1)
self._pos += 1
def var_value(self, varnum):
return self._vars.get(varnum)
| {"/pyS/S/language.py": ["/pyS/S/datatypes.py"], "/pyS/S/interp.py": ["/pyS/S/language.py", "/pyS/S/RT.py"], "/pyS/parser/parser.py": ["/pyS/S/language.py"], "/pyS/parser/lexer_rules.py": ["/pyS/parser/tokens.py"], "/pyS/Sdbg.py": ["/pyS/S/language.py", "/pyS/S/interp.py"], "/pyS/Srun.py": ["/pyS/S/language.py", "/pyS/S/interp.py"], "/pyS/S/datatypes.py": ["/pyS/S/math.py"], "/testing/test_datatypes.py": ["/pyS/S/datatypes.py"], "/pyS/parser/parser_rules.py": ["/pyS/parser/tokens.py"]} |
51,462 | nirvguy/pyS | refs/heads/master | /pyS/config.py | VERSION='0.1.0'
LIST_LINES = 10
| {"/pyS/S/language.py": ["/pyS/S/datatypes.py"], "/pyS/S/interp.py": ["/pyS/S/language.py", "/pyS/S/RT.py"], "/pyS/parser/parser.py": ["/pyS/S/language.py"], "/pyS/parser/lexer_rules.py": ["/pyS/parser/tokens.py"], "/pyS/Sdbg.py": ["/pyS/S/language.py", "/pyS/S/interp.py"], "/pyS/Srun.py": ["/pyS/S/language.py", "/pyS/S/interp.py"], "/pyS/S/datatypes.py": ["/pyS/S/math.py"], "/testing/test_datatypes.py": ["/pyS/S/datatypes.py"], "/pyS/parser/parser_rules.py": ["/pyS/parser/tokens.py"]} |
51,463 | nirvguy/pyS | refs/heads/master | /pyS/parser/parser.py | from ply.lex import lex
from ply.yacc import yacc
from ..S.language import SProgram
from . import lexer_rules
from . import parser_rules
def parse(strcode):
lexer = lex(module=lexer_rules)
parser = yacc(module=parser_rules)
return SProgram.encode(parser.parse(strcode, lexer))
| {"/pyS/S/language.py": ["/pyS/S/datatypes.py"], "/pyS/S/interp.py": ["/pyS/S/language.py", "/pyS/S/RT.py"], "/pyS/parser/parser.py": ["/pyS/S/language.py"], "/pyS/parser/lexer_rules.py": ["/pyS/parser/tokens.py"], "/pyS/Sdbg.py": ["/pyS/S/language.py", "/pyS/S/interp.py"], "/pyS/Srun.py": ["/pyS/S/language.py", "/pyS/S/interp.py"], "/pyS/S/datatypes.py": ["/pyS/S/math.py"], "/testing/test_datatypes.py": ["/pyS/S/datatypes.py"], "/pyS/parser/parser_rules.py": ["/pyS/parser/tokens.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.