index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
32,503
|
tonderys/File_Changer
|
refs/heads/master
|
/File_Finder_test.py
|
import unittest
import shutil
import os
from File_Finder import *
directory = 'testDirectory'
class File_finder_test(unittest.TestCase):
def remove_test_directory(self):
if os.path.exists(directory):
shutil.rmtree(directory)
def setUp(self):
self.remove_test_directory()
def tearDown(self):
self.remove_test_directory()
def test_file_not_found(self):
os.mkdir(directory)
self.assertEqual(File_Finder(directory, ".txt").output_code, 2)
def test_file_found(self):
os.mkdir(directory)
open("%s/file.txt" % directory,"w").close()
self.assertEqual(File_Finder(directory, ".txt").output_code, 1)
def test_invalid_path(self):
self.assertEqual(File_Finder(directory, ".txt").output_code, 3)
if __name__ == "__main__":
unittest.main()
|
{"/File_Changer_GUI.py": ["/File_Finder.py", "/File_Changer.py"], "/tests.py": ["/File_Finder_test.py", "/File_Changer_test.py", "/File_Changer_GUI_test.py"], "/File_Changer_test.py": ["/File_Changer.py"], "/File_Changer_GUI_test.py": ["/File_Changer_GUI.py"], "/File_Finder_test.py": ["/File_Finder.py"]}
|
32,525
|
zhouyonglong/two_tower_recommendation_system
|
refs/heads/master
|
/config.py
|
import json, os, re, codecs
import tensorflow as tf
flags = tf.app.flags
flags.DEFINE_boolean("train_on_cluster", True, "Whether the cluster info need to be passed in as input")
flags.DEFINE_string("train_dir", "", "")
flags.DEFINE_string("data_dir", "", "")
flags.DEFINE_string("log_dir", "", "")
flags.DEFINE_string("ps_hosts", "","")
flags.DEFINE_string("worker_hosts", "","")
flags.DEFINE_string("job_name", "", "One of 'ps', 'worker'")
flags.DEFINE_integer("task_index", 0, "Index of task within the job")
flags.DEFINE_string("model_dir", "hdfs:/user/ranker/ckpt/", "Base directory for the model.")
flags.DEFINE_string("output_model", "hdfs:/user/ranker/model/", "Saved model.")
flags.DEFINE_string("train_data", "./train_data.txt", "Directory for storing mnist data")
flags.DEFINE_string("eval_data", "./eval_data.txt", "Path to the evaluation data.")
flags.DEFINE_string("hidden_units", "512,256,128", "hidden units.")
flags.DEFINE_integer("train_steps",1000000, "Number of (global) training steps to perform")
flags.DEFINE_integer("batch_size", 256, "Training batch size")
flags.DEFINE_float("learning_rate", 0.0001, "learning rate")
flags.DEFINE_integer("save_checkpoints_steps", 10000, "Save checkpoints every this many steps")
FLAGS = flags.FLAGS
|
{"/main.py": ["/feature_processing.py", "/data_input.py", "/config.py"], "/data_input.py": ["/config.py"], "/model.py": ["/config.py", "/feature_processing.py"], "/feature_processing.py": ["/config.py"]}
|
32,526
|
zhouyonglong/two_tower_recommendation_system
|
refs/heads/master
|
/main.py
|
# encoding:utf-8
import os
import tensorflow as tf
from tensorflow import feature_column as fc
import feature_processing as fe
from feature_processing import FeatureConfig
import base_model
import data_input
import config
FLAGS = config.FLAGS
if FLAGS.run_on_cluster:
cluster = json.loads(os.environ["TF_CONFIG"])
task_index = int(os.environ["TF_INDEX"])
task_type = os.environ["TF_ROLE"]
def main(unused_argv):
feature_configs = FeatureConfig().create_features_columns()
classifier = tf.estimator.Estimator(model_fn=model.model_fn,
config=tf.estimator.RunConfig(model_dir=FLAGS.model_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
keep_checkpoint_max=3),
params={"feature_configs": feature_configs,
"hidden_units": list(map(int, FLAGS.hidden_units.split(","))),
"learning_rate": FLAGS.learning_rate}
)
def train_eval_model():
train_spec = tf.estimator.TrainSpec(input_fn=lambda: data_input.train_input_fn(FLAGS.train_data, FLAGS.batch_size),
max_steps=FLAGS.train_steps)
eval_spec = tf.estimator.EvalSpec(input_fn=lambda: data_input.eval_input_fn(FLAGS.eval_data, FLAGS.batch_size),
start_delay_secs=60,
throttle_secs = 30,
steps=1000)
tf.estimator.train_and_evaluate(classifier, train_spec, eval_spec)
def export_model():
feature_spec = feature_configs.feature_spec
feature_map = {}
for key, feature in feature_spec.items():
if key not in fe.feature_configs:
continue
if isinstance(feature, tf.io.VarLenFeature): # 可变长度
feature_map[key] = tf.placeholder(dtype=feature.dtype, shape=[1], name=key)
elif isinstance(feature, tf.io.FixedLenFeature): # 固定长度
feature_map[key] = tf.placeholder(dtype=feature.dtype, shape=[None, feature.shape[0]], name=key)
serving_input_recevier_fn = tf.estimator.export.build_raw_serving_input_receiver_fn(feature_map)
export_dir = classifier.export_saved_model(FLAGS.output_model, serving_input_recevier_fn)
# 模型训练
train_eval_model()
# 导出模型,只在chief中导出一次即可
if FLAGS.train_on_cluster:
if task_type == "chief":
export_model()
else:
export_model()
if __name__ == "__main__":
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
tf.logging.set_verbosity(tf.logging.INFO)
tf.app.run(main=main)
|
{"/main.py": ["/feature_processing.py", "/data_input.py", "/config.py"], "/data_input.py": ["/config.py"], "/model.py": ["/config.py", "/feature_processing.py"], "/feature_processing.py": ["/config.py"]}
|
32,527
|
zhouyonglong/two_tower_recommendation_system
|
refs/heads/master
|
/data_input.py
|
# coding:utf-8
import tensorflow as tf
import config
FLAGS = config.FLAGS
def parse_exp(example):
features_def = {}
features_def["label"] = tf.io.FixedLenFeature([1], tf.int64)
"""
数据解析逻辑
"""
features = tf.io.parse_single_example(example, features_def)
label = features["label"]
return features, label
def train_input_fn(filenames=None, batch_size=128):
with tf.gfile.Open(filenames) as f:
filenames = f.read().split()
if FLAGS.train_on_cluster:
files_all = []
for f in filenames:
files_all += tf.gfile.Glob(f)
train_worker_num = len(FLAGS.worker_hosts.split(","))
hash_id = FLAGS.task_index if FLAGS.job_name == "worker" else train_worker_num - 1
files_shard = [files for i, files in enumerate(files_all) if i % train_worker_num == hash_id]
dataset = tf.data.TFRecordDataset(files_shard)
else:
files = tf.data.Dataset.list_files(filenames)
dataset = tf.data.TFRecordDataset(files)
dataset = dataset.shuffle(batch_size*10)
dataset = dataset.map(parse_exp, num_parallel_calls=8)
dataset = dataset.batch(batch_size).prefetch(1)
return dataset
def eval_input_fn(filenames=None, batch_size=128):
with tf.gfile.Open(filenames) as f:
filenames = f.read().split()
files = tf.data.Dataset.list_files(filenames)
dataset = files.apply(tf.contrib.data.parallel_interleave(lambda filename: tf.data.TFRecordDataset(files), buffer_output_elements=batch_size*20, cycle_length=10))
dataset = dataset.map(parse_exp, num_parallel_calls=4)
dataset = dataset.batch(batch_size)
return dataset
|
{"/main.py": ["/feature_processing.py", "/data_input.py", "/config.py"], "/data_input.py": ["/config.py"], "/model.py": ["/config.py", "/feature_processing.py"], "/feature_processing.py": ["/config.py"]}
|
32,528
|
zhouyonglong/two_tower_recommendation_system
|
refs/heads/master
|
/model.py
|
# coding:utf-8
import tensorflow as tf
from tensorflow import feature_column as fc
import config
import feature_processing as fe
FLAGS = config.FLAGS
def build_user_model(features, mode, params):
# 特征输入
feature_inputs = []
for key, value in params["feature_configs"].user_columns.items():
feature_inputs.append(tf.input_layer(features, value))
# 特征拼接
net = tf.concat(feature_inputs, axis=1)
# 全连接
for idx, units in enumerate(params["hidden_units"]):
net = tf.layers.dense(net, units=units, activation=tf.nn.leaky_relu, name="user_fc_layer_%s"%idx)
net = tf.layers.dropout(net, 0.4, training=(mode == tf.estimator.ModeKeys.TRAIN))
# 最后输出
net = tf.layers.dense(net, units=128, name="user_output_layer")
return net
def build_item_model(features, mode, params):
# 特征输入
feature_inputs = []
for key, value in params["feature_configs"].item_columns.items():
feature_inputs.append(tf.input_layer(features, value))
# 特征拼接
net = tf.concat(feature_inputs, axis=1)
# 全连接
for idx, units in enumerate(params["hidden_units"]):
net = tf.layers.dense(net, units=units, activation=tf.nn.leaky_relu, name="user_fc_layer_%s"%idx)
net = tf.layers.dropout(net, 0.4, training=(mode == tf.estimator.ModeKeys.TRAIN))
# 最后输出
net = tf.layers.dense(net, units=128, name="user_output_layer")
return net
def model_fn(features, labels, mode, params):
user_net = build_user_model(features, mode, params)
item_net = build_item_model(features, mode, params)
dot = tf.reduce_sum(tf.multiply(user_net, item_net), axis=1, keepdims=True)
pred = tf.sigmoid(dot)
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode, predictions={"output": pred})
if mode == tf.estimator.ModeKeys.EVAL:
loss = tf.losses.log_loss(labels, pred)
metrics = {"auc": tf.metrics.auc(labels=labels, predictions=pred)}
return tf.estimator.EstimatorSpec(mode, loss=loss, eval_metric_ops=metrics)
if mode == tf.estimator.ModeKeys.TRAIN:
loss = tf.losses.log_loss(labels, pred)
global_step = tf.train.get_global_step()
learning_rate = tf.train.exponential_decay(params["learning_rate"], global_step, 100000, 0.9, staircase=True)
train_op = (tf.train.AdagradOptimizer(learning_rate).minimize(loss, global_step=global_step))
return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)
|
{"/main.py": ["/feature_processing.py", "/data_input.py", "/config.py"], "/data_input.py": ["/config.py"], "/model.py": ["/config.py", "/feature_processing.py"], "/feature_processing.py": ["/config.py"]}
|
32,529
|
zhouyonglong/two_tower_recommendation_system
|
refs/heads/master
|
/feature_processing.py
|
#coding:utf-8
import tensorflow as tf
from tensorflow import feature_column as fc
import config
FLAGS = config.FLAGS
class FeatureConfig(object):
def __init__(self):
self.user_columns = dict()
self.item_columns = dict()
self.feature_spec = dict()
def create_features_columns(self):
# 向量类特征
user_vector = fc.numeric_column(key="user_vector", shape=(128,), default_value=[0.0] * 128, dtype=tf.float32)
item_vector = fc.numeric_column(key="item_vector", shape=(128,), default_value=[0.0] * 128, dtype=tf.float32)
# 分桶类特征
age = fc.numeric_column(key="age", shape=(1,), default_value=[0], dtype=tf.int64)
age = fc.bucketized_column(input_fc, boundaries=[0,10,20,30,40,50,60,70,80])
age = fc.embedding_column(age, dimension=32, combiner='mean')
# 分类特征
city = fc.categorical_column_with_identity(key="city", num_buckets=1000, default_value=0)
city = fc.embedding_column(city, dimension=32, combiner='mean')
# hash特征
device_id = fc.categorical_column_with_hash_bucket(key="device_id", hash_bucket_size=1000000, dtype=tf.int64)
device_id = fc.embedding_column(device_id, dimension=32, combiner='mean')
item_id = fc.categorical_column_with_hash_bucket(key="item_id", hash_bucket_size=10000, dtype=tf.int64)
item_id = fc.embedding_column(device_id, dimension=32, combiner='mean')
self.user_columns["user_vector"] = user_vector
self.user_columns["age"] = age
self.user_columns["city"] = city
self.user_columns["device_id"] = device_id
self.item_columns["item_vector"] = item_vector
self.item_columns["item_id"] = item_id
self.feature_spec = tf.feature_column.make_parse_example_spec(self.user_columns.values()+self.item_columns.values())
return self
|
{"/main.py": ["/feature_processing.py", "/data_input.py", "/config.py"], "/data_input.py": ["/config.py"], "/model.py": ["/config.py", "/feature_processing.py"], "/feature_processing.py": ["/config.py"]}
|
32,532
|
leonidguadalupe/fun-backend-service
|
refs/heads/master
|
/algorithms/utils/__init__.py
|
from .sort import Sort # noqa: F401
from .quick import QuickSort # noqa: F401
__all__ = ["QuickSort"]
|
{"/algorithms/utils/__init__.py": ["/algorithms/utils/sort.py", "/algorithms/utils/quick.py"], "/algorithms/tests/test_sort.py": ["/algorithms/utils/__init__.py"], "/algorithms/tests/test_quicksort.py": ["/algorithms/utils/__init__.py"], "/algorithms/utils/quick.py": ["/algorithms/utils/sort.py"]}
|
32,533
|
leonidguadalupe/fun-backend-service
|
refs/heads/master
|
/algorithms/utils/sort.py
|
from abc import ABC, abstractmethod
class Sort(ABC):
def __init__(self, array):
self.array = array
self.result = []
super().__init__()
@abstractmethod
def sort(self):
pass
@abstractmethod
def serialize(self):
pass
|
{"/algorithms/utils/__init__.py": ["/algorithms/utils/sort.py", "/algorithms/utils/quick.py"], "/algorithms/tests/test_sort.py": ["/algorithms/utils/__init__.py"], "/algorithms/tests/test_quicksort.py": ["/algorithms/utils/__init__.py"], "/algorithms/utils/quick.py": ["/algorithms/utils/sort.py"]}
|
32,534
|
leonidguadalupe/fun-backend-service
|
refs/heads/master
|
/algorithms/tests/test_sort.py
|
import json
import pytest
from abc import ABC
from algorithms.utils import Sort
def test_sort_is_abstract():
"""
Test expects Sort class to be subclass of
abstract base class
"""
assert issubclass(Sort,ABC)
|
{"/algorithms/utils/__init__.py": ["/algorithms/utils/sort.py", "/algorithms/utils/quick.py"], "/algorithms/tests/test_sort.py": ["/algorithms/utils/__init__.py"], "/algorithms/tests/test_quicksort.py": ["/algorithms/utils/__init__.py"], "/algorithms/utils/quick.py": ["/algorithms/utils/sort.py"]}
|
32,535
|
leonidguadalupe/fun-backend-service
|
refs/heads/master
|
/algorithms/tests/test_quicksort.py
|
import json
import pytest
from algorithms.utils import QuickSort
def test_quicksort_url_return_is_valid_json(rf):
request = rf.get('/sort/quick')
print(request)
with pytest.raises(Exception):
json.loads(request)
def test_quicksort_returns_list():
"""
Test for if quicksort function returns a list type
and if it is a multi dimensional array with dictionary objects
inside.
"""
sample_array = [6,5,4,3,8,9]
a = QuickSort(sample_array)
# check if array is list
assert isinstance(a.result,list)
# check if array is multi dimensional
assert isinstance(a.result[0],dict)
def test_quicksort_check_keys():
sample_array = [6,5,4,3,8,9]
a = QuickSort(sample_array)
assert "list" in a.result[0]
def test_quicksort_output():
"""
Test for final result of the sorting algorithm
"""
sample_array = [6,5,4,3,1,9]
a = QuickSort(sample_array)
assert a.array == sorted(sample_array)
def test_quicksort_serialize():
sample_array = [6,5,4,3,1,9]
a = QuickSort(sample_array)
assert isinstance(a.serialize(), str)
|
{"/algorithms/utils/__init__.py": ["/algorithms/utils/sort.py", "/algorithms/utils/quick.py"], "/algorithms/tests/test_sort.py": ["/algorithms/utils/__init__.py"], "/algorithms/tests/test_quicksort.py": ["/algorithms/utils/__init__.py"], "/algorithms/utils/quick.py": ["/algorithms/utils/sort.py"]}
|
32,536
|
leonidguadalupe/fun-backend-service
|
refs/heads/master
|
/algorithms/utils/quick.py
|
import copy
import json
from .sort import Sort
class QuickSort(Sort):
def __init__(self, array):
super().__init__(array)
self.sort() # sort after array init
def _swap(self: object, array: list, left: int, right: int) -> list:
array[left], array[right] = array[right], array[left]
return array
def _doQuickSort(self: object, array: list, pivot: int, left: int, right: int) -> None:
if left >= right:
return
while right >= left:
if array[pivot] < array[left] and array[pivot] > array[right]:
self._swap(array, left, right)
self.result.append({
"list": copy.deepcopy(array),
"right": right,
"left": left,
"pivot": pivot
})
continue #cut here to show swap change in frontend
if array[pivot] >= array[left]:
left += 1
if array[pivot] <= array[right]:
right -= 1
self.result.append({
"list": copy.deepcopy(array),
"right": right,
"left": left,
"pivot": pivot
})
# swap pivot with right
self._swap(array, pivot, right)
self.result.append({
"list": copy.deepcopy(array),
"right": right,
"left": left,
"pivot": pivot
})
# divide and conquer
self._doQuickSort(array, pivot, pivot+1, right-1)
self._doQuickSort(array, left, left+1, len(array)-1)
return
def sort(self):
self._doQuickSort(self.array, 0, 1, len(self.array)-1)
return self.result
# Let's sort and serialize boiz
def serialize(self) -> str:
return json.dumps(self.result)
|
{"/algorithms/utils/__init__.py": ["/algorithms/utils/sort.py", "/algorithms/utils/quick.py"], "/algorithms/tests/test_sort.py": ["/algorithms/utils/__init__.py"], "/algorithms/tests/test_quicksort.py": ["/algorithms/utils/__init__.py"], "/algorithms/utils/quick.py": ["/algorithms/utils/sort.py"]}
|
32,537
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/userApp/models.py
|
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
User = get_user_model()
class SystemUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
phone = models.CharField(max_length=30, blank=True)
nationalCode = models.CharField(max_length=10)
approved = models.BooleanField(default=False)
date_created = models.DateTimeField(auto_now_add=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
SystemUser.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,538
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/taradodApp/admin.py
|
from django.contrib import admin
# Register your models here.
from .models import Taradod
class TaradodAdmin(admin.ModelAdmin):
ordering = ['seen']
list_display_links = ['plate']
list_display = ('plate','img', 'seen', 'approved')
list_filter = ('approved', 'seen')
admin.site.register(Taradod, TaradodAdmin)
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,539
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/userApp/admin.py
|
from django.contrib import admin
from .models import SystemUser
class UserAdmin(admin.ModelAdmin):
ordering = ['date_created']
list_display = ('user_fullname', 'user', 'phone', 'nationalCode', 'approved', 'date_created')
list_filter = ('approved','date_created')
def user_fullname(self, obj):
return "{}".format(obj.user.get_full_name())
admin.site.site_header = "Plate Detector"
admin.site.register(SystemUser, UserAdmin)
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,540
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/taradodApp/urls.py
|
from django.urls import path
from .views import *
urlpatterns = [
path('<int:traffic_id>/', traffic_report, name='traffic_report'),
# path('', views.register, name='register'),
]
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,541
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/userApp/urls.py
|
from django.urls import path
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path('', views.login, name='login'),
url(r'logout/', auth_views.LogoutView.as_view(next_page='login'), name='logout'),
]
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,542
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/taradodApp/models.py
|
from django.db import models
from django.urls import reverse
# Create your models here.
class Taradod(models.Model):
plate = models.CharField(max_length=50, blank=True)
img = models.ImageField(upload_to='TaradodPic/', blank=True)
seen = models.DateTimeField(auto_now_add=True)
approved = models.BooleanField(default=False)
def short_status(self):
return '%s' % self.plate
def get_absolute_url(self):
return reverse('traffic_report', kwargs={
'traffic_id': self.id
})
def __str__(self):
return '%s %s %s' % (self.plate, self.seen, self.approved)
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,543
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/registerApp/models.py
|
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
ALPHA_CHOICES = (
("1", "الف"),
("2", "ب"),
("3", "پ"),
("4", "ت"),
("5", "ث"),
("6", "ج"),
("7", "چ"),
("8", "ح"),
("9", "خ"),
("10", "د"),
("11", "ذ"),
("12", "ر"),
("13", "ز"),
("14", "ژ"),
("15", "س"),
("16", "ش"),
("17", "ص"),
("18", "ض"),
("19", "ط"),
("20", "ظ"),
("21", "ع"),
("22", "غ"),
("23", "ف"),
("24", "ق"),
("25", "ک",),
("26", "گ"),
("27", "ل"),
("28", "م"),
("29", "ن"),
("30", "و",),
("31", "ه"),
("32", "ی"),
("33", "D"),
("34", "S"),
)
PLATE_CHOICES = (
("1", "سواری ملی"),
("2", "سواری منظقه ازاد انزلی"),)
class Plate(models.Model):
plate_type = models.CharField(
max_length=3,
choices=PLATE_CHOICES,
blank=True,
default=1
)
firstNum = models.IntegerField()
secondNum = models.IntegerField()
cityNum = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(10)], blank=True, default=100)
alpha = models.CharField(
max_length=3,
choices=ALPHA_CHOICES,
blank=True,
default=1
)
class Meta:
unique_together = ('firstNum', 'secondNum', 'cityNum')
def __str__(self):
if self.plate_type == '2':
return '%s - %s - %s' % (self.get_plate_type_display(), self.secondNum, self.firstNum)
else:
return '%s ایران - %s - %s - %s' % (self.cityNum, self.secondNum, self.get_alpha_display(), self.firstNum)
def get_status(self):
if self.plate_type == '2':
return '%s - %s - %s' % (self.get_plate_type_display(), self.secondNum, self.firstNum)
else:
return '%s ایران - %s - %s - %s' % (self.cityNum, self.secondNum, self.get_alpha_display(), self.firstNum)
class Owner(models.Model):
first_name = models.CharField(max_length=20)
img = models.ImageField(upload_to='profilePic/', blank=True)
family_name = models.CharField(max_length=30)
phone = models.CharField(max_length=11, blank=True)
nationalCode = models.CharField(max_length=10, unique=True)
description = models.TextField(max_length=300, blank=True)
def __str__(self):
return 'Full Name: %s %s | phone:%s | National Code: %s | %s' % (
self.first_name, self.family_name, self.phone, self.nationalCode, self.description)
class Vehicle(models.Model):
created = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
plate = models.OneToOneField(Plate, on_delete=models.CASCADE, blank=True)
owner = models.ForeignKey(Owner, on_delete=models.CASCADE)
img = models.ImageField(upload_to='carPic', blank=True)
color = models.CharField(max_length=10, blank=True)
type = models.CharField(max_length=20, blank=True)
def __str__(self):
return '%s %s %s' % (self.plate, self.color, self.type)
def get_status(self):
return '%s' % self.plate
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,544
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/taradodApp/apps.py
|
from django.apps import AppConfig
class TaradodappConfig(AppConfig):
name = 'taradodApp'
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,545
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/registerApp/admin.py
|
from django.contrib import admin
from .models import Vehicle, Plate, Owner
class InlineVehicle(admin.StackedInline):
model = Vehicle
extra = 1
class OwnerAdmin(admin.ModelAdmin):
inlines = [InlineVehicle]
list_display = ('first_name', 'family_name', 'nationalCode', 'phone', 'img', 'description')
list_filter = ('nationalCode',)
class VehicleAdmin(admin.ModelAdmin):
list_filter = ('active',)
list_display = ('owner', 'plate', 'img', 'color', 'type','created','active')
class PlateAdmin(admin.ModelAdmin):
list_display = ('plate_type', 'firstNum', 'alpha', 'secondNum', 'cityNum')
list_filter = ('plate_type', 'cityNum', 'alpha')
admin.site.register(Vehicle, VehicleAdmin)
admin.site.register(Plate, PlateAdmin)
admin.site.register(Owner, OwnerAdmin)
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,546
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/registerApp/views.py
|
from django.shortcuts import render
from .forms import RegisterForm
from .models import Owner, Plate, Vehicle
from django.db import IntegrityError
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
import enum
@login_required(login_url='login')
def register(request):
# register_form = RegisterForm(request.POST or None)
status = 0
if request.method == 'POST':
if request.POST.get('form-key') == 'ثبت-مشخصات':
# status = 1
register_form = RegisterForm(request.POST, request.FILES)
if register_form.is_valid():
try:
if register_form.cleaned_data['owner_select'] == 'old_owner':
owner_obj = Owner.objects.get(nationalCode=register_form.cleaned_data['owner_nationalcode'])
else:
owner_obj = Owner(first_name=register_form.cleaned_data['owner_firstname'] or "-",
family_name=register_form.cleaned_data['owner_lastname'] or "-",
nationalCode=register_form.cleaned_data['owner_nationalcode'],
phone=register_form.cleaned_data['owner_phone'] or "-",
img=register_form.cleaned_data['owner_picture'],
description=register_form.cleaned_data['owner_description'])
owner_obj.save()
except Owner.DoesNotExist:
status = -1
except IntegrityError:
status = -1
else:
try:
if register_form.cleaned_data['plate_type'] == '1':
plate_obj = Plate(plate_type='1',
firstNum=register_form.cleaned_data['plate_firstnum'],
secondNum=register_form.cleaned_data['plate_secondnum'],
cityNum=register_form.cleaned_data['plate_citynum'],
alpha=register_form.cleaned_data['plate_alpha'])
else:
plate_obj = Plate(plate_type='2',
firstNum=register_form.cleaned_data['plate_firstnum'],
secondNum=register_form.cleaned_data['plate_secondnum'])
vehicle_obj = Vehicle(owner=owner_obj,
plate=plate_obj,
color=register_form.cleaned_data['vehicle_color'],
type=register_form.cleaned_data['vehicle_type'],
img=register_form.cleaned_data['vehicle_picture'])
plate_obj.save()
vehicle_obj.save()
except IntegrityError:
status = -1
else:
status = 1
context = {
'register_form': RegisterForm(),
'status': status
}
return render(request, 'form.html', context)
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,547
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/userApp/forms.py
|
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.utils.translation import ugettext_lazy as _
from .models import SystemUser
class SignUpForm(UserCreationForm):
# first_name = forms.CharField(max_length=30, required=False, help_text='Optional.', label=u'نام')
# last_name = forms.CharField(max_length=30, required=False, help_text='Optional.', label=u'نام خانوادگی')
# email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.',
# label=u'پست الکترونیکی')
# phone = forms.CharField(max_length=30, required=False, label=u'شماره موبایل', widget=forms.TextInput(
# attrs={'class': 'form-control', 'autocomplete': 'off', 'pattern': '[0-9]+', 'title': 'Enter numbers Only '}))
# password1 = forms.CharField(label=_(u"رمز عبور"),
# widget=forms.PasswordInput)
# password2 = forms.CharField(label=_(u"تایید رمز عبور"),
# widget=forms.PasswordInput,
# help_text=_("Enter the same password as above, for verification."))
# birth_date = forms.DateField(required=False, help_text="Enter your birth date.", label=u'تاریخ تولد')
# img = forms.ImageField(required=False)
phone = forms.CharField(max_length=11)
nationalCode = forms.CharField(max_length=10)
class Meta:
User._meta.get_field('email')._unique = True
model = User
fields = ['username', 'first_name', 'last_name', 'phone', 'email', 'password1', 'password2', 'nationalCode']
# labels = {
# 'username': _(u'نام کاربری'),
# }
# class SignUpForm(forms.ModelForm):
# class Meta:
# model = SystemUser
# fields = ['user', 'nationalCode', 'phone']
# widgets = {
# 'user': forms.Select(choices=User.objects.all(), attrs={'class': 'form-control'}),
# # 'nationalCode': forms.ClearableFileInput(attrs={'class': 'form-control', 'multiple': False}),
# 'phone': forms.TextInput(attrs={'class': 'form-control'}),
# 'nationalCode': forms.TextInput(attrs={'class': 'form-control'})
# }
class LoginForm(forms.Form):
username = forms.CharField(max_length=255, required=True)
password = forms.CharField(widget=forms.PasswordInput, required=True)
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("login error")
return self.cleaned_data
def login(self, request):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
user = authenticate(username=username, password=password)
return user
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,548
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/taradodApp/views.py
|
import jdatetime
from django.shortcuts import render, get_object_or_404
from django.db.models import Q
from .models import Taradod
from registerApp.models import Vehicle
from django.contrib.auth.decorators import login_required
ALPHA_MAP = {x: y + 1 for y, x in enumerate(
['الف', 'ب', 'پ', 'ت', 'ث', 'ج', 'چ', 'ح', 'خ', 'د', 'ذ', 'ر', 'ز', 'ژ', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع',
'غ', 'ف', 'ق', 'ک', 'گ', 'ل', 'م', 'ن', 'و', 'ه', 'ی', 'D', 'S']
)}
@login_required(login_url='login')
def traffic_report(request, traffic_id):
this_traffic = get_object_or_404(Taradod, id=traffic_id)
plate_split = this_traffic.plate.split('-')
taradods = Taradod.objects.filter(
Q(plate=this_traffic.plate)
)
for taradod in taradods:
taradod.seen = jdatetime.datetime.fromgregorian(day=taradod.seen.day, month=taradod.seen.month.numerator,
year=taradod.seen.year, hour=taradod.seen.astimezone().hour,
minute=taradod.seen.astimezone().minute,
second=taradod.seen.astimezone().second)
if len(plate_split) == 3: # پلاک انزلی
vehicle = Vehicle.objects.filter(
(Q(plate__plate_type=2) & Q(plate__firstNum=int(plate_split[2])) & Q(plate__secondNum=int(plate_split[1])))
)
else: # پلاک عادی
vehicle = Vehicle.objects.filter(
(Q(plate__plate_type=1) & Q(plate__alpha=ALPHA_MAP[plate_split[2].strip()]) &
Q(plate__firstNum=int(plate_split[3])) & Q(plate__secondNum=int(plate_split[1])))
)
# changing active status of the current car with button form
if request.method == 'POST':
car = Vehicle.objects.get(id=vehicle[0].id)
car.active = False
car.save()
# end of action
context = {
'this_traffic': this_traffic,
'this_vehicle': vehicle[0],
'taradods': taradods
}
return render(request, 'traffic_report.html', context)
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,549
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/userApp/views.py
|
from django.shortcuts import render, redirect
from django.contrib.auth import login as auth_login, logout
from .forms import LoginForm, SignUpForm
from django.contrib import messages
def login(request):
if request.user.is_authenticated:
return redirect('index')
else:
login_form, signup_form = None, None
status = 0
if request.method == "POST":
if request.POST.get('form-key') == 'ورود':
login_form = LoginForm(request.POST or None)
if login_form.is_valid():
user = login_form.login(request)
if user:
if user.profile.approved:
auth_login(request, user)
return redirect('index')
messages.warning(request,
'نام کاربری یا رمز عبور وارد شده، در سامانه موجود نمی باشد')
if request.POST.get('form-key') == 'ثبت نام':
signup_form = SignUpForm(request.POST)
status = -1
if signup_form.is_valid():
user = signup_form.save()
user.refresh_from_db()
user.profile.birth_date = signup_form.cleaned_data.get('birth_date')
user.profile.phone = signup_form.cleaned_data.get('phone')
user.profile.nationalCode = signup_form.cleaned_data.get('nationalCode')
messages.success(request,
'مشخصات وارد شده با موفقیت در سامانه ثبت شد، منتظر تایید مدیر سامانه بمانید')
user.save()
# raw_password = signup_form.cleaned_data.get('password1')
# user = authenticate(username=user.username, password=raw_password)
# print(user)
# auth_login(request, user)
# status = 1
return redirect('logout')
if status == -1:
messages.error(request,
'خطا! مشخصات شما در سامانه ثبت نشد، دوباره مقادیر ورودی ها را چک نمایید')
context = {
'login_form': login_form,
'signup_form': signup_form,
}
return render(request, 'login-register.html', context)
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,550
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/registerApp/forms.py
|
from django import forms
from django.forms import ModelForm
from .models import Plate, Vehicle, Owner, \
ALPHA_CHOICES, PLATE_CHOICES
from django.core.validators import MaxValueValidator, MinValueValidator
OWNER_CHOICES = (
("new_owner", "ثبت مالک جدید"),
("old_owner", "از مالکین ثبت شده در سیستم"),)
class RegisterForm(forms.Form):
owner_select = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control'}), choices=OWNER_CHOICES)
owner_firstname = forms.CharField(max_length=20, required=False)
owner_lastname = forms.CharField(max_length=30, required=False)
owner_nationalcode = forms.CharField(max_length=10, required=True)
owner_phone = forms.CharField(max_length=11, required=False)
owner_description = forms.CharField(widget=forms.Textarea, required=False)
owner_picture = forms.ImageField(required=False)
plate_type = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control'}), choices=PLATE_CHOICES)
plate_firstnum = forms.IntegerField(required=True)
plate_secondnum = forms.IntegerField(required=True)
plate_citynum = forms.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(10)], required=False)
plate_alpha = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control'}), choices=ALPHA_CHOICES,
required=False)
vehicle_color = forms.CharField(max_length=10, required=True)
vehicle_type = forms.CharField(max_length=20, required=True)
vehicle_picture = forms.ImageField(required=False)
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,551
|
asal97/Computer-Vision-Project
|
refs/heads/master
|
/CVP/views.py
|
import datetime
import numpy as np
from django.shortcuts import render
from registerApp.models import Plate, Owner, Vehicle
from taradodApp.models import Taradod
import jdatetime
from django.db.models import Count
import calendar
from django.db.models.functions import ExtractDay, ExtractHour, ExtractWeekDay
from django.db.models import Q
from calendar import monthrange
import csv
from django.http import HttpResponse
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from collections import Counter
@login_required(login_url='login')
def index(request):
Taradod_list = Taradod.objects.filter(seen__gte=datetime.date.today())
Vehicle_list = []
for vehicle in Vehicle.objects.all():
if vehicle.active:
Vehicle_list.append(vehicle.plate.get_status())
for taradod in Taradod_list:
taradod.seen = jdatetime.datetime.fromgregorian(day=taradod.seen.day, month=taradod.seen.month.numerator,
year=taradod.seen.year, hour=taradod.seen.astimezone().hour,
minute=taradod.seen.astimezone().minute,
second=taradod.seen.astimezone().second
)
if taradod.plate in Vehicle_list:
t = Taradod.objects.get(id=taradod.id)
t.approved = True
t.save()
context = {
'Taradod_list': Taradod_list,
}
return render(request, 'index.html', context)
def get_total_today(taradod):
qn = taradod.filter(
seen__day=datetime.datetime.now().astimezone().day
).annotate(
hour=ExtractHour('seen'),
).values(
'hour'
).annotate(
n=Count('pk')
).order_by('hour')
data = Counter({d['hour']: d['n'] for d in qn})
ds = 23
result = [data[i] for i in range(0, ds + 1)]
return result
def get_week_day(taradod):
today_num = ((datetime.datetime.today().weekday()) + 2) % 7
start = today_num - 0
days = []
for i in range(0, start):
days.append(0)
start = datetime.datetime.today().date() - datetime.timedelta(days=start)
endCount = 6 - today_num
end = datetime.datetime.today().date() + datetime.timedelta(days=endCount)
week = taradod.objects.filter(seen__gte=start,
seen__lte=end)
if len(week) > 0:
firstCar = week[0]
count = 0
for car in week:
if car.seen.day == firstCar.seen.day:
count += 1
else:
days.append(count)
dayDif = car.seen.day - firstCar.seen.day
for i in range(0, dayDif - 1):
days.append(0)
firstCar = car
count = 1
days.append(count)
for i in range(0, endCount):
days.append(0)
return days
else:
return week
def get_this_month(taradod):
today = datetime.datetime.now()
if datetime.date(datetime.datetime.now().year, 3, 20) <= today.date() <= datetime.date(
datetime.datetime.now().year, 4, 19):
start = datetime.date(datetime.datetime.now().year, 3, 20)
end = datetime.date(datetime.datetime.now().year, 4, 19)
elif datetime.date(datetime.datetime.now().year, 4, 20) <= today.date() <= datetime.date(
datetime.datetime.now().year, 5, 20):
start = datetime.date(datetime.datetime.now().year, 4, 20)
end = datetime.date(datetime.datetime.now().year, 5, 19)
elif datetime.date(datetime.datetime.now().year, 5, 21) <= today.date() <= datetime.date(
datetime.datetime.now().year, 6, 20):
start = datetime.date(datetime.datetime.now().year, 5, 21)
end = datetime.date(datetime.datetime.now().year, 6, 20)
elif datetime.date(datetime.datetime.now().year, 6, 21) <= today.date() <= datetime.date(
datetime.datetime.now().year, 7, 21):
start = datetime.date(datetime.datetime.now().year, 6, 21)
end = datetime.date(datetime.datetime.now().year, 7, 21)
elif datetime.date(datetime.datetime.now().year, 7, 22) <= today.date() <= datetime.date(
datetime.datetime.now().year, 8, 21):
start = datetime.date(datetime.datetime.now().year, 7, 22)
end = datetime.date(datetime.datetime.now().year, 8, 21)
elif datetime.date(datetime.datetime.now().year, 8, 22) <= today.date() <= datetime.date(
datetime.datetime.now().year, 9, 21):
start = datetime.date(datetime.datetime.now().year, 8, 22)
end = datetime.date(datetime.datetime.now().year, 9, 21)
elif datetime.date(datetime.datetime.now().year, 9, 22) <= today.date() <= datetime.date(
datetime.datetime.now().year, 10, 21):
start = datetime.date(datetime.datetime.now().year, 9, 22)
end = datetime.date(datetime.datetime.now().year, 10, 21)
elif datetime.date(datetime.datetime.now().year, 10, 22) <= today.date() <= datetime.date(
datetime.datetime.now().year, 11, 20):
start = datetime.date(datetime.datetime.now().year, 10, 22)
end = datetime.date(datetime.datetime.now().year, 11, 20)
elif datetime.date(datetime.datetime.now().year, 11, 21) <= today.date() <= datetime.date(
datetime.datetime.now().year, 12, 20):
start = datetime.date(datetime.datetime.now().year, 11, 21)
end = datetime.date(datetime.datetime.now().year, 12, 20)
elif datetime.date(datetime.datetime.now().year, 12, 21) <= today.date() <= datetime.date(
datetime.datetime.now().year + 1, 1, 19):
start = datetime.date(datetime.datetime.now().year, 12, 21)
end = datetime.date(datetime.datetime.now().year + 1, 1, 19)
elif datetime.date(datetime.datetime.now().year - 1, 12, 21) <= today.date() <= datetime.date(
datetime.datetime.now().year, 1, 19):
start = datetime.date(datetime.datetime.now().year - 1, 12, 21)
end = datetime.date(datetime.datetime.now().year, 1, 19)
elif datetime.date(datetime.datetime.now().year, 1, 20) <= today.date() <= datetime.date(
datetime.datetime.now().year, 2, 18):
start = datetime.date(datetime.datetime.now().year, 1, 20)
end = datetime.date(datetime.datetime.now().year, 2, 18)
elif datetime.date(datetime.datetime.now().year, 2, 19) <= today.date() <= datetime.date(
datetime.datetime.now().year, 3, 20):
start = datetime.date(datetime.datetime.now().year, 11, 21)
end = datetime.date(datetime.datetime.now().year, 12, 20)
Month = taradod.filter(seen__gte=start,
seen__lte=end)
days = []
if len(Month) > 0:
firstCar = Month[0]
date = firstCar.seen.date() - start
for i in range(0, date.days):
days.append(0)
count = 0
for car in Month:
if car.seen.day == firstCar.seen.day:
count += 1
else:
days.append(count)
dayDif = car.seen.day - firstCar.seen.day
for i in range(0, dayDif - 1):
days.append(0)
firstCar = car
count = 1
days.append(count)
if Month[len(Month) - 1].seen.date() < end:
for i in range(0,
(end - Month[len(Month) - 1].seen.date()).days):
days.append(0)
return days
def get_this_year(taradod):
result = []
today = datetime.datetime.now()
if datetime.date(datetime.datetime.now().year, 3, 21) < today.date() < datetime.date(datetime.datetime.now().year,
12, 31):
year_second = 1
year_first = 0
else:
year_first = -1
year_second = 0
if calendar.isleap(today.year):
######################### Farvardin #################################
Month = taradod.filter(seen__gte=datetime.date(datetime.datetime.now().year + year_first, 3, 20),
seen__lte=datetime.date(
datetime.datetime.now().year + year_first, 4, 19))
result.append(len(Month))
######################### Ordibehesht #################################
Month = taradod.filter(seen__gte=datetime.date(datetime.datetime.now().year + year_first, 4, 20),
seen__lte=datetime.date(
datetime.datetime.now().year + year_first, 5, 20))
result.append(len(Month))
######################### Khordad #################################
Month = taradod.filter(seen__gte=datetime.date(datetime.datetime.now().year + year_first, 5, 21),
seen__lte=datetime.date(
datetime.datetime.now().year + year_first, 6, 20))
result.append(len(Month))
######################### Tir #################################
Month = taradod.filter(seen__gte=datetime.date(datetime.datetime.now().year + year_first, 6, 21),
seen__lte=datetime.date(
datetime.datetime.now().year + year_first, 7, 21))
result.append(len(Month))
######################### Mordad #################################
Month = taradod.filter(seen__gte=datetime.date(datetime.datetime.now().year + year_first, 7, 22),
seen__lte=datetime.date(
datetime.datetime.now().year + year_first, 8, 21))
result.append(len(Month))
######################### Shahrivar #################################
Month = taradod.filter(seen__gte=datetime.date(datetime.datetime.now().year + year_first, 8, 22),
seen__lte=datetime.date(
datetime.datetime.now().year + year_first, 9, 21))
result.append(len(Month))
######################### Mehr #################################
Month = taradod.filter(seen__gte=datetime.date(datetime.datetime.now().year + year_first, 9, 22),
seen__lte=datetime.date(
datetime.datetime.now().year + year_first, 10, 21))
result.append(len(Month))
######################### Aban #################################
Month = taradod.filter(seen__gte=datetime.date(datetime.datetime.now().year + year_first, 10, 22),
seen__lte=datetime.date(
datetime.datetime.now().year + year_first, 11, 20))
result.append(len(Month))
######################### Azar #################################
Month = taradod.filter(seen__gte=datetime.date(datetime.datetime.now().year + year_first, 11, 21),
seen__lte=datetime.date(
datetime.datetime.now().year + year_first, 12, 20))
result.append(len(Month))
######################### Dey #################################
Month = taradod.filter(seen__gte=datetime.date(datetime.datetime.now().year + year_first, 12, 21),
seen__lte=datetime.date(
datetime.datetime.now().year + year_first, 12, 31))
mid_year = len(Month)
Month = taradod.filter(seen__gte=datetime.date(datetime.datetime.now().year + year_second, 1, 1),
seen__lte=datetime.date(
datetime.datetime.now().year + year_second, 1, 19))
mid_year += len(Month)
result.append(mid_year)
######################### Bahman #################################
Month = taradod.filter(seen__gte=datetime.date(datetime.datetime.now().year + year_second, 1, 20),
seen__lte=datetime.date(
datetime.datetime.now().year + year_second, 2, 18))
result.append(len(Month))
######################### Esfand #################################
Month = taradod.filter(seen__gte=datetime.date(datetime.datetime.now().year + year_second, 2, 19),
seen__lte=datetime.date(
datetime.datetime.now().year + year_second, 3, 20))
result.append(len(Month))
return result
@login_required(login_url='login')
def table(request):
vehicle_status = []
Taradod_list = Taradod.objects.all()
Vehicle_list = Vehicle.objects.filter(
Q(active=True)
)
for vehicle in Vehicle_list:
vehicle_status.append(vehicle.plate.get_status())
# getting data for the diagram for table page
today = get_total_today(Taradod_list)
last_hour = today[len(today) - 1]
today = today[0:len(today) - 1]
# getting days of week
week = get_week_day(Taradod)
if len(week) > 0:
last_day = week[len(week) - 1]
week = week[0:len(week) - 1]
else:
week = np.zeros(6, dtype=int)
last_day = int(0)
days_of_month = get_this_month(Taradod_list)
if len(days_of_month) > 0:
last_day_month = days_of_month[len(days_of_month) - 1]
days_of_month = days_of_month[0:len(days_of_month) - 1]
else:
days_of_month = np.zeros(11, dtype=int)
last_day_month = int(0)
months_of_year = get_this_year(Taradod_list)
last_month = months_of_year[len(months_of_year) - 1]
months_of_year = months_of_year[0:len(months_of_year) - 1]
# checking whether the car is in our registered data
for taradod in Taradod_list:
taradod.seen = jdatetime.datetime.fromgregorian(day=taradod.seen.day, month=taradod.seen.month.numerator,
year=taradod.seen.year, hour=taradod.seen.astimezone().hour,
minute=taradod.seen.astimezone().minute,
second=taradod.seen.astimezone().second
)
if taradod.plate in Vehicle_list:
t = Taradod.objects.get(id=taradod.id)
t.approved = True
t.save()
context = {
'monthsCount': int(np.sum(months_of_year) + last_month),
'months': months_of_year,
'last_month': last_month,
'days': days_of_month,
'daysCount': int(np.sum(days_of_month) + last_day_month),
'last_day_month': last_day_month,
'weekCount': int(np.sum(week) + last_day),
'week': week,
'last_day': last_day,
'todayCount': int(np.sum(today) + last_hour),
'today': today,
'last_hour': last_hour,
'Taradod_list': Taradod_list,
}
return render(request, 'table.html', context)
@login_required(login_url='login')
def download_report(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="report.csv"'
writer = csv.writer(response)
writer.writerow(['پلاک', 'تاریخ تردد', 'وضعیت تردد'])
traffics = Taradod.objects.all().values_list('plate', 'seen',
'approved') # TODO: use Q() for filter some specific data
for traffic in traffics:
writer.writerow(traffic)
return response
def about(request):
return render(request, 'about-us.html')
|
{"/taradodApp/admin.py": ["/taradodApp/models.py"], "/userApp/admin.py": ["/userApp/models.py"], "/taradodApp/urls.py": ["/taradodApp/views.py"], "/registerApp/admin.py": ["/registerApp/models.py"], "/registerApp/views.py": ["/registerApp/forms.py", "/registerApp/models.py"], "/userApp/forms.py": ["/userApp/models.py"], "/taradodApp/views.py": ["/taradodApp/models.py", "/registerApp/models.py"], "/userApp/views.py": ["/userApp/forms.py"], "/registerApp/forms.py": ["/registerApp/models.py"], "/CVP/views.py": ["/registerApp/models.py", "/taradodApp/models.py"]}
|
32,559
|
chaimamaatoug/django-project
|
refs/heads/master
|
/gestionprojet/migrations/0001_initial.py
|
# Generated by Django 3.2 on 2021-06-01 14:06
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Project',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=50)),
('descrp', models.TextField(blank=True)),
('date', models.DateTimeField(default=datetime.datetime(2021, 6, 1, 15, 6, 47, 859683))),
],
),
migrations.CreateModel(
name='Task',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('descr', models.TextField(blank=True)),
('date', models.DateTimeField(default=datetime.datetime(2021, 6, 1, 15, 6, 47, 812803))),
('cmplte', models.BooleanField(default=False)),
],
),
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('email', models.EmailField(max_length=50)),
('password', models.CharField(max_length=50)),
('date', models.DateTimeField(default=datetime.datetime(2021, 6, 1, 15, 6, 47, 863670))),
('project', models.ManyToManyField(to='gestionprojet.Project')),
],
),
migrations.AddField(
model_name='project',
name='tasks',
field=models.ManyToManyField(to='gestionprojet.Task'),
),
]
|
{"/gestionprojet/admin.py": ["/gestionprojet/models.py"], "/gestionprojet/views.py": ["/gestionprojet/models.py", "/gestionprojet/forms.py"], "/gestionprojet/forms.py": ["/gestionprojet/models.py"]}
|
32,560
|
chaimamaatoug/django-project
|
refs/heads/master
|
/gestionprojet/admin.py
|
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(User),
admin.site.register(Project),
admin.site.register(Task)
|
{"/gestionprojet/admin.py": ["/gestionprojet/models.py"], "/gestionprojet/views.py": ["/gestionprojet/models.py", "/gestionprojet/forms.py"], "/gestionprojet/forms.py": ["/gestionprojet/models.py"]}
|
32,561
|
chaimamaatoug/django-project
|
refs/heads/master
|
/gestionprojet/views.py
|
from django.shortcuts import render,redirect
from .models import *
from .forms import *
# Create your views here.
def login(request):
if request.session.has_key('gest'):
return redirect('home')
else:
if request.method == "POST":
email = request.POST['email']
password = request.POST['password']
user = User.objects.filter(email = email,password = password).first()
if user:
request.session['gest'] = user.id
return redirect('home')
else:
msg = "email or password invalide"
return render(request,'login.html',{"msg":msg})
else:
return render(request,'login.html',{})
def home(request):
if request.session.has_key('gest'):
user = User.objects.filter(id = request.session['gest']).first()
return render(request,'home.html',{'user':user})
else:
return redirect('login')
def viewproject(request,id):
if request.session.has_key('gest'):
project = Project.objects.filter(id = id).first()
return render(request,'viewproject.html',{'proj':project,'id':id})
def deleteproject(request,id):
if request.session.has_key('gest'):
project = Project.objects.filter(id = id).first()
project.delete()
return redirect('home')
def addproject(request):
if request.session.has_key('gest'):
user = User.objects.filter(id = request.session['gest']).first()
if request.method == "POST":
p = Project()
p.name = request.POST['name']
p.descrp = request.POST['descrp']
p.save()
user.project.add(p)
return redirect('home')
else:
form = ProjectForm()
return render(request,'addproject.html',{"form":form})
else:
return redirect('login')
def addTask(request,id):
if request.session.has_key('gest'): #verify if there is a session or not which mean there is a client connected or not
p = Project.objects.filter(id = id).first() #get project data
if request.method == 'POST':
task = Task()
task.name = request.POST['name']
task.descr =request.POST['descr']
task.save()
p.tasks.add(task)
return redirect('home')
else:
form = TaskForm()
return render(request,'addtask.html',{'form':form})
else:
return redirect('login')
def deleteTask(request,id):
if request.session.has_key('gest'):
task = Task.objects.filter(id = id).first()
task.delete() #delete task from models
return redirect('home')
def cpmlte(request,id):
if request.session.has_key('gest'):
task = Task.objects.filter(id = id).first()
task.cmplte = True
task.save(update_fields=['cmplte']) #update model
return redirect('home')
else:
return redirect('login')
def editeproject(request,id):
if request.session.has_key('gest'):
p = Project.objects.filter(id = id).first() #get project data from model with the id
if request.method == 'POST':
p.name = request.POST['name'] #change the fields with the new values from formulaire
p.descrp = request.POST['descrp']
p.save(update_fields=['name','descrp'])
return redirect('home')
else:
return render(request,'editproject.html',{'proj': p}) #render the html page with a dict have values to edit
else:
return redirect('login')
def edittask(request,id):
if request.session.has_key('gest'):
task = Task.objects.filter(id = id).first() #get project data from model with the id
if request.method == 'POST':
task.name = request.POST['name'] #change the fields with the new values from formulaire
task.descr = request.POST['descr']
task.save(update_fields=['name','descr'])
return redirect('home')
else:
return render(request,'edittask.html',{'proj': task}) #render the html page with a dict have values to edit
else:
return redirect('login')
def logout(request):
if not request.session.has_key('gest'):
return redirect('login')
try:
del request.session['gest'] #delete the session gest
return redirect('login')
except:
pass
def signup(request):
if request.method == "POST":
user = User()
user.email = request.POST['email']
user.password = request.POST['password']
user.save() # inser into user('email','password)
request.session['gest'] = user.id #set up new session
return redirect('home')
else:
return render(request,'inscri.html',{})
|
{"/gestionprojet/admin.py": ["/gestionprojet/models.py"], "/gestionprojet/views.py": ["/gestionprojet/models.py", "/gestionprojet/forms.py"], "/gestionprojet/forms.py": ["/gestionprojet/models.py"]}
|
32,562
|
chaimamaatoug/django-project
|
refs/heads/master
|
/magasin/views.py
|
from django.shortcuts import render
#from django.http import HttpResponse
#from django.template import loader
from .models import Commande, Fournisseur, Produit
from .forms import *
from django.shortcuts import redirect
# Create your views here.
def index(request):
list=Produit.objects.all()
return render(request,'vitrine.html',{'list':list})
def addproduit(request):
if request.method == "POST":
form = ProduitForm(request.POST,request.FILES)
if form.is_valid:
form.save()
return redirect('index')
else:
form = ProduitForm()
return render(request,'majProduits.html',{'form':form})
def viewfor(request):
foni = Fournisseur.objects.all()
return render(request,'viewforni.html',{'forni':foni})
def viewcommande(request):
comm = Commande.objects.all()
return render(request,'viewcommande.html',{'comm':comm})
def addcommande(request):
if request.method == "POST":
form = CommandeForm(request.POST)
if form.is_valid:
form.save()
return redirect('viewcomamnde')
else:
form = CommandeForm()
return render(request,'addcommande.html',{'form':form})
|
{"/gestionprojet/admin.py": ["/gestionprojet/models.py"], "/gestionprojet/views.py": ["/gestionprojet/models.py", "/gestionprojet/forms.py"], "/gestionprojet/forms.py": ["/gestionprojet/models.py"]}
|
32,563
|
chaimamaatoug/django-project
|
refs/heads/master
|
/magasin/urls.py
|
from django.urls import path,include
from django.conf.urls import url
from . import views
urlpatterns=[
path('',views.index,name="index"),
path('addproduit',views.addproduit,name="addproduit"),
path('viewforni',views.viewfor,name="viewforni"),
path('viewcomamnde',views.viewcommande,name="viewcomamnde"),
path('comander',views.addcommande,name="comander")
]
|
{"/gestionprojet/admin.py": ["/gestionprojet/models.py"], "/gestionprojet/views.py": ["/gestionprojet/models.py", "/gestionprojet/forms.py"], "/gestionprojet/forms.py": ["/gestionprojet/models.py"]}
|
32,564
|
chaimamaatoug/django-project
|
refs/heads/master
|
/gestionprojet/forms.py
|
from django.forms import ModelForm
from django.forms.models import fields_for_model
from .models import *
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = ['name','descrp']
class TaskForm(ModelForm):
class Meta:
model = Task
fields = ['name','descr']
|
{"/gestionprojet/admin.py": ["/gestionprojet/models.py"], "/gestionprojet/views.py": ["/gestionprojet/models.py", "/gestionprojet/forms.py"], "/gestionprojet/forms.py": ["/gestionprojet/models.py"]}
|
32,565
|
chaimamaatoug/django-project
|
refs/heads/master
|
/gestionprojet/urls.py
|
from django.urls import path,include
from django.conf.urls import url
from . import views
urlpatterns=[
path('',views.login,name="login"),
path('home',views.home,name="home"),
path('viewproject/<id>',views.viewproject,name="viewproject"),
path('deleteproject/<id>',views.deleteproject,name="deleteproj"),
path('addproject',views.addproject,name="addproj"),
path('addtask/<id>',views.addTask,name="addtask"),
path('deletetask/<id>',views.deleteTask,name="deletetask"),
path('cpmlte/<id>',views.cpmlte,name="cpmlte"),
path('editp/<id>',views.editeproject,name="editp"),
path('edittask/<id>',views.edittask,name="edittask"),
path('logout',views.logout,name="logout"),
path('inscrir',views.signup,name="inscrir")
]
|
{"/gestionprojet/admin.py": ["/gestionprojet/models.py"], "/gestionprojet/views.py": ["/gestionprojet/models.py", "/gestionprojet/forms.py"], "/gestionprojet/forms.py": ["/gestionprojet/models.py"]}
|
32,566
|
chaimamaatoug/django-project
|
refs/heads/master
|
/gestionprojet/migrations/0002_auto_20210601_1506.py
|
# Generated by Django 3.2 on 2021-06-01 14:06
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gestionprojet', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='project',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 6, 1, 15, 6, 50, 891410)),
),
migrations.AlterField(
model_name='task',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 6, 1, 15, 6, 50, 845531)),
),
migrations.AlterField(
model_name='user',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 6, 1, 15, 6, 50, 895399)),
),
]
|
{"/gestionprojet/admin.py": ["/gestionprojet/models.py"], "/gestionprojet/views.py": ["/gestionprojet/models.py", "/gestionprojet/forms.py"], "/gestionprojet/forms.py": ["/gestionprojet/models.py"]}
|
32,567
|
chaimamaatoug/django-project
|
refs/heads/master
|
/mysite/urls.py
|
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from . import views
urlpatterns = [
path('',views.index),
path('admin/', admin.site.urls),
path('magasin/', include('magasin.urls')),
path('gest/', include('gestionprojet.urls')),
]+static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
|
{"/gestionprojet/admin.py": ["/gestionprojet/models.py"], "/gestionprojet/views.py": ["/gestionprojet/models.py", "/gestionprojet/forms.py"], "/gestionprojet/forms.py": ["/gestionprojet/models.py"]}
|
32,568
|
chaimamaatoug/django-project
|
refs/heads/master
|
/gestionprojet/models.py
|
from django.db import models
from datetime import datetime
# Create your models here.
class Task(models.Model):
name = models.CharField(max_length=50)
descr = models.TextField(blank = True)
date = models.DateTimeField(default=datetime.now())
cmplte = models.BooleanField(default=False)
class Project(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
descrp = models.TextField(blank = True)
date = models.DateTimeField(default=datetime.now())
tasks = models.ManyToManyField(Task,null = True,blank=True)
class User(models.Model):
id = models.AutoField(primary_key=True)
email = models.EmailField(max_length=50)
password = models.CharField(max_length=50)
date = models.DateTimeField(default=datetime.now())
project = models.ManyToManyField(Project,null = True,blank=True)
|
{"/gestionprojet/admin.py": ["/gestionprojet/models.py"], "/gestionprojet/views.py": ["/gestionprojet/models.py", "/gestionprojet/forms.py"], "/gestionprojet/forms.py": ["/gestionprojet/models.py"]}
|
32,569
|
chaimamaatoug/django-project
|
refs/heads/master
|
/gestionprojet/migrations/0003_auto_20210601_1607.py
|
# Generated by Django 3.2 on 2021-06-01 15:07
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gestionprojet', '0002_auto_20210601_1506'),
]
operations = [
migrations.AlterField(
model_name='project',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 6, 1, 16, 7, 12, 744955)),
),
migrations.AlterField(
model_name='project',
name='tasks',
field=models.ManyToManyField(blank=True, null=True, to='gestionprojet.Task'),
),
migrations.AlterField(
model_name='task',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 6, 1, 16, 7, 12, 697080)),
),
migrations.AlterField(
model_name='user',
name='date',
field=models.DateTimeField(default=datetime.datetime(2021, 6, 1, 16, 7, 12, 748943)),
),
migrations.AlterField(
model_name='user',
name='project',
field=models.ManyToManyField(blank=True, null=True, to='gestionprojet.Project'),
),
]
|
{"/gestionprojet/admin.py": ["/gestionprojet/models.py"], "/gestionprojet/views.py": ["/gestionprojet/models.py", "/gestionprojet/forms.py"], "/gestionprojet/forms.py": ["/gestionprojet/models.py"]}
|
32,671
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0018_auto_20200316_1848.py
|
# Generated by Django 2.2.2 on 2020-03-16 07:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0017_auto_20200314_1806'),
]
operations = [
migrations.AlterModelOptions(
name='lectionaryverse',
options={'ordering': ('bible_verse',)},
),
migrations.CreateModel(
name='LectionaryVerseMembership',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('order', models.IntegerField(default=0)),
('lection', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.Lection')),
('verse', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.LectionaryVerse')),
],
options={
'ordering': ['order', 'verse__bible_verse'],
},
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,672
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0002_remove_lectionaryverse_unique_string.py
|
# Generated by Django 2.2.2 on 2019-09-19 12:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='lectionaryverse',
name='unique_string',
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,673
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0008_auto_20200106_1548.py
|
# Generated by Django 2.2.2 on 2020-01-06 04:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0007_lectioninsystem_cumulative_mass_lections'),
]
operations = [
migrations.AlterModelOptions(
name='lectioninsystem',
options={'ordering': ['order', 'fixed_date', 'day_of_year', 'order_on_day']},
),
migrations.AddField(
model_name='dayofyear',
name='description',
field=models.CharField(default='', max_length=64),
preserve_default=False,
),
migrations.AddField(
model_name='lectioninsystem',
name='order',
field=models.IntegerField(default=0),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,674
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0009_fixeddate_date.py
|
# Generated by Django 2.2.2 on 2020-01-06 10:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0008_auto_20200106_1548'),
]
operations = [
migrations.AddField(
model_name='fixeddate',
name='date',
field=models.DateField(default=None, null=True),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,675
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0020_remove_lection_verses.py
|
# Generated by Django 2.2.2 on 2020-03-16 10:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0019_auto_20200316_1849'),
]
operations = [
migrations.RemoveField(
model_name='lection',
name='verses',
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,676
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/runtests.py
|
#!/usr/bin/env python
# Taken from https://docs.djangoproject.com/en/3.1/topics/testing/advanced/#using-the-django-test-runner-to-test-reusable-applications
import sys, os, django
from django.conf import settings
from django.test.utils import get_runner
if __name__ == "__main__" or True:
from pathlib import Path
settings_module = "tests.test_settings"
settings_path = Path(settings_module.replace('.', "/") + ".py")
# Find the project base directory
base_dir = Path(__file__).resolve()
while (base_dir/settings_path).exists() == False:
base_dir = base_dir.parent
if not base_dir:
raise Exception(f"Cannot find settings module '{settings_path}'")
# Add the project base directory to the sys.path
# This means the script will look in the base directory for any module imports
# Therefore you'll be able to import analysis.models etc
sys.path.insert(0, str(base_dir))
# The DJANGO_SETTINGS_MODULE has to be set to allow us to access django imports
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test_runner.run_tests(["tests"])
sys.exit(bool(failures))
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,677
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0007_lectioninsystem_cumulative_mass_lections.py
|
# Generated by Django 2.2.2 on 2019-09-28 08:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0006_auto_20190927_1634'),
]
operations = [
migrations.AddField(
model_name='lectioninsystem',
name='cumulative_mass_lections',
field=models.IntegerField(default=-1),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,678
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0024_auto_20200526_1623.py
|
# Generated by Django 2.2.2 on 2020-05-26 06:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0023_auto_20200526_1559'),
]
operations = [
migrations.RenameField(
model_name='lectionaryversemembership',
old_name='cummulative_mass_from_lection_start',
new_name='cumulative_mass_from_lection_start',
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,679
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0014_auto_20200314_1246.py
|
# Generated by Django 2.2.2 on 2020-03-14 01:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0013_auto_20200302_1226'),
]
operations = [
migrations.AddField(
model_name='lectioninsystem',
name='occasion_text',
field=models.TextField(blank=True, default=''),
),
migrations.AddField(
model_name='lectioninsystem',
name='occasion_text_en',
field=models.TextField(blank=True, default=''),
),
migrations.AddField(
model_name='lectioninsystem',
name='reference_membership',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.LectionInSystem'),
),
migrations.AddField(
model_name='lectioninsystem',
name='reference_text_en',
field=models.TextField(blank=True, default=''),
),
migrations.AlterField(
model_name='lectioninsystem',
name='lection',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.Lection'),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,680
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/models.py
|
from pathlib import Path
from itertools import chain
from lxml import etree
from django.db import models
from django.db.models import F
from django.db.models import Max, Min, Sum
from django.shortcuts import render
from django.urls import reverse
from polymorphic.models import PolymorphicModel
import numpy as np
import pandas as pd
from collections import defaultdict
from scipy.special import expit
import gotoh
from dcodex.models import Manuscript, Verse, VerseLocation
from dcodex_bible.models import BibleVerse
from dcodex_bible.similarity import *
import dcodex.distance as distance
import logging
DEFAULT_LECTIONARY_VERSE_MASS = 50
def data_dir():
return Path(__file__).parent/"data"
class LectionaryVerse(Verse):
bible_verse = models.ForeignKey(BibleVerse, on_delete=models.CASCADE, default=None, null=True, blank=True )
unique_string = models.CharField(max_length=100, default="")
mass = models.PositiveIntegerField(default=0)
class Meta:
ordering = ('bible_verse',)
def save(self,*args,**kwargs):
# Check to see if ID is assigned
if self.mass == 0:
self.mass = self.bible_verse.char_count if self.bible_verse and self.bible_verse.char_count else DEFAULT_LECTIONARY_VERSE_MASS
super().save(*args,**kwargs)
def reference(self, abbreviation = False, end_verse=None):
if not self.bible_verse:
if abbreviation and "Heading" in self.unique_string:
return "Head"
return self.unique_string
if end_verse:
return "vv %d–%d" % (self.id, end_verse.id)
return self.bible_verse.reference( abbreviation )
# Override
@classmethod
def get_from_dict( cls, dictionary ):
return cls.get_from_values(
dictionary.get('verse_id', 1) )
# Override
@classmethod
def get_from_string( cls, verse_as_string ):
if verse_as_string.isdigit():
return cls.get_from_values( verse_as_string )
return cls.objects.filter( unique_string=verse_as_string ).first()
@classmethod
def get_from_values( cls, verse_id ):
try:
return cls.objects.filter( id=int(verse_id) ).first()
except:
return None
# Override
def url_ref(self):
return self.unique_string
def set_unique_string( self ):
if not self.bible_verse:
return
other_vv = LectionaryVerse.objects.filter( bible_verse=self.bible_verse )
if self.id:
other_vv = other_vv.filter( id__lt=self.id )
self.unique_string = self.bible_verse.reference_abbreviation().replace(" ", '')
count = other_vv.count()
if count > 0:
self.unique_string += "_%d" % (count+1)
return self.unique_string
@classmethod
def new_from_bible_verse( cls, bible_verse ):
try:
rank = 1 + cls.objects.aggregate( Max('rank') )['rank__max']
except:
rank = 1
lectionary_verse = cls( bible_verse=bible_verse, rank=rank)
lectionary_verse.set_unique_string()
lectionary_verse.save()
return lectionary_verse
@classmethod
def new_from_bible_verse_id( cls, bible_verse_id ):
bible_verse = BibleVerse.objects.get( id=bible_verse_id )
return cls.new_from_bible_verse( bible_verse )
def others_with_bible_verse( self ):
return LectionaryVerse.objects.filter( bible_verse=self.bible_verse ).exclude( id=self.id )
class Lection(models.Model):
verses = models.ManyToManyField(LectionaryVerse, through='LectionaryVerseMembership')
description = models.CharField(max_length=100)
first_verse_id = models.IntegerField(default=0)
first_bible_verse_id = models.IntegerField(default=0)
def save(self,*args,**kwargs):
# Check to see if ID is assigned
if not self.id:
return super().save(*args,**kwargs)
first_verse = self.verses.first()
if first_verse:
self.first_verse_id = first_verse.id
self.first_bible_verse_id = first_verse.bible_verse.id if first_verse.bible_verse else 0
return super().save(*args,**kwargs)
class Meta:
ordering = ['first_bible_verse_id','description']
def __str__(self):
return self.description
def description_max_chars( self, max_chars=40 ):
description = self.description
if max_chars < 6:
max_chars = 6
if len(description) < max_chars:
return description
return description[:max_chars-3] + "..."
def days(self):
field = 'day'
ids = {value[field] for value in LectionInSystem.objects.filter(lection=self).values(field) if value[field]}
return LectionaryDay.objects.get(id__in=ids) # Look for a more efficient way to do this query
def dates(self):
""" Deprecated: Use 'days' """
return self.days()
def description_with_days( self ):
description = self.description_max_chars()
days = self.days()
if len(days) == 0:
return description
return "%s (%s)" % (description, ", ".join( [str(day) for day in days] ) )
def description_with_dates( self ):
""" Deprecated: Use 'description_with_days' """
return self.description_with_days()
def verse_memberships(self):
return LectionaryVerseMembership.objects.filter( lection=self ).all()
def reset_verse_order(self):
for verse_order, verse_membership in enumerate(self.verse_memberships()):
verse_membership.order = verse_order
verse_membership.save()
# print(verse_membership)
def verse_ids(self):
return LectionaryVerseMembership.objects.filter(lection=self).values_list( 'verse__id', flat=True )
def first_verse_id_in_set( self, intersection_set ):
return LectionaryVerseMembership.objects.filter(lection=self, verse__id__in=intersection_set).values_list( 'verse__id', flat=True ).first()
# OLD CODE
for verse_id in self.verse_ids():
if verse_id in intersection_set:
return verse_id
return None
def last_verse_id_in_set( self, intersection_set ):
return LectionaryVerseMembership.objects.filter(lection=self, verse__id__in=intersection_set).reverse().values_list( 'verse__id', flat=True ).first()
# OLD CODE
for verse_id in LectionaryVerseMembership.objects.filter(lection=self).reverse().values_list( 'verse__id', flat=True ):
if verse_id in intersection_set:
return verse_id
return None
# Deprecated - use add_verses_from_passages_string
def add_verses_from_range( self, start_verse_string, end_verse_string, lection_descriptions_with_verses=[], create_verses=False ):
lection_bible_verse_start = BibleVerse.get_from_string( start_verse_string )
lection_bible_verse_end = BibleVerse.get_from_string( end_verse_string )
# Find verses in other lections to use for this lection
verses_from_other_lections = []
for lection_description_with_verses in lection_descriptions_with_verses:
#print("Finding lection:", lection_description_with_verses)
lection_with_verses = Lection.objects.get( description=lection_description_with_verses )
verses_from_other_lections += list( lection_with_verses.verses.all() )
# Add verses in order, use verses from other lections if present otherwise create them
for bible_verse_id in range(lection_bible_verse_start.id, lection_bible_verse_end.id + 1):
lectionary_verse = None
for verse_from_other_lections in verses_from_other_lections:
if verse_from_other_lections.bible_verse.id == bible_verse_id:
lectionary_verse = verse_from_other_lections
break
if lectionary_verse is None:
if create_verses == False:
print("Trying to create lection %s with range of verses from %s to %s using %s other lections but there are not the right number of verses. i..e %d != %d" %
(description, str(lection_bible_verse_start), str(lection_bible_verse_end), lection_descriptions_with_verses, lection.verses.count(), lection_bible_verse_end.id-lection_bible_verse_start.id + 1 ) )
sys.exit()
lectionary_verse = LectionaryVerse.new_from_bible_verse_id( bible_verse_id )
self.verses.add(lectionary_verse)
self.save()
def add_verses_from_passages_string( self, passages_string, overlapping_lection_descriptions=[], overlapping_verses = [], overlapping_lections = [], create_verses=True ):
bible_verses = BibleVerse.get_verses_from_string( passages_string )
# Find verses in other lections to use for this lection
overlapping_lections += [Lection.objects.get( description=description ) for description in overlapping_lection_descriptions]
for overlapping_lection in overlapping_lections:
overlapping_verses += list( overlapping_lection.verses.all() )
# Add verses in order, use verses from other lections if present otherwise create them
for bible_verse in bible_verses:
lectionary_verse = None
for overlapping_verse in overlapping_verses:
if overlapping_verse.bible_verse and overlapping_verse.bible_verse.id == bible_verse.id:
lectionary_verse = overlapping_verse
break
if lectionary_verse is None:
if create_verses == False:
raise Exception( "Failed Trying to create lection %s using %s other lections but there are not the right number of verses." % (passages_string,overlapping_verses) )
lectionary_verse = LectionaryVerse.new_from_bible_verse_id( bible_verse.id )
self.verses.add(lectionary_verse)
self.save()
@classmethod
def update_or_create_from_description( cls, description, start_verse_string, end_verse_string, lection_descriptions_with_verses=[], create_verses=False ):
lection, created = cls.objects.get_or_create(description=description)
if created == False:
return lection
lection.verses.clear()
lection.add_verses_from_range( start_verse_string, end_verse_string, lection_descriptions_with_verses, create_verses )
lection.maintenance()
return lection
@classmethod
def update_or_create_from_passages_string( cls, passages_string, lection_descriptions_with_verses=[], create_verses=False ):
lection, created = cls.objects.get_or_create(description=passages_string)
if created == False:
return lection
lection.verses.clear()
lection.add_verses_from_passages_string( passages_string, overlapping_lection_descriptions=lection_descriptions_with_verses, create_verses=create_verses )
lection.maintenance()
return lection
@classmethod
def create_from_passages_string( cls, passages_string, **kwargs ):
lection = cls(description=passages_string)
lection.save()
lection.add_verses_from_passages_string( passages_string, **kwargs )
lection.save()
return lection
def first_verse(self):
return self.verses.first()
def calculate_mass(self):
mass = self.verses.aggregate( Sum('mass') ).get('mass__sum')
return mass
def maintenance(self):
cumulative_mass_from_lection_start = 0
for verse_membership in self.verse_memberships():
verse_membership.cumulative_mass_from_lection_start = cumulative_mass_from_lection_start
verse_membership.save()
cumulative_mass_from_lection_start += verse_membership.verse.mass
class LectionaryVerseMembership(models.Model):
lection = models.ForeignKey(Lection, on_delete=models.CASCADE)
verse = models.ForeignKey(LectionaryVerse, on_delete=models.CASCADE)
order = models.IntegerField(default=0)
cumulative_mass_from_lection_start = models.IntegerField(default=0, help_text="The total mass of verses from the beginning of the lection until this verse")
class Meta:
ordering = ['order','verse__bible_verse']
def __str__(self):
return "%d: %s in %s" % (self.order, self.verse, self.lection)
class FixedDate(models.Model):
"""
A liturgical day that corresponds to a fixed date in the calendar.
Because DateTime fields in Django need to be for a particular year, the year chosen was 1003 for September to December and 1004 for January to August. This year was chosen simply because 1004 is a leap year and so includes February 29.
"""
description = models.CharField(max_length=100)
date = models.DateField(default=None,null=True, blank=True)
def __str__(self):
return self.description
@classmethod
def get_with_string( cls, date_string ):
from dateutil import parser
dt = parser.parse( date_string )
year = 1003 if dt.month >= 9 else 1004
dt = dt.replace(year=year)
#print(dt, date_string)
return cls.objects.filter( date=dt ).first()
class Meta:
ordering = ('date','description')
class LectionaryDay(PolymorphicModel):
pass
class MiscDay(LectionaryDay):
description = models.CharField(max_length=255)
def __str__(self):
return self.description
class Meta:
ordering = ('description',)
class EothinaDay(LectionaryDay):
rank = models.IntegerField()
def __str__(self):
return f"Eothina {self.rank}"
class Meta:
ordering = ('rank',)
class FixedDay(LectionaryDay):
"""
A lectionary day that corresponds to a fixed date in the calendar.
Because DateTime fields in Django need to be for a particular year,
the year chosen was 1003 for September to December and 1004 for January to August.
This year was chosen simply because 1004 is a leap year and so includes February 29.
"""
date = models.DateField(default=None,null=True, blank=True)
def __str__(self):
return self.date.strftime('%b %d')
@classmethod
def get_with_string( cls, date_string ):
from dateutil import parser
dt = parser.parse( date_string )
year = 1003 if dt.month >= 9 else 1004
dt = dt.replace(year=year)
return cls.objects.filter( date=dt ).first()
class Meta:
ordering = ('date',)
class MovableDay(LectionaryDay):
SUNDAY = 0
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
DAY_CHOICES = [
(SUNDAY, 'Sunday'),
(MONDAY, 'Monday'),
(TUESDAY, 'Tuesday'),
(WEDNESDAY, 'Wednesday'),
(THURSDAY, 'Thursday'),
(FRIDAY, 'Friday'),
(SATURDAY, 'Saturday'),
]
DAY_ABBREVIATIONS = [
(SUNDAY, 'Sun'),
(MONDAY, 'Mon'),
(TUESDAY, 'Tues'),
(WEDNESDAY, 'Wed'),
(THURSDAY, 'Th'),
(FRIDAY, 'Fri'),
(SATURDAY, 'Sat'),
]
day_of_week = models.IntegerField(choices=DAY_CHOICES)
EASTER = 'E'
PENTECOST = 'P'
FEAST_OF_THE_CROSS = 'F'
LENT = 'L'
GREAT_WEEK = 'G'
EPIPHANY = 'T'
SEASON_CHOICES = [
(EASTER, 'Easter'),
(PENTECOST, 'Pentecost'),
(FEAST_OF_THE_CROSS, 'Feast of the Cross'),
(LENT, 'Lent'),
(GREAT_WEEK, 'Great Week'),
(EPIPHANY, 'Epiphany'),
]
season = models.CharField(max_length=1, choices=SEASON_CHOICES)
week = models.CharField(max_length=31, blank=True, default="")
weekday_number = models.CharField(max_length=32, blank=True, default="")
earliest_date = models.CharField(max_length=15, blank=True, default="")
latest_date = models.CharField(max_length=15, blank=True, default="")
rank = models.PositiveIntegerField(default=0, blank=False, null=False)
class Meta:
ordering = ('rank','id')
def description_str( self, abbreviation = False ):
day_choices = self.DAY_ABBREVIATIONS if abbreviation else DAY_CHOICES
string = "%s: %s" % (self.get_season_display(), day_choices[self.day_of_week][1] )
if self.week.isdigit():
string += ", Week %s" % (self.week )
elif self.week != "Holy Week":
string += ", %s" % (self.week )
if abbreviation:
string = string.replace("Week", "Wk")
string = string.replace("Feast of the Cross", "Cross")
string = string.replace(" Fare", "")
return string
def __str__(self):
return self.description_str(True)
@classmethod
def read_season(cls, target):
target = target.lower().strip()
for season, season_string in cls.SEASON_CHOICES:
if season_string.lower().startswith(target):
return season
if target.startswith("cross"):
return cls.FEAST_OF_THE_CROSS
if target.startswith("theoph"):
return cls.EPIPHANY
return None
@classmethod
def read_day_of_week(cls, target):
target = target.lower().strip()
for day, day_abbreviation in cls.DAY_ABBREVIATIONS:
if target.startswith(day_abbreviation.lower()):
return day
return None
class DayOfYear(models.Model):
"DEPRECATED. See Moveable Day."
SUNDAY = 0
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
DAY_CHOICES = [
(SUNDAY, 'Sunday'),
(MONDAY, 'Monday'),
(TUESDAY, 'Tuesday'),
(WEDNESDAY, 'Wednesday'),
(THURSDAY, 'Thursday'),
(FRIDAY, 'Friday'),
(SATURDAY, 'Saturday'),
]
DAY_ABBREVIATIONS = [
(SUNDAY, 'Sun'),
(MONDAY, 'Mon'),
(TUESDAY, 'Tues'),
(WEDNESDAY, 'Wed'),
(THURSDAY, 'Th'),
(FRIDAY, 'Fri'),
(SATURDAY, 'Sat'),
]
day_of_week = models.IntegerField(choices=DAY_CHOICES)
EASTER = 'E'
PENTECOST = 'P'
FEAST_OF_THE_CROSS = 'F'
LENT = 'L'
GREAT_WEEK = 'G'
EPIPHANY = 'T'
PERIOD_CHOICES = [
(EASTER, 'Easter'),
(PENTECOST, 'Pentecost'),
(FEAST_OF_THE_CROSS, 'Feast of the Cross'),
(LENT, 'Lent'),
(GREAT_WEEK, 'Great Week'),
(EPIPHANY, 'Epiphany'),
]
period = models.CharField(max_length=1, choices=PERIOD_CHOICES)
week = models.CharField(max_length=31)
weekday_number = models.CharField(max_length=32)
earliest_date = models.CharField(max_length=15)
latest_date = models.CharField(max_length=15)
description = models.CharField(max_length=255)
def description_str( self, abbreviation = False ):
day_choices = self.DAY_ABBREVIATIONS if abbreviation else DAY_CHOICES
string = "%s: %s" % (self.get_period_display(), day_choices[self.day_of_week][1] )
if self.week.isdigit():
string += ", Week %s" % (self.week )
elif self.week != "Holy Week":
string += ", %s" % (self.week )
if abbreviation:
string = string.replace("Week", "Wk")
string = string.replace("Feast of the Cross", "Cross")
string = string.replace(" Fare", "")
return string
def __str__(self):
return self.description_str(True)
class Meta:
verbose_name_plural = 'Days of year'
@classmethod
def read_period(cls, target):
target = target.lower().strip()
for period, period_string in cls.PERIOD_CHOICES:
if period_string.lower().startswith(target):
return period
return None
class LectionInSystem(models.Model):
lection = models.ForeignKey(Lection, on_delete=models.CASCADE, default=None, null=True, blank=True)
system = models.ForeignKey('LectionarySystem', on_delete=models.CASCADE)
day_of_year = models.ForeignKey(DayOfYear, on_delete=models.CASCADE, default=None, null=True, blank=True) # Deprecated
fixed_date = models.ForeignKey(FixedDate, on_delete=models.CASCADE, default=None, null=True, blank=True) # Deprecated
day = models.ForeignKey(LectionaryDay, on_delete=models.CASCADE, default=None, null=True, blank=True)
order_on_day = models.IntegerField(default=0) # Deprecated
cumulative_mass_lections = models.IntegerField(default=-1) # The mass of all the previous lections until the start of this one
order = models.IntegerField(default=0)
reference_text_en = models.TextField(default="", blank=True)
incipit = models.TextField(default="", blank=True)
reference_membership = models.ForeignKey('LectionInSystem', on_delete=models.CASCADE, default=None, null=True, blank=True)
occasion_text = models.TextField(default="", blank=True)
occasion_text_en = models.TextField(default="", blank=True)
def __str__(self):
return "%s in %s on %s" % ( str(self.lection), str(self.system), self.day_description() )
def clone_to_system( self, new_system ):
return LectionInSystem.objects.get_or_create(
system=new_system,
lection=self.lection,
order=self.order,
day=self.day,
cumulative_mass_lections=self.cumulative_mass_lections,
incipit=self.incipit,
reference_text_en=self.reference_text_en,
reference_membership=self.reference_membership,
)
def day_description(self):
if self.order_on_day < 2:
return str(self.day)
return "%s (%d)" % (str(self.day), self.order_on_day)
def description(self):
return "%s. %s" % (self.day_description(), str(self.lection) )
def description_max_chars( self, max_chars=40 ):
description = self.description()
if max_chars < 6:
max_chars = 6
if len(description) < max_chars:
return description
return description[:max_chars-3] + "..."
class Meta:
ordering = ('order', 'day', 'order_on_day',)
def prev(self):
return self.system.prev_lection_in_system( self )
def next(self):
return self.system.next_lection_in_system( self )
def cumulative_mass_of_verse( self, verse ):
mass = self.cumulative_mass_lections
verse_membership = LectionaryVerseMembership.objects.filter( lection=self.lection, verse=verse ).first()
cumulative_mass_verses = LectionaryVerseMembership.objects.filter( lection=self.lection, order__lt=verse_membership.order ).aggregate( Sum('verse__mass') ).get('verse__mass__sum')
if cumulative_mass_verses:
mass += cumulative_mass_verses
return mass
class LectionarySystem(models.Model):
name = models.CharField(max_length=200)
lections = models.ManyToManyField(Lection, through=LectionInSystem)
def __str__(self):
return self.name
def first_lection_in_system(self):
return self.lections_in_system().first()
def last_lection_in_system(self):
return self.lections_in_system().last()
def first_lection(self):
first_lection_in_system = self.first_lection_in_system()
return first_lection_in_system.lection
def first_verse(self):
first_lection = self.first_lection()
return first_lection.first_verse()
def maintenance(self):
self.reset_order()
self.calculate_masses()
def find_movable_day( self, **kwargs ):
day = MovableDay.objects.filter(**kwargs).first()
print('Day:', day)
if day:
return LectionInSystem.objects.filter(system=self, day=day).first()
return None
def find_fixed_day( self, last=False, **kwargs ):
memberships = self.find_fixed_day_all(**kwargs)
if not memberships:
return None
if last:
return memberships.last()
return memberships.first()
def find_fixed_day_all( self, **kwargs ):
date = FixedDay.objects.filter(**kwargs).first()
if date:
return LectionInSystem.objects.filter(system=self, day=date).all()
return None
def reset_order(self):
lection_memberships = self.lections_in_system()
for order, lection_membership in enumerate(lection_memberships.all()):
lection_membership.order = order
lection_membership.save()
lection_membership.lection.reset_verse_order()
def lections_in_system(self):
return LectionInSystem.objects.filter(system=self)
def lections_in_system_min_verses(self, min_verses=2):
return [m for m in self.lections_in_system().all() if m.lection.verses.count() >= min_verses]
def export_csv(self, filename) -> pd.DataFrame:
"""
Exports the lectionary system as a CSV.
Returns the lectionary system as a dataframe.
"""
df = self.dataframe()
df.to_csv(filename)
return df
def dataframe(self) -> pd.DataFrame:
"""
Returns the lectionary system as a pandas dataframe.
"""
data = []
columns = ["lection", 'season', 'week', 'day']
for lection_membership in self.lections_in_system():
if type(lection_membership.day) != MovableDay:
raise NotImplementedError(f"Cannot yet export for days of type {type(lection_membership.day)}.")
data.append(
[
lection_membership.lection.description,
lection_membership.day.get_season_display(),
lection_membership.day.week,
lection_membership.day.get_day_of_week_display(),
]
)
df = pd.DataFrame(data, columns=columns)
return df
def import_csv(self, csv, replace=False, create_verses=True):
"""
Reads a CSV and lections from it into this lectionary system.
The CSV file must have columns corresponding to 'lection', 'season', 'week', 'day', 'parallels' (optional).
"""
df = pd.read_csv(csv)
df.fillna('', inplace=True)
required_columns = ['season', 'week', 'day', 'lection']
for required_column in required_columns:
if not required_column in df.columns:
raise ValueError(f"No column named '{required_column}' in {df.columns}.")
for _, row in df.iterrows():
season = MovableDay.read_season(row['season'])
week = row['week']
day_of_week = MovableDay.read_day_of_week(row['day'])
day_filters = dict(season=season, week=week, day_of_week=day_of_week)
day_of_year = MovableDay.objects.filter( **day_filters ).first()
if not day_of_year:
raise ValueError(f"Cannot find day for row\n{row}. Filters: {day_filters}")
if "parallels" in row and not pd.isna(row["parallels"]):
parallels = row["parallels"].split("|")
else:
parallels = []
lection = Lection.update_or_create_from_passages_string(
row["lection"],
lection_descriptions_with_verses=parallels,
create_verses=create_verses,
)
print(f"\t{day_of_year} -> {lection}")
if replace:
self.replace_with_lection(day_of_year, lection)
else:
self.add_lection( day_of_year, lection )
self.maintenance()
@classmethod
def create_apostolos_e(cls, **kwargs):
system, _ = cls.objects.update_or_create(name="Apostolos e")
system.import_csv( data_dir()/"LectionarySystem-Apostolos-e.csv", **kwargs )
return system
@classmethod
def create_apostolos_esk(cls, **kwargs):
system, _ = cls.objects.update_or_create(name="Apostolos esk")
system.import_csv( data_dir()/"LectionarySystem-Apostolos-esk.csv", **kwargs )
return system
@classmethod
def create_apostolos_sk(cls, **kwargs):
system, _ = cls.objects.update_or_create(name="Apostolos sk")
system.import_csv( data_dir()/"LectionarySystem-Apostolos-sk.csv", **kwargs )
return system
@classmethod
def create_apostolos_k(cls, **kwargs):
system, _ = cls.objects.update_or_create(name="Apostolos k")
system.import_csv( data_dir()/"LectionarySystem-Apostolos-k.csv", **kwargs )
return system
def next_lection_in_system(self, lection_in_system):
found = False
for object in self.lections_in_system().all():
if object == lection_in_system:
found = True
elif found:
return object
def prev_lection_in_system(self, lection_in_system):
found = False
for object in self.lections_in_system().all().reverse():
if object == lection_in_system:
found = True
elif found:
return object
def calculate_masses( self ):
cumulative_mass = 0.0
for lection_in_system in self.lections_in_system().all():
lection_in_system.cumulative_mass_lections = cumulative_mass
lection_in_system.save()
cumulative_mass += lection_in_system.lection.calculate_mass()
# try:
# cumulative_mass += lection_in_system.lection.calculate_mass()
# except Exception as err:
# print( f'Failed to calculate mass: {lection_in_system.lection}\n{err}' )
# continue
@classmethod
def calculate_masses_all_systems( cls ):
for system in cls.objects.all():
system.calculate_masses()
@classmethod
def maintenance_all_systems( cls ):
print("Doing maintenance for each lection")
for lection in Lection.objects.all():
print(lection)
lection.maintenance()
print("Doing maintenance for each system")
for system in cls.objects.all():
print(system)
system.maintenance()
def lection_for_verse( self, verse ):
lections_with_verse = verse.lection_set.all()
lections_in_system = self.lections.all()
for lection in lections_with_verse:
if lection in lections_in_system:
return lection
return None
def lection_in_system_for_verse( self, verse ):
lection = self.lection_for_verse( verse )
return self.lectioninsystem_set.filter( lection=lection ).first()
def get_max_order( self ):
return self.lections_in_system().aggregate(Max('order')).get('order__max')
def add_lection( self, day, lection ):
membership, created = LectionInSystem.objects.get_or_create(system=self, lection=lection, day=day)
if created == True:
max_order = self.get_max_order()
membership.order = max_order + 1
membership.save()
return membership
def add_lection_from_description( self, day, lection_description ):
lection, created = Lection.objects.get_or_create(description=lection_description)
return self.add_lection( day, lection )
def add_new_lection_from_description( self, day, lection_description, start_verse_string, end_verse_string, lection_descriptions_with_verses=[], create_verses=False ):
lection = Lection.update_or_create_from_description(description=lection_description, start_verse_string=start_verse_string, end_verse_string=end_verse_string, lection_descriptions_with_verses=lection_descriptions_with_verses, create_verses=create_verses)
return self.add_lection( day, lection )
def add_new_lection_from_passages_string( self, day, passages_string, **kwargs ):
lection = Lection.update_or_create_from_passages_string(passages_string=passages_string, **kwargs)
return self.add_lection( day, lection )
def delete_all_on_day( self, day ):
print("Deleting all on Day of year:", day )
lection_memberships = LectionInSystem.objects.filter(system=self, day=day).delete()
def replace_with_lection( self, day, lection ):
self.delete_all_on_day( day )
print("Adding:", lection)
return self.add_lection( day, lection )
def insert_lection( self, day, lection, insert_after=None ):
order = None
if insert_after is not None:
insert_after_membership = LectionInSystem.objects.filter(system=self, lection=insert_after).first()
if insert_after_membership:
order = insert_after_membership.order + 1
LectionInSystem.objects.filter(system=self, order__gte=order).update( order=F('order') + 1 )
if not order:
print('order is none')
print('insert_after', insert_after)
print('insert_after_membership ', insert_after_membership )
print('system ', self )
return None
membership = self.add_lection( day, lection )
membership.order = order
membership.save()
return membership
def replace_with_new_lection_from_description( self, day, lection_description, start_verse_string, end_verse_string, lection_descriptions_with_verses=[], create_verses=False ):
lection = Lection.update_or_create_from_description(description=lection_description, start_verse_string=start_verse_string, end_verse_string=end_verse_string, lection_descriptions_with_verses=lection_descriptions_with_verses, create_verses=create_verses)
self.replace_with_lection( day, lection )
return lection
def empty( self ):
""" This method removes references to all lections in this system and leaves the lectionary system empty. """
LectionInSystem.objects.filter( system=self ).delete()
def clone_to_system( self, new_system ):
new_system.empty()
for lection_membership in self.lections_in_system().all():
lection_membership.clone_to_system( new_system )
def clone_to_system_synaxarion( self, new_system ):
new_system.empty()
for lection_membership in LectionInSystem.objects.filter( system=self, day__in=MovableDay.objects.all() ).all(): # There should be a more efficient way to do this query
lection_membership.clone_to_system( new_system )
def clone_to_system_with_name(self, new_system_name ):
new_system, created = LectionarySystem.objects.get_or_create(name=new_system_name)
self.clone_to_system( new_system )
return new_system
def cumulative_mass( self, verse ):
lection_in_system = self.lection_in_system_for_verse( verse )
if lection_in_system:
return lection_in_system.cumulative_mass_of_verse( verse )
return 0
def verse_from_mass_difference( self, reference_verse, additional_mass ):
logger = logging.getLogger(__name__)
logger.error("ref_verse "+str(reference_verse))
logger.error("additional_mass "+str(additional_mass))
cumulative_mass = self.cumulative_mass(reference_verse) + additional_mass
logger.error("cumulative_mass "+str(cumulative_mass))
lection_membership = LectionInSystem.objects.filter( system=self, cumulative_mass_lections__lte=cumulative_mass ).order_by( '-cumulative_mass_lections' ).first()
logger.error("lection_membership "+str(lection_membership))
logger.error("lection_membership.cumulative_mass_lections "+str(lection_membership.cumulative_mass_lections))
if lection_membership == None:
return None
mass_from_start_of_lection = cumulative_mass - lection_membership.cumulative_mass_lections
logger.error("mass_from_start_of_lection "+str(mass_from_start_of_lection))
verse_membership = LectionaryVerseMembership.objects.filter( lection=lection_membership.lection, cumulative_mass_from_lection_start__lte=mass_from_start_of_lection ).order_by( '-cumulative_mass_from_lection_start' ).first()
if verse_membership:
return verse_membership.verse
return None
def create_reference( self, date, insert_after, description="", reference_text_en="", reference_membership=None, has_incipit=False ):
if not description:
description = "Reference: "+str(date)
heading_description = str(date) + " Heading"
incipit_description = str(date) + " Incipit"
else:
heading_description = description + " Heading"
incipit_description = description + " Incipit"
# Create Lection
print('getting', description)
lection, created = Lection.objects.get_or_create(description=description)
print('created', description)
if created:
# Add heading
heading_verse, created = LectionaryVerse.objects.get_or_create( bible_verse=None, unique_string=heading_description, rank=0 )
lection.verses.add( heading_verse )
# Add Incipit
if has_incipit:
incipit, created = LectionaryVerse.objects.get_or_create( bible_verse=None, unique_string=incipit_description, rank=0 )
lection.verses.add( incipit )
lection.save()
# Insert Into System
membership = self.insert_lection( date, lection, insert_after )
print('membership', membership)
membership.reference_membership = reference_membership
membership.reference_text_en = reference_text_en
membership.save()
return membership
class Lectionary( Manuscript ):
system = models.ForeignKey(LectionarySystem, on_delete=models.CASCADE)
@classmethod
def verse_class(cls):
return LectionaryVerse
@classmethod
def verse_from_id(cls, verse_id):
verse = super().verse_from_id(verse_id)
if verse:
return verse
return cls.verse_class().objects.filter(bible_verse_id=verse_id).first()
# Override
def verse_search_template(self):
return "dcodex_lectionary/verse_search.html"
# Override
def location_popup_template(self):
return 'dcodex_lectionary/location_popup.html'
class Meta:
verbose_name_plural = 'Lectionaries'
# Override
def render_verse_search( self, request, verse ):
lection_in_system = self.system.lection_in_system_for_verse( verse )
if lection_in_system is None:
lection_in_system = self.system.first_lection_in_system()
verse = lection_in_system.lection.first_verse()
return render(request, self.verse_search_template(), {'verse': verse, 'manuscript': self, 'lection_in_system': lection_in_system, 'next_verse':self.next_verse(verse), 'prev_verse':self.prev_verse(verse),} )
# Override
def render_location_popup( self, request, verse ):
lection_in_system = self.system.lection_in_system_for_verse( verse )
return render(request, self.location_popup_template(), {'verse': verse, 'manuscript': self, 'lection_in_system': lection_in_system, 'next_verse':self.next_verse(verse), 'prev_verse':self.prev_verse(verse),} )
# Override
def comparison_texts( self, verse, manuscripts = None ):
lectionary_comparisons = super().comparison_texts( verse, manuscripts )
# Find all other lectionary verse transcriptions with this Bible Verse
lectionary_verses_with_bible_verse = verse.others_with_bible_verse()
lectionary_comparisons_same_bible_verse = self.transcription_class().objects.filter( verse__in=lectionary_verses_with_bible_verse )
if manuscripts:
lectionary_comparisons_same_bible_verse = lectionary_comparisons_same_bible_verse.filter( manuscript__in=manuscripts )
continuous_text_comparisons = super().comparison_texts( verse.bible_verse, manuscripts )
# return list(chain(lectionary_comparisons, continuous_text_comparisons))
return list(chain(lectionary_comparisons, lectionary_comparisons_same_bible_verse.all(), continuous_text_comparisons))
# Override
def accordance(self):
""" Returns a string formatted as an Accordance User Bible """
user_bible = ""
# Loop over all transcriptions and put them in a dictionary based on the bible verse
bible_verse_to_transcriptions_dict = defaultdict(list)
for transcription in self.transcriptions():
transcription_clean = transcription.remove_markup()
if transcription.verse.bible_verse:
bible_verse_to_transcriptions_dict[transcription.verse.bible_verse].append(transcription_clean)
# Loop over the distinct Bible verses in order
bible_verses = sorted(bible_verse_to_transcriptions_dict.keys(), key=lambda bible_verse: bible_verse.id)
for bible_verse in bible_verses:
transcriptions_txt = " | ".join(bible_verse_to_transcriptions_dict[bible_verse])
user_bible += f"{bible_verse} <color=black></color>{transcriptions_txt}<br>\n"
return user_bible
def tei_element_text( self, ignore_headings=True ):
text = etree.Element("text")
body = etree.SubElement(text, "body")
for membership in self.system.lectioninsystem_set.all():
lection_div = etree.SubElement(body, "div", type="lection", n=membership.description() )
for verse_index, verse in enumerate(membership.lection.verses.all()):
if not verse.bible_verse:
continue
transcription = self.transcription( verse )
if transcription:
verse_tei_id = transcription.verse.bible_verse.tei_id()
tei_text = transcription.tei()
# ab = etree.SubElement(body, "ab", n=verse_tei_id)
ab = etree.fromstring( f'<ab n="{verse_tei_id}">{tei_text}</ab>' )
lection_div.append(ab)
return text
def next_verse( self, verse, lection_in_system = None ):
if lection_in_system == None:
lection_in_system = self.system.lection_in_system_for_verse( verse )
if lection_in_system == None:
return None
next_verse = lection_in_system.lection.verses.filter( rank__gt=verse.rank ).order_by('rank').first()
if not next_verse:
lection_in_system = lection_in_system.next()
if lection_in_system and lection_in_system.lection:
next_verse = lection_in_system.lection.verses.order_by('rank').first()
return next_verse
def prev_verse( self, verse, lection_in_system = None ):
if lection_in_system == None:
lection_in_system = self.system.lection_in_system_for_verse( verse )
if lection_in_system == None:
return None
prev_verse = lection_in_system.lection.verses.filter( rank__lt=verse.rank ).order_by('-rank').first()
if not prev_verse:
lection_in_system = lection_in_system.prev()
if not lection_in_system:
return None
prev_verse = lection_in_system.lection.verses.order_by('-rank').first()
return prev_verse
def verse_membership( self, verse ):
return LectionaryVerseMembership.objects.filter( verse=verse, lection__lectioninsystem__system=self.system ).first()
def location_before_or_equal( self, verse ):
if not verse:
return None
logger = logging.getLogger(__name__)
current_verse_membership = self.verse_membership( verse )
if not current_verse_membership:
return None
verse_ids_with_locations = set(self.verse_ids_with_locations())
# Search within current lection
verse_id = LectionaryVerseMembership.objects.filter(
lection=current_verse_membership.lection,
order__lte=current_verse_membership.order,
verse__id__in=verse_ids_with_locations
).values_list( 'verse__id', flat=True ).last()
# Search in previous lections if necessary
if not verse_id:
current_lection_in_system = self.system.lection_in_system_for_verse( verse )
verse_id = LectionInSystem.objects.filter(
system=self.system,
order__lt=current_lection_in_system.order,
lection__verses__id__in=verse_ids_with_locations,
).values_list('lection__verses', flat=True).last()
if verse_id:
return VerseLocation.objects.filter( manuscript=self, verse__id=verse_id ).first()
return None
def location_after( self, verse ):
if not verse:
return None
# logger = logging.getLogger(__name__)
current_verse_membership = self.verse_membership( verse )
if not current_verse_membership:
return None
verse_ids_with_locations = self.verse_ids_with_locations()
# Search within current lection
verse_id = LectionaryVerseMembership.objects.filter(
lection=current_verse_membership.lection,
order__gt=current_verse_membership.order,
verse__id__in=verse_ids_with_locations
).values_list( 'verse__id', flat=True ).first()
# Search in subsequent lections if necessary
if not verse_id:
current_lection_in_system = self.system.lection_in_system_for_verse( verse )
verse_id = LectionInSystem.objects.filter(
system=self.system,
order__gt=current_lection_in_system.order,
lection__verses__id__in=verse_ids_with_locations,
).values_list('lection__verses', flat=True).first()
if verse_id:
return VerseLocation.objects.filter( manuscript=self, verse__id=verse_id ).first()
return None
def last_location( self ):
return VerseLocation.objects.filter( manuscript=self ).order_by('-page', '-y').first()
def first_location( self ):
return VerseLocation.objects.filter( manuscript=self ).order_by('page', 'y').first()
def first_verse( self ):
return self.system.first_verse()
def first_empty_verse( self ):
verse = self.first_verse()
while verse is not None:
if self.transcription( verse ) is None:
return verse
else:
verse = self.next_verse( verse )
return None
# Override
def title_dict( self, verse ):
day_description = ""
lection_in_system = self.system.lection_in_system_for_verse( verse )
if lection_in_system:
day_description = lection_in_system.day_description()
url_ref = verse.url_ref()
return {
'title': "%s %s %s" % (self.siglum, day_description, verse.reference_abbreviation() ),
'url': reverse( "dcodex-manuscript-verse", kwargs=dict(request_siglum=self.siglum, request_verse=url_ref) ),
'verse_url_ref': url_ref,
}
def lection_transcribed_count( self, lection ):
return self.transcription_class().objects.filter( manuscript=self, verse__in=lection.verses.all() ).count()
def transcribed_count_df( self ):
total_transcribed_count = 0
total_verses_count = 0
df = pd.DataFrame(columns=('Lection', 'Day', 'Verses Transcribed', 'Verses Count'))
i=0
for i, lection_in_system in enumerate(self.system.lections_in_system()):
lection = lection_in_system.lection
verses_count = lection.verses.count()
transcribed_verses_count = self.lection_transcribed_count( lection )
total_transcribed_count += transcribed_verses_count
total_verses_count += verses_count
df.loc[i] = [str(lection), lection_in_system.day_description(), transcribed_verses_count, verses_count]
df.loc[i+1] = ["Total", "", total_transcribed_count, total_verses_count]
df['Percentage'] = df['Verses Transcribed']/df['Verses Count']*100.0
return df
def transcriptions_in_lections( self, lections, ignore_incipits=False ):
transcriptions = []
for lection in lections:
print(lection)
for verse_index, verse in enumerate(lection.verses.all()):
if verse_index == 0 and ignore_incipits:
continue
transcription = self.transcription( verse )
if transcription:
transcriptions.append( transcription )
return transcriptions
def transcriptions_in_lections_dict( self, **kwargs ):
return { transcription.verse.bible_verse.id : transcription.transcription for transcription in self.transcriptions_in_lections( **kwargs ) }
def transcription( self, verse ):
if type(verse) == LectionaryVerse:
return super().transcription(verse)
if type(verse) == BibleVerse:
lectionary_verse = self.verse_class().objects.filter(bible_verse=verse).first() # HACK This will give the first version, not necessarily the one we want!
return super().transcription(lectionary_verse)
return None
def similarity_lection( self, lection, comparison_mss, similarity_func=distance.similarity_levenshtein, ignore_incipits=False ):
similarity_values = np.zeros( (len(comparison_mss),) )
counts = np.zeros( (len(comparison_mss),), dtype=int )
has_seen_incipit = False
for verse_index, verse in enumerate(lection.verses.all()):
if not verse.bible_verse:
continue
if not has_seen_incipit:
has_seen_incipit = True
if ignore_incipits:
continue
my_transcription = self.normalized_transcription( verse )
if not my_transcription:
continue
for ms_index, ms in enumerate(comparison_mss):
comparison_transcription = ms.normalized_transcription( verse ) if type(ms) is Lectionary else ms.normalized_transcription( verse.bible_verse )
if not comparison_transcription:
continue
similarity_values[ms_index] += similarity_func( my_transcription, comparison_transcription )
counts[ms_index] += 1
averages = []
for similarity_value, count in zip(similarity_values, counts):
average = None if count == 0 else similarity_value/count
averages.append(average)
return averages
def similarity_probabilities_lection( self, lection, comparison_mss, weights, gotoh_param, prior_log_odds=0.0, ignore_incipits=False ):
gotoh_totals = np.zeros( (len(comparison_mss),4), dtype=np.int32 )
weights = np.asarray(weights)
for verse_index, verse in enumerate(lection.verses.all()):
if verse_index == 0 and ignore_incipits:
continue
my_transcription = self.normalized_transcription( verse )
if not my_transcription:
continue
for ms_index, ms in enumerate(comparison_mss):
comparison_transcription = ms.normalized_transcription( verse ) if type(ms) is Lectionary else ms.normalized_transcription( verse.bible_verse )
if not comparison_transcription:
continue
counts = gotoh.counts( my_transcription, comparison_transcription, *gotoh_param )
gotoh_totals[ms_index][:] += counts
results = []
for ms_index in range(len(comparison_mss)):
length = gotoh_totals[ms_index].sum()
similarity = 100.0 * gotoh_totals[ms_index][0]/length if length > 0 else np.NAN
logodds = prior_log_odds + np.dot( gotoh_totals[ms_index], weights )
posterior_probability = expit( logodds )
results.extend([similarity, posterior_probability])
return results
def similarity_df( self, comparison_mss, min_verses = 2, **kwargs ):
columns = ['Lection']
columns += [ms.siglum for ms in comparison_mss]
df = pd.DataFrame(columns=columns)
for i, lection_in_system in enumerate(self.system.lections_in_system().all()):
lection = lection_in_system.lection
if lection.verses.count() < min_verses:
continue
averages = self.similarity_lection( lection, comparison_mss, **kwargs )
df.loc[i] = [str(lection_in_system)] + averages
return df
def similarity_probabilities_df( self, comparison_mss, min_verses=2, **kwargs ):
columns = ['Lection','Lection_Membership__id','Lection_Membership__order']
for ms in comparison_mss:
columns.extend( [ms.siglum + "_similarity", ms.siglum + "_probability"] )
df = pd.DataFrame(columns=columns)
index = 0
for lection_in_system in self.system.lections_in_system().all():
lection = lection_in_system.lection
if lection.verses.count() < min_verses:
continue
# if ignore_untranscribed and self.lection_transcribed_count( lection ) == 0:
# print("Ignoring untranscribed lection:", lection)
# continue
results = self.similarity_probabilities_lection( lection, comparison_mss, **kwargs )
df.loc[index] = [str(lection_in_system), lection_in_system.id, lection_in_system.order] + results
index += 1
print('similarity_probabilities_df indexes:', index)
return df
def similarity_families_array( self, comparison_mss, start_verse, end_verse, threshold, **kwargs ):
verse_count = end_verse.rank - start_verse.rank + 1
families_array = np.zeros( (verse_count,) )
UNCERTAIN = 1
MIXED = 2
for i, lection in enumerate(self.system.lections.all()):
averages = self.similarity_lection( lection, comparison_mss, **kwargs )
# print(lection, averages)
max_index = None
max_average = 0.0
for ms_index, average in enumerate( averages ):
print(average)
print( 'average is not None', average is not None )
# print( 'average > max_average', average > max_average )
if average is not None and average > max_average:
max_index = ms_index
max_average = average
if max_index is None:
continue
family = max_index + MIXED + 1 if max_average > threshold else UNCERTAIN
print( lection, max_index, family, max_average, averages )
for lectionary_verse in lection.verses.all():
array_index = lectionary_verse.bible_verse.rank - start_verse.rank
if families_array[array_index] <= UNCERTAIN:
families_array[array_index] = family
elif families_array[array_index] != family:
families_array[array_index] = MIXED
return families_array
def lections_agreeing_with( self, comparison_mss, threshold, **kwargs ):
lections_agreeing_with = defaultdict( list )
for i, lection in enumerate(self.system.lections.all()):
averages = self.similarity_lection( lection, comparison_mss, **kwargs )
max_index = None
max_average = 0.0
for ms_index, average in enumerate( averages ):
if average is not None and average > max_average:
max_index = ms_index
max_average = average
if max_index is None:
continue
if max_average > threshold:
lections_agreeing_with[max_index].append( lection )
# Add Sigla to dictionary
for ms_index, ms in enumerate( comparison_mss ):
lections_agreeing_with[ ms.siglum ] = lections_agreeing_with[ ms_index ]
return lections_agreeing_with
def verse_from_mass_difference( self, reference_verse, additional_mass ):
return self.system.verse_from_mass_difference( reference_verse, additional_mass )
def cumulative_mass( self, verse ):
return self.system.cumulative_mass(verse)
def distance_between_verses( self, verse1, verse2 ):
return self.cumulative_mass( verse2 ) - self.cumulative_mass( verse1 )
def plot_lections_similarity(
self,
mss_sigla,
lections = None,
min_lection_index = None,
max_lection_index = None,
output_filename = None,
csv_filename = None,
force_compute = False,
gotoh_param = [6.6995597099885345, -0.9209875054657459, -5.097397327423096, -1.3005714416503906], # From PairHMM of whole dataset
weights = [0.07124444438506426, -0.2723489152810223, -0.634987796501936, -0.05103656566400282], # From whole dataset
figsize=(12,7),
colors = ['#007AFF', '#6EC038', 'darkred', 'magenta'],
mode = LIKELY__UNLIKELY,
xticks = [],
xticks_rotation=0,
minor_markers=1,
ymin=60,
ymax=100,
prior_log_odds=0.0,
annotations=[],
annotation_color='red',
annotations_spaces_to_lines=False,
legend_location="best",
circle_marker=True,
highlight_regions=[],
highlight_color='yellow',
fill_empty=True,
space_evenly=False,
ignore_untranscribed=False,
):
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.family'] = 'Linux Libertine O'
rcParams.update({'font.size': 14})
#plt.rc('text', usetex=True)
#plt.rc('text.latex', preamble=r'\usepackage{amsmath}')
import matplotlib.ticker as mtick
import matplotlib.lines as mlines
from os import access, R_OK
from os.path import isfile
from matplotlib.ticker import FixedLocator
fig, ax = plt.subplots(figsize=figsize)
mss = [Manuscript.find( siglum ) for siglum in mss_sigla.keys()]
if not force_compute and csv_filename and isfile( csv_filename ) and access(csv_filename, R_OK):
df = pd.read_csv(csv_filename)
else:
df = self.similarity_probabilities_df( mss, weights=weights, gotoh_param=gotoh_param, prior_log_odds=prior_log_odds )
if csv_filename:
df.to_csv( csv_filename )
if min_lection_index:
if isinstance( min_lection_index, LectionInSystem ):
min_lection_index = min_lection_index.order
df = df[ df['Lection_Membership__order'] >= min_lection_index ]
if max_lection_index:
if isinstance( max_lection_index, LectionInSystem ):
max_lection_index = max_lection_index.order
print('max_lection_index', max_lection_index)
df = df[df['Lection_Membership__order'] <= max_lection_index ]
if lections:
lection_ids = []
for lection in lections:
if isinstance(lection,LectionInSystem):
lection_ids.append( lection.id )
else:
lection_ids.append( lection )
# print(df)
df = df[ df['Lection_Membership__id'].isin( lection_ids ) ]
# print(df)
# print(lection_ids)
# return
min = df.index.min()
max = df.index.max()
if fill_empty:
df = df.set_index( 'Lection_Membership__order' )
df = df.reindex( np.arange( min, max+1 ) )
if space_evenly:
df.index = np.arange( len(df.index) )
print(df)
#return
circle_marker = 'o' if circle_marker else ''
for index, ms_siglum in enumerate(mss_sigla.keys()):
ms_df = df[ df[ms_siglum+'_similarity'].notnull() ] if ignore_untranscribed else df
if mode is HIGHLY_LIKELY__LIKELY__ELSE:
plt.plot(ms_df.index, ms_df[ms_siglum+'_similarity'].mask(ms_df[ms_siglum+"_probability"] < 0.95), '-', color=colors[index], linewidth=2.5, label=mss_sigla[ms_siglum] + " (Highly Likely)" );
plt.plot(ms_df.index, ms_df[ms_siglum+'_similarity'].mask( (ms_df[ms_siglum+"_probability"] > 0.95) | (ms_df[ms_siglum+"_probability"] < 0.5)), '-', color=colors[index], linewidth=1.5, label=mss_sigla[ms_siglum] + " (Likely)" );
plt.plot(ms_df.index, ms_df[ms_siglum+'_similarity'].mask(ms_df[ms_siglum+"_probability"] > 0.95), '--', color=colors[index], linewidth=0.5, label=mss_sigla[ms_siglum] + " (Unlikely)" );
elif mode is HIGHLY_LIKELY__ELSE:
plt.plot(ms_df.index, ms_df[ms_siglum+'_similarity'].mask(ms_df[ms_siglum+"_probability"] < 0.95), '-', color=colors[index], linewidth=2.5, label=mss_sigla[ms_siglum] + " (Highly Likely)" );
plt.plot(ms_df.index, ms_df[ms_siglum+'_similarity'], '--', color=colors[index], linewidth=1, label=mss_sigla[ms_siglum] );
else:
plt.plot(ms_df.index, ms_df[ms_siglum+'_similarity'].mask(ms_df[ms_siglum+"_probability"] < 0.5), marker=circle_marker, linestyle='-', color=colors[index], linewidth=2.5, label=mss_sigla[ms_siglum] + " (Likely)", zorder=11, markersize=8.0, markerfacecolor=colors[index], markeredgecolor=colors[index]);
plt.plot(ms_df.index, ms_df[ms_siglum+'_similarity'], marker=circle_marker, linestyle='--', color=colors[index], linewidth=1, label=mss_sigla[ms_siglum] + " (Unlikely)", zorder=10, markerfacecolor='white', markeredgecolor=colors[index], markersize=5.0 );
# plt.plot(df.index, df[ms_siglum+'_similarity'].mask(df[ms_siglum+"_probability"] > 0.5), '--', color=colors[index], linewidth=1, label=mss_sigla[ms_siglum] + " (Unlikely)" );
plt.ylim([ymin, ymax])
ax.set_xticklabels([])
plt.ylabel('Similarity', horizontalalignment='right', y=1.0)
ax.yaxis.set_major_formatter(mtick.PercentFormatter(decimals=0))
#######################
##### Grid lines #####
#######################
# first_lection_membership = self.system.first_lection_in_system()
# last_lection_membership = self.system.last_lection_in_system()
###### Major Grid Lines ######
major_tick_locations = []
major_tick_annotations = []
for membership in xticks:
if type(membership) == tuple:
if not isinstance( membership[0], LectionInSystem ):
print("Trouble with membership:", membership)
continue
print( 'looking for:', membership[0].id, membership )
x = df.index[ df['Lection_Membership__id'] == membership[0].id ].values.item()
description = membership[-1]
else:
if not isinstance( membership, LectionInSystem ):
print("Trouble with membership:", membership)
continue
print( 'looking for:', membership.id, membership )
x = df.index[ df['Lection_Membership__id'] == membership.id ].values.item()
description = str(membership.day)
if annotations_spaces_to_lines:
description = description.replace( ' ', "\n" )
major_tick_locations.append( x )
major_tick_annotations.append( description )
plt.xticks(major_tick_locations, major_tick_annotations, rotation=xticks_rotation )
linewidth = 2
ax.xaxis.grid(True, which='major', color='#666666', linestyle='-', alpha=0.4, linewidth=linewidth)
###### Minor Grid Lines ######
minor_ticks = [x for x in df.index if x not in major_tick_locations and x % minor_markers == 0]
ax.xaxis.set_minor_locator(FixedLocator(minor_ticks))
ax.xaxis.grid(True, which='minor', color='#666666', linestyle='-', alpha=0.2, linewidth=1,)
###### Annotations ######
for annotation in annotations:
if type(annotation) == tuple:
if not isinstance( annotation[0], LectionInSystem ):
print("Trouble with annotation:", annotation)
continue
annotation_x = df.index[ df['Lection_Membership__id'] == annotation[0].id ].item()
annotation_description = annotation[-1]
else:
if not isinstance( annotation, LectionInSystem ):
print("Trouble with annotation:", annotation)
continue
annotation_x = df.index[ df['Lection_Membership__id'] == annotation.id ].item()
annotation_description = str(annotation.day)
if annotations_spaces_to_lines:
annotation_description = annotation_description.replace( ' ', "\n" )
plt.axvline(x=annotation_x, color=annotation_color, linestyle="--")
ax.annotate(annotation_description, xy=(annotation_x, ymax), xycoords='data', ha='center', va='bottom',xytext=(0,10), textcoords='offset points', fontsize=10, family='Linux Libertine O', color=annotation_color)
ax.legend(shadow=False, title='', framealpha=1, edgecolor='black', loc=legend_location, facecolor="white", ncol=2).set_zorder(100)
for region in highlight_regions:
from matplotlib.patches import Rectangle
region_start = region[0]
if isinstance(region_start, LectionInSystem):
region_start = df.index[ df['Lection_Membership__id'] == region_start.id ].item()
region_end = region[1]
if isinstance(region_end, LectionInSystem):
region_end = df.index[ df['Lection_Membership__id'] == region_end.id ].item()
rect = Rectangle((region_start,ymin),region_end-region_start,ymax-ymin,linewidth=1,facecolor=highlight_color)
ax.add_patch(rect)
plt.show()
if output_filename:
fig.tight_layout()
fig.savefig(output_filename)
notnull = False
for index, ms_siglum in enumerate(mss_sigla.keys()):
notnull = notnull | df[ms_siglum+'_similarity'].notnull()
ms_df = df[ notnull ]
print(ms_df)
for index, ms_siglum in enumerate(mss_sigla.keys()):
print( ms_siglum, df[ms_siglum+'_similarity'].mean() )
print("Number of lections:", ms_df.shape[0])
class AffiliationLectionsSet(AffiliationBase):
""" An abstract Affiliation class which is active only in certain lections which is defined by a function. """
class Meta:
abstract = True
def lections_where_active( self ):
""" This needs to be set by child class """
raise NotImplementedError
def is_active( self, verse ):
""" This affiliation is active whenever the verse is in the lection. If the verse is of type BibleVerse, then it is active if the lections have a mapping to that verse. """
if isinstance( verse, LectionaryVerse ):
return self.lections_where_active().filter( verses__id=verse.id ).exists()
elif isinstance( verse, BibleVerse ):
return self.lections_where_active().filter( verses__bible_verse__id=verse.id ).exists()
return False
def manuscript_and_verse_ids_at( self, verse ):
if isinstance( verse, LectionaryVerse ):
return super().manuscript_and_verse_ids_at( verse )
manuscript_ids = self.manuscript_ids_at(verse)
pairs = set()
if len(manuscript_ids) > 0:
verses = LectionaryVerse.objects.filter( bible_verse=verse, lection__in=self.lections_where_active())
for lectionary_verse in verses:
pairs.update( {(manuscript_id, lectionary_verse.id) for manuscript_id in manuscript_ids} )
return pairs
def distinct_bible_verses(self):
""" Returns a set of all the distinct verses from the lections of this affiliation object. """
distinct_verses = set()
for lection in self.lections_where_active():
distinct_verses.update([v.bible_verse for v in lection.verses.all()])
return distinct_verses
def distinct_bible_verses_count(self):
""" Returns the total number of distinct verses from the lections of this affiliation object. """
return len(self.distinct_bible_verses())
def verse_count(self):
"""
Returns the total number of verses from the lections of this affiliation object.
This may include verses multiple times.
"""
count = 0
for lection in self.lections_where_active():
count += lection.verses.count() # This should be done with an aggregation function in django
return count
class AffiliationLectionarySystem(AffiliationLectionsSet):
""" An Affiliation class which is active for all lections in a lectionary system (unless specified in an exclusion list). """
system = models.ForeignKey(LectionarySystem, on_delete=models.CASCADE)
exclude = models.ManyToManyField(Lection, blank=True, help_text="All the lections at which this affiliation object is not active.")
def lections_where_active(self):
""" All the lections that are included in this affiliation. """
return self.system.lections.exclude(id__in=self.exclude.values_list( 'id', flat=True ))
class AffiliationLections(AffiliationLectionsSet):
""" An Affiliation class which is active only in certain lections. """
lections = models.ManyToManyField(Lection, blank=True, help_text="All the lections at which this affiliation object is active.")
def lections_where_active(self):
""" All the lections that are included in this affiliation. """
return self.lections.all()
def add_lections( self, lections ):
""" Adds an iterable of lections to this affiliation object. They can be Lection objects or strings with unique descriptions of the lections. """
for lection in lections:
if isinstance(lection, str):
lection = Lection.objects.filter(description=lection).first()
if lection and isinstance( lection, Lection ):
self.lections.add(lection)
self.save()
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,681
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0005_auto_20190921_1617.py
|
# Generated by Django 2.2.2 on 2019-09-21 06:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0004_auto_20190921_1617'),
]
operations = [
migrations.RenameField(
model_name='lectioninsystem',
old_name='fixed_day',
new_name='fixed_date',
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,682
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0015_lectioninsystem_incipit.py
|
# Generated by Django 2.2.2 on 2020-03-14 02:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0014_auto_20200314_1246'),
]
operations = [
migrations.AddField(
model_name='lectioninsystem',
name='incipit',
field=models.TextField(blank=True, default=''),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,683
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0028_auto_20200813_2236.py
|
# Generated by Django 3.0.6 on 2020-08-13 12:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0027_affiliationlectionarysystem'),
]
operations = [
migrations.AlterModelOptions(
name='affiliationlectionarysystem',
options={},
),
migrations.AlterModelOptions(
name='affiliationlections',
options={},
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,684
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0019_auto_20200316_1849.py
|
# Generated by Django 2.2.2 on 2020-03-16 07:49
from django.db import migrations
# https://stackoverflow.com/questions/26927705/django-migration-error-you-cannot-alter-to-or-from-m2m-fields-or-add-or-remove/51351406
def create_through_relations(apps, schema_editor):
Lection = apps.get_model('dcodex_lectionary', 'Lection')
LectionaryVerseMembership = apps.get_model('dcodex_lectionary', 'LectionaryVerseMembership')
for lection in Lection.objects.all():
for verse in lection.verses.all():
LectionaryVerseMembership(
verse=verse,
lection=lection
).save()
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0018_auto_20200316_1848'),
]
operations = [
migrations.RunPython(create_through_relations, reverse_code=migrations.RunPython.noop),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,685
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0011_auto_20200225_1756.py
|
# Generated by Django 2.2.2 on 2020-02-25 06:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0010_auto_20200221_1733'),
]
operations = [
migrations.AlterModelOptions(
name='lectioninsystem',
options={'ordering': ('order', 'fixed_date', 'day_of_year', 'order_on_day')},
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,686
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0032_auto_20201119_2154.py
|
# Generated by Django 3.0.11 on 2020-11-19 10:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0031_auto_20201119_2140'),
]
operations = [
migrations.AlterModelOptions(
name='eothinaday',
options={'ordering': ('rank',)},
),
migrations.AlterModelOptions(
name='miscday',
options={'ordering': ('description',)},
),
migrations.AlterModelOptions(
name='movableday',
options={'ordering': ('rank', 'id')},
),
migrations.RemoveField(
model_name='lectionaryday',
name='description',
),
migrations.AddField(
model_name='miscday',
name='description',
field=models.CharField(default='', max_length=255),
preserve_default=False,
),
migrations.AddField(
model_name='movableday',
name='rank',
field=models.PositiveIntegerField(default=0),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,687
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/templatetags/dcodex_lectionary_tags.py
|
from django import template
import logging
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def affiliation_active_for(affiliation, lection):
if lection in affiliation.lections.all():
return "active"
return ""
@register.filter
def affiliation_button_for(affiliation, lection):
if lection in affiliation.lections.all():
icon = "fa-ban"
classes = "btn-outline-danger lection"
else:
icon = "fa-plus"
classes = "btn-outline-success lection"
return mark_safe(f'<button type="button" class="btn {classes}" data-lection="{lection.id}"><i class="fas {icon}"></i></button>')
@register.filter
def list_if_active(affiliation, membership):
if membership.lection in affiliation.lections.all():
day_description = membership.day_description()
return mark_safe(f'<li class="list-group-item lection" data-lection="{membership.lection.id}">\\item {membership.lection} ({day_description})</li>')
return ""
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,688
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0027_affiliationlectionarysystem.py
|
# Generated by Django 3.0.8 on 2020-08-10 10:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dcodex', '0025_auto_20200809_1536'),
('dcodex_lectionary', '0026_auto_20200809_1631'),
]
operations = [
migrations.CreateModel(
name='AffiliationLectionarySystem',
fields=[
('affiliationbase_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='dcodex.AffiliationBase')),
('exclude', models.ManyToManyField(blank=True, help_text='All the lections at which this affiliation object is not active.', to='dcodex_lectionary.Lection')),
('system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.LectionarySystem')),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('dcodex.affiliationbase',),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,689
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0030_auto_20201119_2131.py
|
# Generated by Django 3.0.11 on 2020-11-19 10:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('dcodex_lectionary', '0029_auto_20201116_2119'),
]
operations = [
migrations.CreateModel(
name='LectionaryDay',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.CharField(max_length=255)),
('polymorphic_ctype', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='polymorphic_dcodex_lectionary.lectionaryday_set+', to='contenttypes.ContentType')),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
),
migrations.CreateModel(
name='EothinaDay',
fields=[
('lectionaryday_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='dcodex_lectionary.LectionaryDay')),
('rank', models.IntegerField()),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('dcodex_lectionary.lectionaryday',),
),
migrations.CreateModel(
name='FixedDay',
fields=[
('lectionaryday_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='dcodex_lectionary.LectionaryDay')),
('date', models.DateField(blank=True, default=None, null=True)),
],
options={
'ordering': ('date',),
},
bases=('dcodex_lectionary.lectionaryday',),
),
migrations.CreateModel(
name='MiscDay',
fields=[
('lectionaryday_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='dcodex_lectionary.LectionaryDay')),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('dcodex_lectionary.lectionaryday',),
),
migrations.CreateModel(
name='MovableDay',
fields=[
('lectionaryday_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='dcodex_lectionary.LectionaryDay')),
('day_of_week', models.IntegerField(choices=[(0, 'Sunday'), (1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), (6, 'Saturday')])),
('period', models.CharField(choices=[('E', 'Easter'), ('P', 'Pentecost'), ('F', 'Feast of the Cross'), ('L', 'Lent'), ('G', 'Great Week'), ('T', 'Epiphany')], max_length=1)),
('week', models.CharField(max_length=31)),
('weekday_number', models.CharField(max_length=32)),
('earliest_date', models.CharField(max_length=15)),
('latest_date', models.CharField(max_length=15)),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('dcodex_lectionary.lectionaryday',),
),
migrations.AddField(
model_name='lectioninsystem',
name='lectionary_day',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.LectionaryDay'),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,690
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/tests/test_settings.py
|
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'akfjnakfcjaldunfkhaldfhalshf'
INSTALLED_APPS = [
'django.contrib.auth',
"django.contrib.contenttypes",
"adminsortable2",
'easy_thumbnails',
'filer',
'mptt',
'imagedeck',
'polymorphic',
"dcodex",
"dcodex_bible",
"dcodex_lectionary",
"tests",
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
"context_processors": [
"django.template.context_processors.request",
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
DEFAULT_AUTO_FIELD='django.db.models.AutoField' # for django 3.2
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,691
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0034_auto_20201122_2300.py
|
# Generated by Django 3.0.11 on 2020-11-22 12:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0033_auto_20201119_2239'),
]
operations = [
migrations.AlterModelOptions(
name='lectioninsystem',
options={'ordering': ('order', 'day', 'order_on_day')},
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,692
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0006_auto_20190927_1634.py
|
# Generated by Django 2.2.2 on 2019-09-27 06:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0005_auto_20190921_1617'),
]
operations = [
migrations.AlterModelOptions(
name='lectioninsystem',
options={'ordering': ['fixed_date', 'day_of_year', 'order_on_day']},
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,693
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/__init__.py
|
default_app_config = 'dcodex_lectionary.apps.DcodexLectionaryConfig'
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,694
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/views.py
|
from django.http import HttpResponse
from django.http import Http404
from django.shortcuts import get_object_or_404, render
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from dcodex_lectionary.models import *
from dcodex.util import get_request_dict
import logging
import json
@login_required
def lection_verses(request):
request_dict = get_request_dict(request)
lection = get_object_or_404(Lection, id=request_dict.get('lection_id'))
verse = LectionaryVerse.objects.filter( id=request_dict.get('verse_id') ).first()
field_id = request_dict.get('field_id')
field_class = request_dict.get('field_class')
return render(request, 'dcodex_lectionary/lection_verses.html', {'lection': lection, 'verse': verse, 'field_id':field_id , 'field_class':field_class} )
@login_required
def insert_lection(request):
request_dict = get_request_dict(request)
date = get_object_or_404(FixedDate, id=request_dict.get('date_id'))
lection = get_object_or_404(Lection, id=request_dict.get('lection_id'))
manuscript = get_object_or_404(Manuscript, id=request_dict.get('manuscript_id'))
insert_after_lection = get_object_or_404(Lection, id=request_dict.get('insert_after_lection_id'))
system = manuscript.system
if system is None:
return Http404("The manuscript '%s' does not have a lectionary system." % manuscript)
membership = system.insert_lection( date, lection, insert_after=insert_after_lection )
system.maintenance()
return JsonResponse({ 'first_verse_id':lection.first_verse_id,} );
@login_required
def create_lection(request):
request_dict = get_request_dict(request)
date = get_object_or_404(FixedDate, id=request_dict.get('date_id'))
manuscript = get_object_or_404(Manuscript, id=request_dict.get('manuscript_id'))
insert_after_lection = get_object_or_404(Lection, id=request_dict.get('insert_after_lection_id'))
lection_description = request_dict.get('lection_description');
overlapping_lection_IDs = json.loads(request_dict.get('overlapping_lection_IDs'))
overlapping_lections = [Lection.objects.get(id=id) for id in overlapping_lection_IDs]
lection = Lection.create_from_passages_string( lection_description, overlapping_lections=overlapping_lections, create_verses=True )
system = manuscript.system
if system is None:
return Http404("The manuscript '%s' does not have a lectionary system." % manuscript)
membership = system.insert_lection( date, lection, insert_after=insert_after_lection )
system.maintenance()
return JsonResponse({ 'first_verse_id':lection.first_verse_id,} );
@login_required
def insert_reference(request):
request_dict = get_request_dict(request)
date = get_object_or_404(FixedDate, id=request_dict.get('date_id'))
manuscript = get_object_or_404(Manuscript, id=request_dict.get('manuscript_id'))
insert_after_lection = get_object_or_404(Lection, id=request_dict.get('insert_after_lection_id'))
system = manuscript.system
reference_text_en = request_dict.get('reference_text_en');
#occasion_text = request_dict.get('occasion_text');
#occasion_text_en = request_dict.get('occasion_text_en');
reference_membership_id = request_dict.get('reference_membership')
reference_membership = get_object_or_404(LectionInSystem, id=reference_membership_id) if reference_membership_id else None
if system is None:
return Http404("The manuscript '%s' does not have a lectionary system." % manuscript)
membership = system.create_reference( date=date, insert_after=insert_after_lection, reference_text_en=reference_text_en, reference_membership=reference_membership )
return JsonResponse({ 'first_verse_id': membership.lection.first_verse_id,} );
@login_required
def lection_suggestions(request):
request_dict = get_request_dict(request)
date = get_object_or_404(FixedDate, id=request_dict.get('date_id'))
memberships = LectionInSystem.objects.filter( fixed_date=date ).all()
return render(request, 'dcodex_lectionary/lection_suggestions.html', {'memberships': memberships} )
@login_required
def add_lection_box(request):
request_dict = get_request_dict(request)
manuscript = get_object_or_404(Manuscript, id=request_dict.get('manuscript_id'))
movable_days = DayOfYear.objects.all()
fixed_days = FixedDate.objects.all()
lections = Lection.objects.all()
lection_in_system = get_object_or_404(LectionInSystem, id=request_dict.get('lection_in_system_id'))
return render(request, 'dcodex_lectionary/add_lection_box.html', {'manuscript': manuscript, 'lection_in_system':lection_in_system, 'movable_days': movable_days, 'fixed_days':fixed_days, 'lections':lections} )
@login_required
def count(request, request_siglum):
if request_siglum.isdigit():
manuscript = get_object_or_404(Manuscript, id=request_siglum)
else:
manuscript = get_object_or_404(Manuscript, siglum=request_siglum)
df = manuscript.transcribed_count_df()
title = "%s Count" % (str(manuscript.siglum))
return render(request, 'dcodex/table.html', {'table': df.to_html(), 'title':title} )
@login_required
def complete(request, request_sigla, request_lections):
mss = []
request_sigla = request_sigla.split(",")
for siglum in request_sigla:
ms = Manuscript.objects.filter(siglum=siglum).first()
if ms:
mss.append( ms )
request_lections = request_lections.replace( "_", " " )
request_lections = request_lections.split("|")
lections = []
for description in request_lections:
lection = Lection.objects.filter(description=description).first()
if lection:
lections.append( lection )
total_transcribed_count = defaultdict(int)
total_verses_count = 0
columns = ['Lection'] + [ms.siglum for ms in mss]
df = pd.DataFrame(columns=columns)
total = 0
for i, lection in enumerate(lections):
verses_count = lection.verses.count()
total_verses_count += verses_count
percentages = []
for ms in mss:
transcribed_verses_count = ms.lection_transcribed_count( lection )
percentages.append( transcribed_verses_count/verses_count*100.0 )
total_transcribed_count[ms.siglum] += transcribed_verses_count
total += transcribed_verses_count
df.loc[i] = [str(lection)] + percentages
def summary( total, total_verses_count ):
return "%d of %d (%f)" % (total, total_verses_count, total/total_verses_count*100.0 )
df.loc[len(df)] = [summary(total, total_verses_count * len(mss)) ] + [total_transcribed_count[ms.siglum]/total_verses_count*100.0 for ms in mss]
title = "%s Count" % (str(request_sigla))
formatters={ms.siglum: '{:,.1f}'.format for ms in mss}
styled_df = df.style.apply( lambda x: ['background-color: yellow' if value and value > 99 else 'background-color: lightgreen' if value > 0 else '' for value in x],
subset=request_sigla).format(formatters)#.apply( 'text-align: center', subset=request_sigla )
return render(request, 'dcodex/table.html', {'table': styled_df.render(), 'title':title} )
# return render(request, 'dcodex/table.html', {'table': df.to_html(formatters=formatters), 'title':title} )
@login_required
def similarity(request, request_siglum, comparison_sigla_string):
if request_siglum.isdigit():
manuscript = get_object_or_404(Manuscript, id=request_siglum)
else:
manuscript = get_object_or_404(Manuscript, siglum=request_siglum)
comparison_mss = []
comparison_sigla = comparison_sigla_string.split(",")
for comparison_siglum in comparison_sigla:
comparison_ms = Manuscript.objects.filter(siglum=comparison_siglum).first()
if comparison_ms:
comparison_mss.append( comparison_ms )
df = manuscript.similarity_df(comparison_mss, ignore_incipits=True)
title = "%s Similarity" % (str(manuscript.siglum))
threshold = 76.4
styled_df = df.style.apply( lambda x: ['font-weight: bold; background-color: yellow' if value and value > threshold else '' for value in x],
subset=comparison_sigla)
return render(request, 'dcodex/table.html', {'table': styled_df.render(), 'title':title} )
#return render(request, 'dcodex/table.html', {'table': df.to_html(), 'title':title} )
@login_required
def similarity_probabilities(request, request_siglum, comparison_sigla_string):
if request_siglum.isdigit():
manuscript = get_object_or_404(Manuscript, id=request_siglum)
else:
manuscript = get_object_or_404(Manuscript, siglum=request_siglum)
comparison_mss = []
comparison_sigla = comparison_sigla_string.split(",")
for comparison_siglum in comparison_sigla:
comparison_ms = Manuscript.objects.filter(siglum=comparison_siglum).first()
if comparison_ms:
comparison_mss.append( comparison_ms )
df = manuscript.similarity_probabilities_df(comparison_mss, ignore_incipits=True)
title = "%s Similarity" % (str(manuscript.siglum))
threshold = 76.4
styled_df = df.style.apply( lambda x: ['font-weight: bold; background-color: yellow' if value and value > threshold else '' for value in x],
subset=comparison_sigla)
return render(request, 'dcodex/table.html', {'table': styled_df.render(), 'title':title} )
@login_required
def affiliation_lections(request, affiliation_id, system_id):
affiliation = get_object_or_404(AffiliationLections, id=affiliation_id)
system = get_object_or_404(LectionarySystem, id=system_id)
return render(request, 'dcodex_lectionary/affiliation_lections.html', {'affiliation': affiliation, 'system': system, } )
@login_required
def affiliation_lections_list(request, affiliation_id, system_id):
affiliation = get_object_or_404(AffiliationLections, id=affiliation_id)
system = get_object_or_404(LectionarySystem, id=system_id)
return render(request, 'dcodex_lectionary/affiliation_lections_list.html', {'affiliation': affiliation, 'system': system, } )
@login_required
def toggle_affiliation_lection(request):
request_dict = get_request_dict(request)
affiliation = get_object_or_404(AffiliationLections, id=request_dict.get('affiliation_id'))
lection = get_object_or_404(Lection, id=request_dict.get('lection_id'))
if lection in affiliation.lections.all():
affiliation.lections.remove(lection)
else:
affiliation.lections.add(lection)
return HttpResponse("OK")
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,695
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/urls.py
|
from django.urls import path
from . import views
urlpatterns = [
path('ajax/lection-verses/', views.lection_verses, name='dcodex-lectionary-lection-verses'),
path('ajax/add-lection-box/', views.add_lection_box, name='dcodex-lectionary-add-lection-box'),
path('ajax/insert-lection/', views.insert_lection, name='dcodex-lectionary-insert-lection'),
path('ajax/create-lection/', views.create_lection, name='dcodex-lectionary-create-lection'),
path('ajax/insert-reference/', views.insert_reference, name='dcodex-lectionary-insert-reference'),
path('ajax/toggle_affiliation_lection', views.toggle_affiliation_lection, name='dcodex-lectionary-toggle-affiliation-lection'),
path('ajax/lection-suggestions/', views.lection_suggestions, name='dcodex-lectionary-lection-suggestions'),
path('ms/<str:request_siglum>/count/', views.count, name='dcodex-lectionary-count'),
path('ms/<str:request_siglum>/<str:comparison_sigla_string>/similarity/', views.similarity, name='dcodex-lectionary-similarity'),
path('ms/<str:request_siglum>/<str:comparison_sigla_string>/similarity_probabilities/', views.similarity_probabilities, name='dcodex-lectionary-similarity_probabilities'),
path('ms/<str:request_sigla>/<str:request_lections>/complete/', views.complete, name='dcodex-lectionary-complete'),
path('affiliation/<int:affiliation_id>/<int:system_id>/', views.affiliation_lections, name='dcodex-lectionary-affiliation_lections'),
path('affiliation_lections_list/<int:affiliation_id>/<int:system_id>/', views.affiliation_lections_list, name='dcodex-lectionary-affiliation_lections_list'),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,696
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0025_affiliationlections.py
|
# Generated by Django 2.2.2 on 2020-05-28 04:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dcodex', '0020_affiliationbase_name'),
('dcodex_lectionary', '0024_auto_20200526_1623'),
]
operations = [
migrations.CreateModel(
name='AffiliationLections',
fields=[
('affiliationbase_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='dcodex.AffiliationBase')),
('lections', models.ManyToManyField(help_text='All the lections at which this affiliation object is active.', to='dcodex_lectionary.Lection')),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('dcodex.affiliationbase',),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,697
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/admin.py
|
from django.contrib import admin
from polymorphic.admin import PolymorphicParentModelAdmin, PolymorphicChildModelAdmin, PolymorphicChildModelFilter
from adminsortable2.admin import SortableInlineAdminMixin, SortableAdminMixin
from dcodex.admin import ManuscriptChildAdmin
from .models import *
class LectionaryDayChildAdmin(PolymorphicChildModelAdmin):
""" Base admin class for all LectionaryDay models """
base_model = LectionaryDay # Optional, explicitly set here.
@admin.register(MiscDay)
class MiscDayAdmin(LectionaryDayChildAdmin):
base_model = MiscDay
show_in_index = True
@admin.register(EothinaDay)
class EothinaDayAdmin(LectionaryDayChildAdmin):
base_model = EothinaDay
show_in_index = True
@admin.register(FixedDay)
class FixedDayAdmin(LectionaryDayChildAdmin):
base_model = FixedDay
show_in_index = True
@admin.register(MovableDay)
class MovableDayAdmin(SortableAdminMixin, LectionaryDayChildAdmin):
base_model = MovableDay
show_in_index = True
list_per_page = 200
@admin.register(LectionaryDay)
class LectionaryDayParentAdmin(PolymorphicParentModelAdmin):
""" The parent LectionaryDay admin """
base_model = LectionaryDay # Optional, explicitly set here.
child_models = (MovableDay, FixedDay, EothinaDay, MiscDay)
list_filter = (PolymorphicChildModelFilter,) # This is optional.
class LectionaryVerseMembershipInlineSortable(SortableInlineAdminMixin, admin.TabularInline):
model = Lection.verses.through
raw_id_fields = ("verse",)
extra = 0
class LectionaryVerseMembershipInline(admin.TabularInline):
model = Lection.verses.through
raw_id_fields = ("verse",)
extra = 0
# Register your models here.
@admin.register(LectionaryVerse)
class LectionaryVerseAdmin(admin.ModelAdmin):
raw_id_fields = ("bible_verse",)
search_fields = ['unique_string' ]
inlines = [LectionaryVerseMembershipInline]
@admin.register(AffiliationLections)
class AffiliationLectionsAdmin(admin.ModelAdmin):
model = AffiliationLections
@admin.register(Lection)
class LectionAdmin(admin.ModelAdmin):
filter_horizontal = ('verses',)
search_fields = ['description']
# inlines = [LectionaryVerseMembershipInline]
inlines = [LectionaryVerseMembershipInlineSortable]
admin.site.register(AffiliationLectionarySystem)
admin.site.register(DayOfYear)
admin.site.register(FixedDate)
class LectionInSystemInline(admin.TabularInline):
model = LectionInSystem
extra = 0
raw_id_fields = ("lection", "day_of_year", "fixed_date", 'reference_membership')
class LectionInSystemInlineSortable(SortableInlineAdminMixin, admin.TabularInline):
model = LectionarySystem.lections.through
extra = 0
raw_id_fields = ("lection", "day_of_year", "fixed_date", 'reference_membership')
@admin.register(LectionInSystem)
class LectionInSystemAdmin(admin.ModelAdmin):
search_fields = ['order', 'lection__id', 'fixed_date__id' ]
@admin.register(LectionarySystem)
class LectionarySystemAdmin(admin.ModelAdmin):
# inlines = [LectionInSystemInline]
inlines = [LectionInSystemInlineSortable]
@admin.register(Lectionary)
class LectionaryAdmin(ManuscriptChildAdmin):
pass
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,698
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0023_auto_20200526_1559.py
|
# Generated by Django 2.2.2 on 2020-05-26 05:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0022_lectionaryverse_mass'),
]
operations = [
migrations.AddField(
model_name='lectionaryversemembership',
name='cummulative_mass_from_lection_start',
field=models.IntegerField(default=0, help_text='The total mass of verses from the beginning of the lection until this verse'),
),
migrations.AlterField(
model_name='dayofyear',
name='period',
field=models.CharField(choices=[('E', 'Easter'), ('P', 'Pentecost'), ('F', 'Feast of the Cross'), ('L', 'Lent'), ('G', 'Great Week'), ('T', 'Epiphany')], max_length=1),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,699
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/scripts/convert_lectionary_days.py
|
from dcodex.models import *
from dcodex_lectionary.models import *
def get_movable_day(day):
new_day, _ = MovableDay.objects.update_or_create(
day_of_week=day.day_of_week,
season=day.period,
week=day.week,
weekday_number=day.weekday_number,
defaults=dict(
earliest_date=day.earliest_date,
latest_date=day.latest_date,
)
)
return new_day
def get_other_day( day ):
if day.date:
new_day, _ = FixedDay.objects.update_or_create(
date=day.date,
)
elif 'Resurrection' in day.description:
rank = int(day.description.split()[-1])
new_day, _ = EothinaDay.objects.update_or_create(rank=rank)
else:
new_day, _ = MiscDay.objects.update_or_create(description=day.description)
return new_day
def run():
for day in DayOfYear.objects.all():
get_movable_day( day )
for day in FixedDate.objects.all():
get_other_day( day )
for membership in LectionInSystem.objects.all():
if membership.day_of_year:
membership.day = get_movable_day(membership.day_of_year)
elif membership.fixed_date:
membership.day = get_other_day(membership.fixed_date)
membership.save()
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,700
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/management/commands/export-lectionary-system.py
|
from django.core.management.base import BaseCommand, CommandError
import pandas as pd
from dcodex_lectionary import models
class Command(BaseCommand):
help = 'Exports a lectionary system to CSV.'
def add_arguments(self, parser):
parser.add_argument('system', type=str, help="The name of the lectionary system to export.")
parser.add_argument('csv', type=str, help="A path to output CSV file.")
def handle(self, *args, **options):
system = models.LectionarySystem.objects.filter( name=options['system'] ).first()
system.export_csv( options['csv'] )
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,701
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0013_auto_20200302_1226.py
|
# Generated by Django 2.2.2 on 2020-03-02 01:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0012_auto_20200225_1756'),
]
operations = [
migrations.AlterModelOptions(
name='fixeddate',
options={'ordering': ('date', 'description')},
),
migrations.AlterField(
model_name='fixeddate',
name='date',
field=models.DateField(blank=True, default=None, null=True),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,702
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0029_auto_20201116_2119.py
|
# Generated by Django 3.0.11 on 2020-11-16 10:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0028_auto_20200813_2236'),
]
operations = [
migrations.AlterField(
model_name='dayofyear',
name='description',
field=models.CharField(max_length=255),
),
migrations.AlterField(
model_name='dayofyear',
name='week',
field=models.CharField(max_length=31),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,703
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/management/commands/create-apostolos-e.py
|
from django.core.management.base import BaseCommand, CommandError
from dcodex_lectionary import models
class Command(BaseCommand):
help = 'Creates an Apostolos e lectionary system.'
def handle(self, *args, **options):
models.LectionarySystem.create_apostolos_e()
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,704
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0004_auto_20190921_1617.py
|
# Generated by Django 2.2.2 on 2019-09-21 06:17
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0003_lectionaryverse_unique_string'),
]
operations = [
migrations.CreateModel(
name='FixedDate',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.CharField(max_length=100)),
],
),
migrations.AlterField(
model_name='lectioninsystem',
name='day_of_year',
field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.DayOfYear'),
),
migrations.AddField(
model_name='lectioninsystem',
name='fixed_day',
field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.FixedDate'),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,705
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0021_lection_verses.py
|
# Generated by Django 2.2.2 on 2020-03-16 10:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0020_remove_lection_verses'),
]
operations = [
migrations.AddField(
model_name='lection',
name='verses',
field=models.ManyToManyField(through='dcodex_lectionary.LectionaryVerseMembership', to='dcodex_lectionary.LectionaryVerse'),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,706
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/management/commands/lectionary-system-maintenance.py
|
from django.core.management.base import BaseCommand, CommandError
import pandas as pd
from dcodex_lectionary import models
class Command(BaseCommand):
help = 'Does necessary maintenance on lectionary systems. Needed if the lections are changed.'
def handle(self, *args, **options):
models.LectionarySystem.maintenance_all_systems()
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,707
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/apps.py
|
from django.apps import AppConfig
class DcodexLectionaryConfig(AppConfig):
name = 'dcodex_lectionary'
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,708
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/tests/test_models.py
|
from pathlib import Path
from re import A
from django.test import TestCase
#from model_bakery import baker
from dcodex.models import *
from dcodex_bible.models import *
from imagedeck.models import DeckImage, Deck
from dcodex_lectionary.models import *
def make_easter_lection():
start_rank = book_names.index('John') * 100
char_aggregate = BibleVerse.objects.count()
for i in range(1,17+1):
BibleVerse.objects.create(
book=book_names.index('John'),
chapter=1,
verse=i,
rank=start_rank+i,
char_aggregate=char_aggregate+i*DEFAULT_LECTIONARY_VERSE_MASS,
char_count=DEFAULT_LECTIONARY_VERSE_MASS,
)
lection = Lection.update_or_create_from_passages_string( "Jn 1:1–17", create_verses=True)
return lection
def make_great_saturday_lection():
start_rank = book_names.index('Matthew') * 100
char_aggregate = BibleVerse.objects.count()
for i in range(1,20+1):
BibleVerse.objects.create(
book=book_names.index('Matthew'),
chapter=28,
verse=i,
rank=start_rank+i,
char_aggregate=char_aggregate+i*DEFAULT_LECTIONARY_VERSE_MASS,
char_count=DEFAULT_LECTIONARY_VERSE_MASS,
)
lection = Lection.update_or_create_from_passages_string( "Mt 28:1–20", create_verses=True)
return lection
class LectionTests(TestCase):
def test_cumulative_mass_from_lection_start(self):
lection = make_easter_lection()
for index, verse_membership in enumerate(lection.verse_memberships()):
self.assertEqual( verse_membership.cumulative_mass_from_lection_start, index*DEFAULT_LECTIONARY_VERSE_MASS )
class LectionaryVerseTests(TestCase):
def test_get_from_string(self):
make_great_saturday_lection()
verse = LectionaryVerse.get_from_string("Mt28:10")
self.assertIsNotNone( verse )
self.assertEqual(str(verse), "Matthew 28:10")
def test_mass(self):
make_great_saturday_lection()
verse = LectionaryVerse.get_from_string("Mt28:10")
self.assertEqual( verse.bible_verse.char_aggregate, 10*DEFAULT_LECTIONARY_VERSE_MASS )
self.assertEqual( verse.mass, DEFAULT_LECTIONARY_VERSE_MASS )
class LectionaryTests(TestCase):
def test_make_lection(self):
"""
tests making a lection
"""
easter_lection = make_easter_lection()
# for x in easter_lection.verses.all(): print(x)
great_saturday_lection = make_great_saturday_lection()
# for x in great_saturday_lection.verses.all(): print(x)
self.assertEquals( str(easter_lection), "Jn 1:1–17" )
self.assertIs( easter_lection.verses.count(), 17 )
self.assertEquals( str(great_saturday_lection), "Mt 28:1–20" )
self.assertIs( great_saturday_lection.verses.count(), 20 )
def test_lectionary_first_last_positions(self):
easter_lection = make_easter_lection()
great_saturday_lection = make_great_saturday_lection()
easter, _ = MovableDay.objects.update_or_create( season=MovableDay.EASTER, week=1, day_of_week=MovableDay.SUNDAY )
great_saturday, _ = MovableDay.objects.update_or_create( season=MovableDay.GREAT_WEEK, week=1, day_of_week=MovableDay.SATURDAY )
system = LectionarySystem.objects.create(name="Test Lectionary System")
system.add_lection(easter, easter_lection)
system.add_lection(great_saturday, great_saturday_lection)
ms = Lectionary.objects.create(name="Test Lectionary", system=system)
ms.imagedeck = Deck.objects.create(name="Test Lectionary Imagedeck")
ms.save()
membership1 = ms.imagedeck.add_image( DeckImage.objects.create() )
membership2 = ms.imagedeck.add_image( DeckImage.objects.create() )
membership3 = ms.imagedeck.add_image( DeckImage.objects.create() )
first_location = ms.save_location(easter_lection.verses.first(), membership1, 0.0, 0.0)
ms.save_location(easter_lection.verses.last(), membership2, 0.0, 0.0)
last_location = ms.save_location(great_saturday_lection.verses.last(), membership3, 0.0, 0.5)
ms.save_location(great_saturday_lection.verses.first(), membership3, 0.0, 0.0)
self.assertEqual( ms.first_location().id, first_location.id)
self.assertEqual( ms.last_location().id, last_location.id)
def test_affiliation_lection(self):
"""
Tests the ability to make an Affiliation from a lection.
"""
ms = Manuscript(name="Test Lectionary")
ms.save()
family1 = Family(name="Test Family 1")
family1.save()
family2 = Family(name="Test Family 2")
family2.save()
easter_lection = make_easter_lection()
great_saturday_lection = make_great_saturday_lection()
family1.add_manuscript_all( ms )
affiliation = AffiliationLections( name="Great Week Affiliation" )
family2.add_manuscript_to_affiliation( affiliation, ms )
affiliation.add_lections( ["Mt 28:1–20"] )
self.assertIs( ms.families_at(easter_lection.verses.first()).count(), 1 )
self.assertIs( ms.families_at(great_saturday_lection.verses.first()).count(), 2 )
self.assertIs( ms.is_in_family_at(family1, easter_lection.verses.last()), True )
self.assertIs( ms.is_in_family_at(family2, easter_lection.verses.last()), False )
self.assertIs( ms.is_in_family_at(family1, great_saturday_lection.verses.last()), True )
self.assertIs( ms.is_in_family_at(family2, great_saturday_lection.verses.last()), True )
self.assertIs( ms.is_in_family_at(family1, easter_lection.verses.last().bible_verse), True )
self.assertIs( ms.is_in_family_at(family2, easter_lection.verses.last().bible_verse), False )
self.assertIs( ms.is_in_family_at(family1, great_saturday_lection.verses.last().bible_verse), True )
self.assertIs( ms.is_in_family_at(family2, great_saturday_lection.verses.last().bible_verse), True )
def test_affiliation_lection_overlap(self):
"""
Tests the ability to make an Affiliation from a lection where the groups overlap.
"""
ms = Manuscript(name="Test Lectionary")
ms.save()
family1 = Family(name="Test Family 1")
family1.save()
family2 = Family(name="Test Family 2")
family2.save()
easter_lection = make_easter_lection()
great_saturday_lection = make_great_saturday_lection()
family1.add_manuscript_all( ms )
overlap_affiliation = AffiliationLections( name="families 1 & 2 overlap" )
overlap_affiliation.save()
overlap_affiliation.families.add( family1 )
overlap_affiliation.families.add( family2 )
overlap_affiliation.add_lections( ["Mt 28:1–20"] )
overlap_affiliation.save()
self.assertIs( ms.families_at(easter_lection.verses.first()).count(), 1 )
self.assertIs( ms.families_at(great_saturday_lection.verses.first()).count(), 2 )
self.assertIs( ms.is_in_family_at(family1, easter_lection.verses.last()), True )
self.assertIs( ms.is_in_family_at(family2, easter_lection.verses.last()), False )
self.assertIs( ms.is_in_family_at(family1, great_saturday_lection.verses.last()), True )
self.assertIs( ms.is_in_family_at(family2, great_saturday_lection.verses.last()), True )
self.assertIs( ms.is_in_family_at(family1, easter_lection.verses.last().bible_verse), True )
self.assertIs( ms.is_in_family_at(family2, easter_lection.verses.last().bible_verse), False )
self.assertIs( ms.is_in_family_at(family1, great_saturday_lection.verses.last().bible_verse), True )
self.assertIs( ms.is_in_family_at(family2, great_saturday_lection.verses.last().bible_verse), True )
class AffiliationLectionsTests(TestCase):
def setUp(self):
self.ms = Manuscript(name="Test Lectionary")
self.ms.save()
self.family1 = Family(name="Test Family 1")
self.family1.save()
easter_lection = make_easter_lection()
great_saturday_lection = make_great_saturday_lection()
overlap_affiliation = AffiliationLections( name="families 1 & 2 overlap" )
overlap_affiliation.save()
overlap_affiliation.families.add( self.family1 )
overlap_affiliation.manuscripts.add( self.ms )
overlap_affiliation.add_lections( ["Mt 28:1–20"] )
overlap_affiliation.save()
def test_manuscript_and_verse_ids_at(self):
bible_verse = BibleVerse.get_from_string( "Mt 28:1" )
pairs = list(self.family1.manuscript_and_verse_ids_at( bible_verse ))
self.assertEqual( len(pairs), 1 )
manuscript_id = pairs[0][0]
verse_id = pairs[0][1]
self.assertEqual( manuscript_id, self.ms.id )
found_verse = Verse.objects.get(id=verse_id)
self.assertEqual( manuscript_id, self.ms.id )
self.assertIs(type(found_verse), LectionaryVerse)
self.assertEqual(found_verse.bible_verse.id, bible_verse.id)
def test_manuscript_and_verse_ids_at_none(self):
bible_verse = BibleVerse.get_from_string( "Jn 1:1" )
pairs = list(self.family1.manuscript_and_verse_ids_at( bible_verse ))
self.assertEqual( len(pairs), 0 )
class AffiliationLectionarySystemTests(TestCase):
def setUp(self):
self.ms = Manuscript(name="Test Lectionary")
self.ms.save()
self.system = LectionarySystem(name="Test Lectionary System")
self.system.save()
self.family1 = Family(name="Test Family 1")
self.family1.save()
easter_lection = make_easter_lection()
great_saturday_lection = make_great_saturday_lection()
self.system.lections.add( easter_lection )
affiliation = AffiliationLectionarySystem( name="Test AffiliationLectionarySystem", system=self.system )
affiliation.save()
affiliation.families.add( self.family1 )
affiliation.manuscripts.add( self.ms )
affiliation.save()
def test_manuscript_and_verse_ids_at(self):
bible_verse = BibleVerse.get_from_string( "Jn 1:1" )
pairs = list(self.family1.manuscript_and_verse_ids_at( bible_verse ))
self.assertEqual( len(pairs), 1 )
manuscript_id = pairs[0][0]
verse_id = pairs[0][1]
self.assertEqual( manuscript_id, self.ms.id )
found_verse = Verse.objects.get(id=verse_id)
self.assertEqual( manuscript_id, self.ms.id )
self.assertIs(type(found_verse), LectionaryVerse)
self.assertEqual(found_verse.bible_verse.id, bible_verse.id)
def test_manuscript_and_verse_ids_at_none(self):
bible_verse = BibleVerse.get_from_string( "Mt 28:1" )
pairs = list(self.family1.manuscript_and_verse_ids_at( bible_verse ))
self.assertEqual( len(pairs), 0 )
class MovableDayTests(TestCase):
def test_read_season(self):
self.assertEquals( MovableDay.read_season("Easter"), MovableDay.EASTER )
self.assertEquals( MovableDay.read_season("EAST"), MovableDay.EASTER )
self.assertEquals( MovableDay.read_season("Pent"), MovableDay.PENTECOST )
self.assertEquals( MovableDay.read_season("Pentecost"), MovableDay.PENTECOST )
self.assertEquals( MovableDay.read_season("Feast"), MovableDay.FEAST_OF_THE_CROSS )
self.assertEquals( MovableDay.read_season("Great Week "), MovableDay.GREAT_WEEK )
self.assertEquals( MovableDay.read_season("L"), MovableDay.LENT )
self.assertEquals( MovableDay.read_season("EPIPH"), MovableDay.EPIPHANY )
self.assertEquals( MovableDay.read_season("Theophany"), MovableDay.EPIPHANY )
self.assertEquals( MovableDay.read_season("cross"), MovableDay.FEAST_OF_THE_CROSS )
def test_read_day(self):
self.assertEquals( MovableDay.read_day_of_week("Sunday"), MovableDay.SUNDAY )
self.assertEquals( MovableDay.read_day_of_week("sun"), MovableDay.SUNDAY )
self.assertEquals( MovableDay.read_day_of_week("Tues"), MovableDay.TUESDAY )
class LectionarySystemTests(TestCase):
def setUp(self):
self.system = LectionarySystem(name="Test Lectionary System")
self.system.save()
def test_import_csv_incomplete(self):
csv = Path(__file__).parent/"testdata/test-system-incomplete.csv"
with self.assertRaises(ValueError):
self.system.import_csv( csv )
def test_import_csv_incorrect_date(self):
csv = Path(__file__).parent/"testdata/test-system-incorrect-date.csv"
with self.assertRaises(ValueError):
self.system.import_csv( csv )
def test_import_csv(self):
# Create Days
easter, _ = MovableDay.objects.update_or_create( season=MovableDay.EASTER, week=1, day_of_week=MovableDay.SUNDAY )
great_saturday, _ = MovableDay.objects.update_or_create( season=MovableDay.GREAT_WEEK, week=1, day_of_week=MovableDay.SATURDAY )
gold_days = [easter, great_saturday]
gold_lections = [make_easter_lection(), make_great_saturday_lection()]
csv = Path(__file__).parent/"testdata/test-system.csv"
self.system.import_csv( csv )
self.assertEquals( self.system.lections.count(), 2 )
lection_memberships = list(self.system.lections_in_system())
for membership, gold_day, gold_lection in zip(lection_memberships, gold_days, gold_lections):
self.assertEquals( membership.day.id, gold_day.id)
self.assertEquals( membership.lection.id, gold_lection.id)
def test_dataframe(self):
easter, _ = MovableDay.objects.update_or_create( season=MovableDay.EASTER, week=1, day_of_week=MovableDay.SUNDAY )
great_saturday, _ = MovableDay.objects.update_or_create( season=MovableDay.GREAT_WEEK, week=1, day_of_week=MovableDay.SATURDAY )
gold_days = [easter, great_saturday]
gold_lections = [make_easter_lection(), make_great_saturday_lection()]
for day, lection in zip(gold_days, gold_lections):
self.system.add_lection( day, lection )
df = self.system.dataframe()
gold_columns = ['lection', 'season', 'week', 'day']
self.assertListEqual( gold_columns, list(df.columns) )
self.assertEquals( len(df.index), 2 )
class FixtureTests(TestCase):
fixtures = ["lectionarydays.json"]
def test_moveable_days(self):
self.assertEqual( MovableDay.objects.filter( season=MovableDay.EASTER, week=1, day_of_week=MovableDay.SUNDAY ).count(), 1 )
self.assertEqual( MovableDay.objects.filter( season=MovableDay.PENTECOST, week=1, day_of_week=MovableDay.MONDAY ).count(), 1 )
class LectionaryLocationTests(TestCase):
def setUp(self):
easter_lection = make_easter_lection()
great_saturday_lection = make_great_saturday_lection()
easter, _ = MovableDay.objects.update_or_create( season=MovableDay.EASTER, week=1, day_of_week=MovableDay.SUNDAY )
great_saturday, _ = MovableDay.objects.update_or_create( season=MovableDay.GREAT_WEEK, week=1, day_of_week=MovableDay.SATURDAY )
system = LectionarySystem.objects.create(name="Test Lectionary System")
system.add_lection(easter, easter_lection)
system.add_lection(great_saturday, great_saturday_lection)
system.maintenance()
self.ms = Lectionary.objects.create(name="Test Lectionary", system=system)
self.ms.imagedeck = Deck.objects.create(name="Test Lectionary Imagedeck")
self.ms.save()
self.membership1 = self.ms.imagedeck.add_image( DeckImage.objects.create() )
self.membership2 = self.ms.imagedeck.add_image( DeckImage.objects.create() )
self.membership3 = self.ms.imagedeck.add_image( DeckImage.objects.create() )
self.first_location = self.ms.save_location(easter_lection.verses.first(), self.membership1, 0.0, 0.0)
self.ms.save_location(easter_lection.verses.last(), self.membership2, 0.0, 0.0)
verse = LectionaryVerse.get_from_string("Mt28:10")
self.last_location = self.ms.save_location(verse, self.membership3, 0.0, 0.5)
verse = LectionaryVerse.get_from_string("Mt28:1")
self.ms.save_location(verse, self.membership3, 0.0, 0.0)
def test_lectionary_first_position(self):
self.assertEqual( self.ms.first_location().id, self.first_location.id)
def test_lectionary_first_position(self):
self.assertEqual( self.ms.last_location().id, self.last_location.id)
def test_lectionary_extrapolate(self):
location = self.ms.location( LectionaryVerse.get_from_string("Mt28:20") )
self.assertEqual( location.id, None )
self.assertIsNotNone( location.deck_membership )
self.assertEqual( location.deck_membership.id, self.membership3.id )
self.assertEqual( location.y, 1.0 )
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,709
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0031_auto_20201119_2140.py
|
# Generated by Django 3.0.11 on 2020-11-19 10:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0030_auto_20201119_2131'),
]
operations = [
migrations.RenameField(
model_name='movableday',
old_name='period',
new_name='season',
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,710
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0035_auto_20210811_1101.py
|
# Generated by Django 3.2.6 on 2021-08-11 01:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0034_auto_20201122_2300'),
]
operations = [
migrations.AlterField(
model_name='movableday',
name='earliest_date',
field=models.CharField(blank=True, default='', max_length=15),
),
migrations.AlterField(
model_name='movableday',
name='latest_date',
field=models.CharField(blank=True, default='', max_length=15),
),
migrations.AlterField(
model_name='movableday',
name='week',
field=models.CharField(blank=True, default='', max_length=31),
),
migrations.AlterField(
model_name='movableday',
name='weekday_number',
field=models.CharField(blank=True, default='', max_length=32),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,711
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0012_auto_20200225_1756.py
|
# Generated by Django 2.2.2 on 2020-02-25 06:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0011_auto_20200225_1756'),
]
operations = [
migrations.AlterField(
model_name='lectioninsystem',
name='day_of_year',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.DayOfYear'),
),
migrations.AlterField(
model_name='lectioninsystem',
name='fixed_date',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.FixedDate'),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,712
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0003_lectionaryverse_unique_string.py
|
# Generated by Django 2.2.2 on 2019-09-19 12:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0002_remove_lectionaryverse_unique_string'),
]
operations = [
migrations.AddField(
model_name='lectionaryverse',
name='unique_string',
field=models.CharField(default='', max_length=20),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,713
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0026_auto_20200809_1631.py
|
# Generated by Django 3.0.8 on 2020-08-09 06:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0025_affiliationlections'),
]
operations = [
migrations.AlterField(
model_name='affiliationlections',
name='lections',
field=models.ManyToManyField(blank=True, help_text='All the lections at which this affiliation object is active.', to='dcodex_lectionary.Lection'),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,714
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0001_initial.py
|
# Generated by Django 2.2.2 on 2019-09-19 12:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('dcodex', '0001_initial'),
('dcodex_bible', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='DayOfYear',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('day_of_week', models.IntegerField(choices=[(0, 'Sunday'), (1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), (6, 'Saturday')])),
('period', models.CharField(choices=[('E', 'Easter'), ('P', 'Pentecost'), ('F', 'Feast of the Cross'), ('L', 'Lent'), ('G', 'Great Week')], max_length=1)),
('week', models.CharField(max_length=15)),
('weekday_number', models.CharField(max_length=32)),
('earliest_date', models.CharField(max_length=15)),
('latest_date', models.CharField(max_length=15)),
],
options={
'verbose_name_plural': 'Days of year',
},
),
migrations.CreateModel(
name='Lection',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='LectionarySystem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
],
),
migrations.CreateModel(
name='LectionInSystem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('order_on_day', models.IntegerField(default=0)),
('day_of_year', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.DayOfYear')),
('lection', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.Lection')),
('system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.LectionarySystem')),
],
options={
'ordering': ['day_of_year', 'order_on_day'],
},
),
migrations.CreateModel(
name='LectionaryVerse',
fields=[
('verse_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='dcodex.Verse')),
('unique_string', models.CharField(default='', max_length=20)),
('bible_verse', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dcodex_bible.BibleVerse')),
],
options={
'abstract': False,
'base_manager_name': 'objects',
},
bases=('dcodex.verse',),
),
migrations.AddField(
model_name='lectionarysystem',
name='lections',
field=models.ManyToManyField(through='dcodex_lectionary.LectionInSystem', to='dcodex_lectionary.Lection'),
),
migrations.CreateModel(
name='Lectionary',
fields=[
('manuscript_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='dcodex.Manuscript')),
('system', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dcodex_lectionary.LectionarySystem')),
],
options={
'verbose_name_plural': 'Lectionaries',
},
bases=('dcodex.manuscript',),
),
migrations.AddField(
model_name='lection',
name='verses',
field=models.ManyToManyField(to='dcodex_lectionary.LectionaryVerse'),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,715
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/management/commands/import-lectionary-system.py
|
from django.core.management.base import BaseCommand, CommandError
import pandas as pd
from dcodex_lectionary import models
class Command(BaseCommand):
help = 'Imports a lectionary system from CSV.'
def add_arguments(self, parser):
parser.add_argument('system', type=str, help="The name of the lectionary system to import.")
parser.add_argument('csv', type=str, help="A CSV file with columns corresponding to 'period', 'week', 'day', 'passage', 'parallels' (optional).")
parser.add_argument('--flush', action='store_true', help="Removes the lections on this system before importing.")
def handle(self, *args, **options):
system, _ = models.LectionarySystem.objects.update_or_create( name=options['system'] )
if options['flush']:
system.lections.all().delete()
system.import_csv( options['csv'] )
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,716
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0010_auto_20200221_1733.py
|
# Generated by Django 2.2.2 on 2020-02-21 06:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0009_fixeddate_date'),
]
operations = [
migrations.AlterModelOptions(
name='lection',
options={'ordering': ['first_bible_verse_id', 'description']},
),
migrations.AddField(
model_name='lection',
name='first_bible_verse_id',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='lection',
name='first_verse_id',
field=models.IntegerField(default=0),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,717
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0022_lectionaryverse_mass.py
|
# Generated by Django 2.2.2 on 2020-03-16 10:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0021_lection_verses'),
]
operations = [
migrations.AddField(
model_name='lectionaryverse',
name='mass',
field=models.PositiveIntegerField(default=0),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,718
|
rbturnbull/dcodex_lectionary
|
refs/heads/master
|
/dcodex_lectionary/migrations/0016_auto_20200314_1804.py
|
# Generated by Django 2.2.2 on 2020-03-14 07:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dcodex_lectionary', '0015_lectioninsystem_incipit'),
]
operations = [
migrations.AlterField(
model_name='lectionaryverse',
name='bible_verse',
field=models.ForeignKey(blank=True, default=None, on_delete=django.db.models.deletion.CASCADE, to='dcodex_bible.BibleVerse'),
),
migrations.AlterField(
model_name='lectionaryverse',
name='unique_string',
field=models.CharField(default='', max_length=100),
),
]
|
{"/dcodex_lectionary/views.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/urls.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/admin.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/scripts/convert_lectionary_days.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/export-lectionary-system.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/create-apostolos-e.py": ["/dcodex_lectionary/__init__.py"], "/dcodex_lectionary/management/commands/lectionary-system-maintenance.py": ["/dcodex_lectionary/__init__.py"], "/tests/test_models.py": ["/dcodex_lectionary/models.py"], "/dcodex_lectionary/management/commands/import-lectionary-system.py": ["/dcodex_lectionary/__init__.py"]}
|
32,737
|
zapplecat/oschmod
|
refs/heads/main
|
/oschmod/__init__.py
|
# -*- coding: utf-8 -*-
"""oschmod module.
Module for working with file permissions that are consistent across Windows,
macOS, and Linux.
These bitwise permissions from the stat module can be used with this module:
stat.S_IRWXU # Mask for file owner permissions
stat.S_IREAD # Owner has read permission
stat.S_IRUSR # Owner has read permission
stat.S_IWRITE # Owner has write permission
stat.S_IWUSR # Owner has write permission
stat.S_IEXEC # Owner has execute permission
stat.S_IXUSR # Owner has execute permission
stat.S_IRWXG # Mask for group permissions
stat.S_IRGRP # Group has read permission
stat.S_IWGRP # Group has write permission
stat.S_IXGRP # Group has execute permission
stat.S_IRWXO # Mask for permissions for others (not in group)
stat.S_IROTH # Others have read permission
stat.S_IWOTH # Others have write permission
stat.S_IXOTH # Others have execute permission
"""
import os
import platform
import random
import re
import stat
import string
IS_WINDOWS = platform.system() == 'Windows'
HAS_PYWIN32 = False
try:
import ntsecuritycon # noqa: F401
import win32security # noqa: F401
from pywintypes import error as pywinerror
HAS_PYWIN32 = True
except ImportError:
pass
HAS_PWD = False
try:
import pwd # noqa: F401
import grp # noqa: F401
HAS_PWD = True
except ImportError:
pass
if IS_WINDOWS and not HAS_PYWIN32:
raise ImportError("win32security and ntsecuritycon required on Windows")
if HAS_PYWIN32:
W_FLDIR = ntsecuritycon.FILE_LIST_DIRECTORY # = 1
W_FADFL = ntsecuritycon.FILE_ADD_FILE # = 10
W_FADSD = ntsecuritycon.FILE_ADD_SUBDIRECTORY # = 100
W_FRDEA = ntsecuritycon.FILE_READ_EA # = 1000
W_FWREA = ntsecuritycon.FILE_WRITE_EA # = 10000
W_FTRAV = ntsecuritycon.FILE_TRAVERSE # = 100000
W_FDLCH = ntsecuritycon.FILE_DELETE_CHILD # = 1000000
W_FRDAT = ntsecuritycon.FILE_READ_ATTRIBUTES # = 10000000
W_FWRAT = ntsecuritycon.FILE_WRITE_ATTRIBUTES # = 100000000
W_DELET = ntsecuritycon.DELETE # = 10000000000000000
W_RDCON = ntsecuritycon.READ_CONTROL # = 100000000000000000
W_WRDAC = ntsecuritycon.WRITE_DAC # = 1000000000000000000
W_WROWN = ntsecuritycon.WRITE_OWNER # = 10000000000000000000
W_SYNCH = ntsecuritycon.SYNCHRONIZE # = 100000000000000000000
W_FGNEX = ntsecuritycon.FILE_GENERIC_EXECUTE # = 100100000000010100000
W_FGNRD = ntsecuritycon.FILE_GENERIC_READ # = 100100000000010001001
W_FGNWR = ntsecuritycon.FILE_GENERIC_WRITE # = 100100000000100010110
W_GENAL = ntsecuritycon.GENERIC_ALL # 10000000000000000000000000000
W_GENEX = ntsecuritycon.GENERIC_EXECUTE # 100000000000000000000000000000
W_GENWR = ntsecuritycon.GENERIC_WRITE # 1000000000000000000000000000000
W_GENRD = ntsecuritycon.GENERIC_READ # -10000000000000000000000000000000
W_DIRRD = W_FLDIR | W_FRDEA | W_FRDAT | W_RDCON | W_SYNCH
W_DIRWR = W_FADFL | W_FADSD | W_FWREA | W_FDLCH | W_FWRAT | W_DELET | \
W_RDCON | W_WRDAC | W_WROWN | W_SYNCH
W_DIREX = W_FTRAV | W_RDCON | W_SYNCH
W_FILRD = W_FGNRD
W_FILWR = W_FDLCH | W_DELET | W_WRDAC | W_WROWN | W_FGNWR
W_FILEX = W_FGNEX
WIN_RWX_PERMS = [
[W_FILRD, W_FILWR, W_FILEX],
[W_DIRRD, W_DIRWR, W_DIREX]
]
WIN_FILE_PERMISSIONS = (
"DELETE", "READ_CONTROL", "WRITE_DAC", "WRITE_OWNER",
"SYNCHRONIZE", "FILE_GENERIC_READ", "FILE_GENERIC_WRITE",
"FILE_GENERIC_EXECUTE", "FILE_DELETE_CHILD")
WIN_DIR_PERMISSIONS = (
"DELETE", "READ_CONTROL", "WRITE_DAC", "WRITE_OWNER",
"SYNCHRONIZE", "FILE_ADD_SUBDIRECTORY", "FILE_ADD_FILE",
"FILE_DELETE_CHILD", "FILE_LIST_DIRECTORY", "FILE_TRAVERSE",
"FILE_READ_ATTRIBUTES", "FILE_WRITE_ATTRIBUTES", "FILE_READ_EA",
"FILE_WRITE_EA")
WIN_DIR_INHERIT_PERMISSIONS = (
"DELETE", "READ_CONTROL", "WRITE_DAC", "WRITE_OWNER",
"SYNCHRONIZE", "GENERIC_READ", "GENERIC_WRITE", "GENERIC_EXECUTE",
"GENERIC_ALL")
WIN_ACE_TYPES = (
"ACCESS_ALLOWED_ACE_TYPE", "ACCESS_DENIED_ACE_TYPE",
"SYSTEM_AUDIT_ACE_TYPE", "SYSTEM_ALARM_ACE_TYPE")
WIN_INHERITANCE_TYPES = (
"OBJECT_INHERIT_ACE", "CONTAINER_INHERIT_ACE",
"NO_PROPAGATE_INHERIT_ACE", "INHERIT_ONLY_ACE",
"INHERITED_ACE", "SUCCESSFUL_ACCESS_ACE_FLAG",
"FAILED_ACCESS_ACE_FLAG")
SECURITY_NT_AUTHORITY = ('SYSTEM', 'NT AUTHORITY', 5)
FILE = 0
DIRECTORY = 1
OBJECT_TYPES = [FILE, DIRECTORY]
OWNER = 0
GROUP = 1
OTHER = 2
OWNER_TYPES = [OWNER, GROUP, OTHER]
READ = 0
WRITE = 1
EXECUTE = 2
OPER_TYPES = [READ, WRITE, EXECUTE]
STAT_MODES = [
[stat.S_IRUSR, stat.S_IWUSR, stat.S_IXUSR],
[stat.S_IRGRP, stat.S_IWGRP, stat.S_IXGRP],
[stat.S_IROTH, stat.S_IWOTH, stat.S_IXOTH]
]
STAT_KEYS = (
"S_IRUSR",
"S_IWUSR",
"S_IXUSR",
"S_IRGRP",
"S_IWGRP",
"S_IXGRP",
"S_IROTH",
"S_IWOTH",
"S_IXOTH"
)
__version__ = "0.3.12"
def get_mode(path):
"""Get bitwise mode (stat) of object (dir or file)."""
if IS_WINDOWS:
return win_get_permissions(path)
return os.stat(path).st_mode & (stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
def set_mode(path, mode):
"""
Set bitwise mode (stat) of object (dir or file).
Three types of modes can be used:
1. Decimal mode - an integer representation of set bits (eg, 512)
2. Octal mode - a string expressing an octal number (eg, "777")
3. Symbolic representation - a string with modifier symbols (eg, "+x")
"""
new_mode = 0
if isinstance(mode, int):
new_mode = mode
elif isinstance(mode, str):
if '+' in mode or '-' in mode or '=' in mode:
new_mode = get_effective_mode(get_mode(path), mode)
else:
new_mode = int(mode, 8)
if IS_WINDOWS:
return win_set_permissions(path, new_mode)
return os.chmod(path, new_mode)
def set_mode_recursive(path, mode, dir_mode=None):
r"""
Set all file and directory permissions at or under path to modes.
Args:
path: (:obj:`str`)
Object which will have its mode set. If path is a file, only its mode
is set - no recursion occurs. If path is a directory, its mode and the
mode of all files and subdirectories below it are set.
mode: (`int`)
Mode to be applied to object(s).
dir_mode: (`int`)
If provided, this mode is given to all directories only.
"""
if get_object_type(path) == FILE:
return set_mode(path, mode)
if not dir_mode:
dir_mode = mode
for root, dirs, files in os.walk(path, topdown=False):
for one_file in files:
set_mode(os.path.join(root, one_file), mode)
for one_dir in dirs:
set_mode(os.path.join(root, one_dir), dir_mode)
return set_mode(path, dir_mode)
def _get_effective_mode_multiple(current_mode, modes):
"""Get octal mode, given current mode and symbolic mode modifiers."""
new_mode = current_mode
for mode in modes.split(","):
new_mode = get_effective_mode(new_mode, mode)
return new_mode
def get_effective_mode(current_mode, symbolic):
"""Get octal mode, given current mode and symbolic mode modifier."""
if not isinstance(symbolic, str):
raise AttributeError('symbolic must be a string')
if "," in symbolic:
return _get_effective_mode_multiple(current_mode, symbolic)
result = re.search(r'^\s*([ugoa]*)([-+=])([rwx]*)\s*$', symbolic)
if result is None:
raise AttributeError('bad format of symbolic representation modifier')
whom = result.group(1) or "ugo"
operation = result.group(2)
perm = result.group(3)
if "a" in whom:
whom = "ugo"
# bitwise magic
bit_perm = _get_basic_symbol_to_mode(perm)
mask_mode = ("u" in whom and bit_perm << 6) | \
("g" in whom and bit_perm << 3) | \
("o" in whom and bit_perm << 0)
if operation == "=":
original = ("u" not in whom and current_mode & 448) | \
("g" not in whom and current_mode & 56) | \
("o" not in whom and current_mode & 7)
return mask_mode | original
if operation == "+":
return current_mode | mask_mode
return current_mode & ~mask_mode
def get_object_type(path):
"""Get whether object is file or directory."""
object_type = DIRECTORY
if os.path.isfile(path):
object_type = FILE
return object_type
def get_owner(path):
"""Get the object owner."""
if IS_WINDOWS:
return win32security.LookupAccountSid(None, win_get_owner_sid(path))
return pwd.getpwuid(os.stat(path).st_uid).pw_name
def get_group(path):
"""Get the object group."""
if IS_WINDOWS:
return win32security.LookupAccountSid(None, win_get_group_sid(path))
return grp.getgrgid(os.stat(path).st_gid).gr_name
def win_get_owner_sid(path):
"""Get the file owner."""
sec_descriptor = win32security.GetNamedSecurityInfo(
path, win32security.SE_FILE_OBJECT,
win32security.OWNER_SECURITY_INFORMATION)
return sec_descriptor.GetSecurityDescriptorOwner()
def win_get_group_sid(path):
"""Get the file group."""
sec_descriptor = win32security.GetNamedSecurityInfo(
path, win32security.SE_FILE_OBJECT,
win32security.GROUP_SECURITY_INFORMATION)
return sec_descriptor.GetSecurityDescriptorGroup()
def win_get_other_sid():
"""Get the other SID.
For now this is the Users builtin account. In the future, probably should
allow account to be passed in and find any non-owner, non-group account
currently associated with the file. As a default, it could use Users."""
return win32security.ConvertStringSidToSid("S-1-5-32-545")
def convert_win_to_stat(win_perm, user_type, object_type):
"""Given Win perm and user type, give stat mode."""
mode = 0
for oper in OPER_TYPES:
if win_perm & WIN_RWX_PERMS[object_type][oper] == \
WIN_RWX_PERMS[object_type][oper]:
mode = mode | STAT_MODES[user_type][oper]
return mode
def convert_stat_to_win(mode, user_type, object_type):
"""Given stat mode, return Win bitwise permissions for user type."""
win_perm = 0
for oper in OPER_TYPES:
if mode & STAT_MODES[user_type][oper] == STAT_MODES[user_type][oper]:
win_perm = win_perm | WIN_RWX_PERMS[object_type][oper]
return win_perm
def win_get_user_type(sid, sids):
"""Given object and SIDs, return user type."""
if sid == sids[OWNER]:
return OWNER
if sid == sids[GROUP]:
return GROUP
return OTHER
def win_get_object_sids(path):
"""Get the owner, group, other SIDs for an object."""
return [
win_get_owner_sid(path),
win_get_group_sid(path),
win_get_other_sid()
]
def win_get_permissions(path):
"""Get the file or dir permissions."""
if not os.path.exists(path):
raise FileNotFoundError('Path %s could not be found.' % path)
return _win_get_permissions(path, get_object_type(path))
def _get_basic_symbol_to_mode(symbol):
"""Calculate numeric value of set of 'rwx'."""
return ("r" in symbol and 1 << 2) | \
("w" in symbol and 1 << 1) | \
("x" in symbol and 1 << 0)
def _win_get_permissions(path, object_type):
"""Get the permissions."""
sec_des = win32security.GetNamedSecurityInfo(
path, win32security.SE_FILE_OBJECT,
win32security.DACL_SECURITY_INFORMATION)
dacl = sec_des.GetSecurityDescriptorDacl()
sids = win_get_object_sids(path)
mode = 0
for index in range(0, dacl.GetAceCount()):
ace = dacl.GetAce(index)
if ace[0][0] == win32security.ACCESS_ALLOWED_ACE_TYPE and \
win32security.LookupAccountSid(None, ace[2]) != \
SECURITY_NT_AUTHORITY:
# Not handling win32security.ACCESS_DENIED_ACE_TYPE
mode = mode | convert_win_to_stat(
ace[1],
win_get_user_type(ace[2], sids),
object_type)
return mode
def win_set_permissions(path, mode):
"""Set the file or dir permissions."""
if not os.path.exists(path):
raise FileNotFoundError('Path %s could not be found.' % path)
_win_set_permissions(path, mode, get_object_type(path))
def _win_set_permissions(path, mode, object_type):
"""Set the permissions."""
# Overview of Windows inheritance:
# Get/SetNamedSecurityInfo = Always includes inheritance
# Get/SetFileSecurity = Can exclude/disable inheritance
# Here we read effective permissions with GetNamedSecurityInfo, i.e.,
# including inherited permissions. However, we'll set permissions with
# SetFileSecurity and NO_INHERITANCE, to disable inheritance.
sec_des = win32security.GetNamedSecurityInfo(
path, win32security.SE_FILE_OBJECT,
win32security.DACL_SECURITY_INFORMATION)
dacl = sec_des.GetSecurityDescriptorDacl()
system_ace = None
for _ in range(0, dacl.GetAceCount()):
ace = dacl.GetAce(0)
try:
if ace[2] and ace[2].IsValid() and win32security.LookupAccountSid(
None, ace[2]) == SECURITY_NT_AUTHORITY:
system_ace = ace
except pywinerror:
print("Found orphaned SID:", ace[2])
dacl.DeleteAce(0)
if system_ace:
dacl.AddAccessAllowedAceEx(
dacl.GetAclRevision(),
win32security.NO_INHERITANCE, system_ace[1], system_ace[2])
sids = win_get_object_sids(path)
for user_type, sid in enumerate(sids):
win_perm = convert_stat_to_win(mode, user_type, object_type)
if win_perm > 0:
dacl.AddAccessAllowedAceEx(
dacl.GetAclRevision(),
win32security.NO_INHERITANCE, win_perm, sid)
sec_des.SetSecurityDescriptorDacl(1, dacl, 0)
win32security.SetFileSecurity(
path, win32security.DACL_SECURITY_INFORMATION, sec_des)
def print_win_inheritance(flags):
"""Display inheritance flags."""
print(" -Flags:", hex(flags))
if flags == win32security.NO_INHERITANCE:
print(" ", "NO_INHERITANCE")
else:
for i in WIN_INHERITANCE_TYPES:
if flags & getattr(win32security, i) == getattr(win32security, i):
print(" ", i)
def print_mode_permissions(mode):
"""Print component permissions in a stat mode."""
print("Mode:", oct(mode), "(Decimal: " + str(mode) + ")")
for i in STAT_KEYS:
if mode & getattr(stat, i) == getattr(stat, i):
print(" stat." + i)
def print_win_ace_type(ace_type):
"""Print ACE type."""
print(" -Type:")
for i in WIN_ACE_TYPES:
if getattr(ntsecuritycon, i) == ace_type:
print(" ", i)
def print_win_permissions(win_perm, flags, object_type):
"""Print permissions from ACE information."""
print(" -Permissions Mask:", hex(win_perm), "(" + str(win_perm) + ")")
# files and directories do permissions differently
if object_type == FILE:
permissions = WIN_FILE_PERMISSIONS
else:
permissions = WIN_DIR_PERMISSIONS
# directories have ACE that is inherited by children within them
if flags & ntsecuritycon.OBJECT_INHERIT_ACE == \
ntsecuritycon.OBJECT_INHERIT_ACE and flags & \
ntsecuritycon.INHERIT_ONLY_ACE == \
ntsecuritycon.INHERIT_ONLY_ACE:
permissions = WIN_DIR_INHERIT_PERMISSIONS
calc_mask = 0 # see if we are printing all of the permissions
for i in permissions:
if getattr(ntsecuritycon, i) & win_perm == getattr(
ntsecuritycon, i):
calc_mask = calc_mask | getattr(ntsecuritycon, i)
print(" ", i)
print(" -Mask calculated from printed permissions:", hex(calc_mask))
def print_obj_info(path):
"""Prints object security permission info."""
if not os.path.exists(path):
print(path, "does not exist!")
raise FileNotFoundError('Path %s could not be found.' % path)
object_type = get_object_type(path)
print("----------------------------------------")
if object_type == FILE:
print("FILE:", path)
else:
print("DIRECTORY:", path)
print_mode_permissions(get_mode(path))
print("Owner:", get_owner(path))
print("Group:", get_group(path))
if IS_WINDOWS:
_print_win_obj_info(path)
def _print_win_obj_info(path):
"""Print windows object security info."""
# get ACEs
sec_descriptor = win32security.GetFileSecurity(
path, win32security.DACL_SECURITY_INFORMATION)
dacl = sec_descriptor.GetSecurityDescriptorDacl()
if dacl is None:
print("No Discretionary ACL")
return
for ace_no in range(0, dacl.GetAceCount()):
ace = dacl.GetAce(ace_no)
print("ACE", ace_no)
print(' -SID:', win32security.LookupAccountSid(None, ace[2]))
print_win_ace_type(ace[0][0])
print_win_inheritance(ace[0][1])
print_win_permissions(ace[1], ace[0][1], get_object_type(path))
def perm_test(mode=stat.S_IRUSR | stat.S_IWUSR):
"""Creates test file and modifies permissions."""
path = ''.join(
random.choice(string.ascii_letters) for i in range(10)) + '.txt'
file_hdl = open(path, 'w+')
file_hdl.write("new file")
file_hdl.close()
print("Created test file:", path)
print("BEFORE Permissions:")
print_obj_info(path)
print("Setting permissions:")
print_mode_permissions(mode)
set_mode(path, mode)
print("AFTER Permissions:")
print_obj_info(path)
|
{"/tests/test_oschmod.py": ["/oschmod/__init__.py"], "/oschmod/cli.py": ["/oschmod/__init__.py"]}
|
32,738
|
zapplecat/oschmod
|
refs/heads/main
|
/tests/test_oschmod.py
|
# -*- coding: utf-8 -*-
# pylint: disable=redefined-outer-name
"""test_oschmod module."""
import glob
import os
import random
import shutil
import stat
import string
import time
from random import randrange
import oschmod
def test_permissions():
"""Tests for stuff."""
test_dir = "tests"
path = os.path.join(test_dir, ''.join(
random.choice(string.ascii_letters) for i in range(10)) + '.txt')
file_hdl = open(path, 'w+')
file_hdl.write(path)
file_hdl.close()
oschmod.set_mode(path, stat.S_IRUSR | stat.S_IWUSR)
assert oschmod.get_mode(path) == stat.S_IRUSR | stat.S_IWUSR
path = os.path.join(test_dir, ''.join(
random.choice(string.ascii_letters) for i in range(10)) + '.txt')
file_hdl = open(path, 'w+')
file_hdl.write(path)
file_hdl.close()
mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | \
stat.S_IWGRP | stat.S_IROTH | stat.S_IWOTH
oschmod.set_mode(path, mode)
assert oschmod.get_mode(path) == mode
path = os.path.join(test_dir, ''.join(
random.choice(string.ascii_letters) for i in range(10)) + '.txt')
file_hdl = open(path, 'w+')
file_hdl.write(path)
file_hdl.close()
mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | \
stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IWOTH | \
stat.S_IXOTH
oschmod.set_mode(path, mode)
assert oschmod.get_mode(path) == mode
file_list = glob.glob(os.path.join(test_dir, "*txt"))
for file_path in file_list:
try:
os.remove(file_path)
except FileNotFoundError:
print("Error while deleting file : ", file_path)
def test_set_recursive():
"""Check file permissions are recursively set."""
# create dirs
topdir = 'testdir1'
testdir = os.path.join(topdir, 'testdir2', 'testdir3')
os.makedirs(testdir)
# create files
fileh = open(os.path.join(topdir, 'file1'), "w+")
fileh.write("contents")
fileh.close()
fileh = open(os.path.join(testdir, 'file2'), "w+")
fileh.write("contents")
fileh.close()
# set permissions to badness
triple7 = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP\
| stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IWOTH\
| stat.S_IXOTH
oschmod.set_mode(topdir, triple7)
oschmod.set_mode(testdir, triple7)
oschmod.set_mode(os.path.join(topdir, 'file1'), triple7)
oschmod.set_mode(os.path.join(testdir, 'file2'), triple7)
time.sleep(1) # modes aren't always ready to go immediately
# set permissions - the test
file_mode = 0o600
dir_mode = 0o700
oschmod.set_mode_recursive(topdir, file_mode, dir_mode)
time.sleep(1) # modes aren't always ready to go immediately
mode_dir1 = oschmod.get_mode(topdir)
mode_dir2 = oschmod.get_mode(os.path.join(topdir, 'testdir2'))
mode_dir3 = oschmod.get_mode(testdir)
mode_file1 = oschmod.get_mode(os.path.join(topdir, 'file1'))
mode_file2 = oschmod.get_mode(os.path.join(testdir, 'file2'))
# clean up
shutil.rmtree(topdir)
# check it out
assert mode_dir1 == dir_mode
assert mode_dir2 == dir_mode
assert mode_dir3 == dir_mode
assert mode_file1 == file_mode
assert mode_file2 == file_mode
def test_symbolic_effective_add():
"""Check calculation of effective mode from symbolic."""
assert oschmod.get_effective_mode(0b111000000, "g+x") == 0b111001000
assert oschmod.get_effective_mode(0b111000000, "o+x") == 0b111000001
assert oschmod.get_effective_mode(0b111000000, "u+x") == 0b111000000
assert oschmod.get_effective_mode(0b111000000, "+x") == 0b111001001
assert oschmod.get_effective_mode(0b111000000, "ugo+x") == 0b111001001
assert oschmod.get_effective_mode(0b111000000, "a+x") == 0b111001001
assert oschmod.get_effective_mode(0b111000000, "g+wx") == 0b111011000
assert oschmod.get_effective_mode(0b111000000, "o+wx") == 0b111000011
assert oschmod.get_effective_mode(0b111000000, "u+wx") == 0b111000000
assert oschmod.get_effective_mode(0b111000000, "+wx") == 0b111011011
assert oschmod.get_effective_mode(0b111000000, "a+wx") == 0b111011011
assert oschmod.get_effective_mode(0b111000000, "g+rwx") == 0b111111000
assert oschmod.get_effective_mode(0b111000000, "o+rwx") == 0b111000111
assert oschmod.get_effective_mode(0b111000000, "u+rwx") == 0b111000000
assert oschmod.get_effective_mode(0b111000000, "+rwx") == 0b111111111
assert oschmod.get_effective_mode(0b111000000, "a+rwx") == 0b111111111
# randomly chosen starting permission = 394
assert oschmod.get_effective_mode(0b110001010, "g+x") == 0b110001010
assert oschmod.get_effective_mode(0b110001010, "o+x") == 0b110001011
assert oschmod.get_effective_mode(0b110001010, "u+x") == 0b111001010
assert oschmod.get_effective_mode(0b110001010, "+x") == 0b111001011
assert oschmod.get_effective_mode(0b110001010, "ugo+x") == 0b111001011
assert oschmod.get_effective_mode(0b110001010, "a+x") == 0b111001011
assert oschmod.get_effective_mode(0b110001010, "g+wx") == 0b110011010
assert oschmod.get_effective_mode(0b110001010, "o+wx") == 0b110001011
assert oschmod.get_effective_mode(0b110001010, "u+wx") == 0b111001010
assert oschmod.get_effective_mode(0b110001010, "+wx") == 0b111011011
assert oschmod.get_effective_mode(0b110001010, "a+wx") == 0b111011011
assert oschmod.get_effective_mode(0b110001010, "g+rwx") == 0b110111010
assert oschmod.get_effective_mode(0b110001010, "o+rwx") == 0b110001111
assert oschmod.get_effective_mode(0b110001010, "u+rwx") == 0b111001010
assert oschmod.get_effective_mode(0b110001010, "+rwx") == 0b111111111
assert oschmod.get_effective_mode(0b110001010, "a+rwx") == 0b111111111
def test_symbolic_effective_add2():
"""Check calculation of effective mode from symbolic."""
# randomly chosen starting permission = 53
assert oschmod.get_effective_mode(0b000110101, "g+x") == 0b000111101
assert oschmod.get_effective_mode(0b000110101, "o+x") == 0b000110101
assert oschmod.get_effective_mode(0b000110101, "u+x") == 0b001110101
assert oschmod.get_effective_mode(0b000110101, "+x") == 0b001111101
assert oschmod.get_effective_mode(0b000110101, "ugo+x") == 0b001111101
assert oschmod.get_effective_mode(0b000110101, "a+x") == 0b001111101
assert oschmod.get_effective_mode(0b000110101, "g+wx") == 0b000111101
assert oschmod.get_effective_mode(0b000110101, "o+wx") == 0b000110111
assert oschmod.get_effective_mode(0b000110101, "u+wx") == 0b011110101
assert oschmod.get_effective_mode(0b000110101, "+wx") == 0b011111111
assert oschmod.get_effective_mode(0b000110101, "a+wx") == 0b011111111
assert oschmod.get_effective_mode(0b000110101, "g+rwx") == 0b000111101
assert oschmod.get_effective_mode(0b000110101, "o+rwx") == 0b000110111
assert oschmod.get_effective_mode(0b000110101, "u+rwx") == 0b111110101
# randomly chosen starting permission = 372
assert oschmod.get_effective_mode(0b101110100, "g+x") == 0b101111100
assert oschmod.get_effective_mode(0b101110100, "o+x") == 0b101110101
assert oschmod.get_effective_mode(0b101110100, "u+x") == 0b101110100
assert oschmod.get_effective_mode(0b101110100, "+x") == 0b101111101
assert oschmod.get_effective_mode(0b101110100, "ugo+x") == 0b101111101
assert oschmod.get_effective_mode(0b101110100, "a+x") == 0b101111101
assert oschmod.get_effective_mode(0b101110100, "g+rx") == 0b101111100
assert oschmod.get_effective_mode(0b101110100, "o+rx") == 0b101110101
assert oschmod.get_effective_mode(0b101110100, "u+rx") == 0b101110100
assert oschmod.get_effective_mode(0b101110100, "+rx") == 0b101111101
assert oschmod.get_effective_mode(0b101110100, "a+rx") == 0b101111101
assert oschmod.get_effective_mode(0b101110100, "g+rwx") == 0b101111100
assert oschmod.get_effective_mode(0b101110100, "o+rwx") == 0b101110111
assert oschmod.get_effective_mode(0b101110100, "u+rwx") == 0b111110100
# randomly chosen starting permission = 501
assert oschmod.get_effective_mode(0b111110101, "g+x") == 0b111111101
assert oschmod.get_effective_mode(0b111110101, "o+x") == 0b111110101
assert oschmod.get_effective_mode(0b111110101, "u+x") == 0b111110101
assert oschmod.get_effective_mode(0b111110101, "+x") == 0b111111101
assert oschmod.get_effective_mode(0b111110101, "ugo+x") == 0b111111101
assert oschmod.get_effective_mode(0b111110101, "a+x") == 0b111111101
assert oschmod.get_effective_mode(0b111110101, "g+rw") == 0b111110101
assert oschmod.get_effective_mode(0b111110101, "o+rw") == 0b111110111
assert oschmod.get_effective_mode(0b111110101, "u+rw") == 0b111110101
assert oschmod.get_effective_mode(0b111110101, "+rw") == 0b111110111
assert oschmod.get_effective_mode(0b111110101, "a+rw") == 0b111110111
assert oschmod.get_effective_mode(0b111110101, "g+rwx") == 0b111111101
assert oschmod.get_effective_mode(0b111110101, "o+rwx") == 0b111110111
assert oschmod.get_effective_mode(0b111110101, "u+rwx") == 0b111110101
def test_symbolic_effective_sub():
"""Check calculation of effective mode from symbolic."""
# randomly chosen starting permission = 328
assert oschmod.get_effective_mode(0b101001000, "g-x") == 0b101000000
assert oschmod.get_effective_mode(0b101001000, "o-x") == 0b101001000
assert oschmod.get_effective_mode(0b101001000, "u-x") == 0b100001000
assert oschmod.get_effective_mode(0b101001000, "uo-x") == 0b100001000
assert oschmod.get_effective_mode(0b101001000, "-x") == 0b100000000
assert oschmod.get_effective_mode(0b101001000, "ugo-x") == 0b100000000
assert oschmod.get_effective_mode(0b101001000, "a-x") == 0b100000000
# randomly chosen starting permission = 256
assert oschmod.get_effective_mode(0b100000000, "g-r") == 0b100000000
assert oschmod.get_effective_mode(0b100000000, "o-r") == 0b100000000
assert oschmod.get_effective_mode(0b100000000, "u-r") == 0b000000000
assert oschmod.get_effective_mode(0b100000000, "uo-r") == 0b000000000
assert oschmod.get_effective_mode(0b100000000, "-r") == 0b000000000
assert oschmod.get_effective_mode(0b100000000, "ugo-r") == 0b000000000
assert oschmod.get_effective_mode(0b100000000, "a-r") == 0b000000000
# randomly chosen starting permission = 166
assert oschmod.get_effective_mode(0b010100110, "g-x") == 0b010100110
assert oschmod.get_effective_mode(0b010100110, "o-w") == 0b010100100
assert oschmod.get_effective_mode(0b010100110, "u-rw") == 0b000100110
assert oschmod.get_effective_mode(0b010100110, "uo-rw") == 0b000100000
assert oschmod.get_effective_mode(0b010100110, "-wx") == 0b000100100
assert oschmod.get_effective_mode(0b010100110, "ugo-rwx") == 0b000000000
assert oschmod.get_effective_mode(0b010100110, "a-r") == 0b010000010
# randomly chosen starting permission = 174
assert oschmod.get_effective_mode(0b010101110, "ug-w") == 0b000101110
assert oschmod.get_effective_mode(0b010101110, "u-r") == 0b010101110
assert oschmod.get_effective_mode(0b010101110, "u-rx") == 0b010101110
assert oschmod.get_effective_mode(0b010101110, "ug-rwx") == 0b000000110
assert oschmod.get_effective_mode(0b010101110, "g-rx") == 0b010000110
assert oschmod.get_effective_mode(0b010101110, "go-rw") == 0b010001000
assert oschmod.get_effective_mode(0b010101110, "ug-x") == 0b010100110
def test_symbolic_effective_eq():
"""Check calculation of effective mode from symbolic."""
# randomly chosen starting permission = 494
assert oschmod.get_effective_mode(0b111101110, "go=rx") == 0b111101101
assert oschmod.get_effective_mode(0b111101110, "=r") == 0b100100100
assert oschmod.get_effective_mode(0b111101110, "ugo=rw") == 0b110110110
assert oschmod.get_effective_mode(0b111101110, "ugo=rx") == 0b101101101
assert oschmod.get_effective_mode(0b111101110, "uo=r") == 0b100101100
assert oschmod.get_effective_mode(0b111101110, "o=rw") == 0b111101110
assert oschmod.get_effective_mode(0b111101110, "=x") == 0b001001001
# randomly chosen starting permission = 417
assert oschmod.get_effective_mode(0b110100001, "ugo=x") == 0b001001001
assert oschmod.get_effective_mode(0b110100001, "ug=rw") == 0b110110001
assert oschmod.get_effective_mode(0b110100001, "ugo=rw") == 0b110110110
assert oschmod.get_effective_mode(0b110100001, "u=wx") == 0b011100001
assert oschmod.get_effective_mode(0b110100001, "=rx") == 0b101101101
assert oschmod.get_effective_mode(0b110100001, "u=r") == 0b100100001
assert oschmod.get_effective_mode(0b110100001, "uo=wx") == 0b011100011
# randomly chosen starting permission = 359
assert oschmod.get_effective_mode(0b101100111, "go=") == 0b101000000
assert oschmod.get_effective_mode(0b101100111, "ugo=") == 0b000000000
assert oschmod.get_effective_mode(0b101100111, "ugo=rwx") == 0b111111111
assert oschmod.get_effective_mode(0b101100111, "uo=w") == 0b010100010
assert oschmod.get_effective_mode(0b101100111, "=w") == 0b010010010
assert oschmod.get_effective_mode(0b101100111, "uo=wx") == 0b011100011
assert oschmod.get_effective_mode(0b101100111, "u=r") == 0b100100111
def generate_symbolic():
"""Generate one symbolic representation of a mode modifier."""
who = randrange(8)
whom = ((who & 0b100 > 0 and "u") or "") + \
((who & 0b010 > 0 and "g") or "") + \
((who & 0b001 > 0 and "o") or "")
oper = randrange(3)
operation = ((oper == 0 and "+") or "") + \
((oper == 1 and "-") or "") + \
((oper == 2 and "=") or "")
perm = randrange(8)
perms = ((perm & 0b100 > 0 and "r") or "") + \
((perm & 0b010 > 0 and "w") or "") + \
((perm & 0b001 > 0 and "x") or "")
return whom + operation + perms
def generate_case(prefix, suffix):
"""Generate a test case to be solved manually."""
symbolic = [generate_symbolic() for _ in range(randrange(1, 4))]
symbolics = ",".join(symbolic)
return "{0:s}0b{1:09b}, \"{2:s}\"{3:s} == 0b{1:09b}".format(
prefix,
randrange(512),
symbolics,
suffix
)
def generate_cases(count):
"""Generate test cases to be solved manually and added to tests."""
prefix = "assert oschmod.get_effective_mode("
suffix = ")"
cases = [generate_case(prefix, suffix) for _ in range(count)]
print("\n".join(cases))
def test_symbolic_multiples():
"""Check calculation of effective mode from symbolic."""
assert oschmod.get_effective_mode(0b000101010, "g-rwx,go=") == 0b000000000
assert oschmod.get_effective_mode(0b011001011, "uo-wx,u=x") == 0b001001000
assert oschmod.get_effective_mode(0b111101000, "u=rwx,o=x") == 0b111101001
assert oschmod.get_effective_mode(0b110101001, "+r,ug=rx") == 0b101101101
assert oschmod.get_effective_mode(
0b010010000, "go-,go+,u+rw") == 0b110010000
assert oschmod.get_effective_mode(0b000101110, "ug-rw,go=x") == 0b000001001
assert oschmod.get_effective_mode(
0b010110000, "=rwx,=rw,ug-") == 0b110110110
assert oschmod.get_effective_mode(
0b010001111, "o-rwx,o=rwx,ug-x") == 0b010000111
assert oschmod.get_effective_mode(
0b100111011, "u-r,o=rwx,ug-wx") == 0b000100111
assert oschmod.get_effective_mode(
0b111110101, "o=rwx,ugo-,g=rx") == 0b111101111
assert oschmod.get_effective_mode(0b010010000, "u=rx") == 0b101010000
assert oschmod.get_effective_mode(0b001011111, "=") == 0b000000000
assert oschmod.get_effective_mode(0b100011010, "ug-w,uo=rw") == 0b110001110
assert oschmod.get_effective_mode(0b111001001, "ug=rw,g-wx") == 0b110100001
assert oschmod.get_effective_mode(
0b111000000, "u-,uo+rx,go+x") == 0b111001101
assert oschmod.get_effective_mode(0b000000000, "u=rx,uo-x") == 0b100000000
assert oschmod.get_effective_mode(0b101110101, "uo=rx") == 0b101110101
assert oschmod.get_effective_mode(
0b111111010, "g-wx,ug=,-x") == 0b000000010
assert oschmod.get_effective_mode(0b100011000, "uo+rw") == 0b110011110
assert oschmod.get_effective_mode(
0b011111000, "ugo+,uo+w,-rwx") == 0b000000000
assert oschmod.get_effective_mode(
0b000010100, "ug=x,ug=x,g-rx") == 0b001000100
assert oschmod.get_effective_mode(0b110101101, "g=rwx") == 0b110111101
assert oschmod.get_effective_mode(0b000010111, "=wx") == 0b011011011
assert oschmod.get_effective_mode(
0b000111011, "u-rw,uo-x,o+wx") == 0b000111011
assert oschmod.get_effective_mode(0b010110000, "uo+,u+") == 0b010110000
assert oschmod.get_effective_mode(
0b000111110, "go=x,ug+x,uo=rx") == 0b101001101
assert oschmod.get_effective_mode(0b011101111, "o+wx") == 0b011101111
assert oschmod.get_effective_mode(
0b001001011, "u-,go+w,ugo=w") == 0b010010010
assert oschmod.get_effective_mode(0b110110100, "u=w,=x") == 0b001001001
assert oschmod.get_effective_mode(
0b110011100, "u=w,ug-rwx,uo+rwx") == 0b111000111
assert oschmod.get_effective_mode(0b100101001, "go-r") == 0b100001001
assert oschmod.get_effective_mode(
0b110100110, "uo=r,ug+rx,ugo=") == 0b000000000
assert oschmod.get_effective_mode(0b101100000, "go=wx,o-") == 0b101011011
assert oschmod.get_effective_mode(0b111111101, "-r,o=r,o-w") == 0b011011100
assert oschmod.get_effective_mode(0b110101000, "uo-rx,+rwx") == 0b111111111
assert oschmod.get_effective_mode(0b101011111, "go=wx") == 0b101011011
assert oschmod.get_effective_mode(
0b110110010, "go+x,ugo-w,u+rwx") == 0b111101001
assert oschmod.get_effective_mode(0b001100101, "=rx,-rwx") == 0b000000000
assert oschmod.get_effective_mode(0b001010011, "uo=x") == 0b001010001
assert oschmod.get_effective_mode(
0b011101110, "ugo-rx,uo+rw,uo-rw") == 0b000000000
def test_symbolic_use():
"""Check file permissions are recursively set."""
# create dirs
topdir = 'testdir1'
testdir = os.path.join(topdir, 'testdir2', 'testdir3')
os.makedirs(testdir)
# create files
fileh = open(os.path.join(topdir, 'file1'), "w+")
fileh.write("contents")
fileh.close()
fileh = open(os.path.join(testdir, 'file2'), "w+")
fileh.write("contents")
fileh.close()
# set permissions to badness
triple7 = "+rwx"
oschmod.set_mode(topdir, triple7)
oschmod.set_mode(testdir, triple7)
oschmod.set_mode(os.path.join(topdir, 'file1'), triple7)
oschmod.set_mode(os.path.join(testdir, 'file2'), triple7)
time.sleep(1) # modes aren't always ready to go immediately
# set permissions - the test
oschmod.set_mode_recursive(topdir, "u=rw,go=", "u=rwx,go=")
time.sleep(1) # modes aren't always ready to go immediately
dir_mode = 0o700
file_mode = 0o600
mode_dir1 = oschmod.get_mode(topdir)
mode_dir2 = oschmod.get_mode(os.path.join(topdir, 'testdir2'))
mode_dir3 = oschmod.get_mode(testdir)
mode_file1 = oschmod.get_mode(os.path.join(topdir, 'file1'))
mode_file2 = oschmod.get_mode(os.path.join(testdir, 'file2'))
# clean up
shutil.rmtree(topdir)
# check it out
assert mode_dir1 == dir_mode
assert mode_dir2 == dir_mode
assert mode_dir3 == dir_mode
assert mode_file1 == file_mode
assert mode_file2 == file_mode
|
{"/tests/test_oschmod.py": ["/oschmod/__init__.py"], "/oschmod/cli.py": ["/oschmod/__init__.py"]}
|
32,739
|
zapplecat/oschmod
|
refs/heads/main
|
/oschmod/cli.py
|
# -*- coding: utf-8 -*-
"""pyppyn cli."""
from __future__ import (absolute_import, division, print_function,
unicode_literals, with_statement)
import argparse
import oschmod
def main():
"""Provide main function for CLI."""
parser = argparse.ArgumentParser(
description='Change the mode (permissions) of a file or directory')
parser.add_argument('-R', action='store_true',
help='apply mode recursively')
parser.add_argument(
'mode', nargs=1, help='octal or symbolic mode of the object')
parser.add_argument('object', nargs=1, help='file or directory')
args = parser.parse_args()
mode = args.mode[0]
obj = args.object[0]
if args.R:
oschmod.set_mode_recursive(obj, mode)
else:
oschmod.set_mode(obj, mode)
|
{"/tests/test_oschmod.py": ["/oschmod/__init__.py"], "/oschmod/cli.py": ["/oschmod/__init__.py"]}
|
32,746
|
milesizzo/prompt
|
refs/heads/master
|
/example/world.py
|
from commands import CommandProcessor
def enum(**enums):
return type('Enum', (), enums)
Direction = enum(North=1, East=2, South=3, West=4)
class World(CommandProcessor):
def __init__(self, scene):
self.scene = scene
self.time = 0
def processCommand(self, command):
result = self.scene.processCommand(command)
if isinstance(result, tuple):
scene, result = result
self.scene = scene
return result
class Scene:
def __init__(self, description):
self.description = description
self.directions = {Direction.North: None, Direction.East: None, Direction.South: None, Direction.West: None}
def connect(self, direction, scene):
opposite = {
Direction.North: Direction.South,
Direction.East: Direction.West,
Direction.South: Direction.North,
Direction.West: Direction.East
}[direction]
if scene.directions[opposite] is not None:
raise Exception("Invalid scene placement")
scene.directions[opposite] = self
self.directions[direction] = scene
def walk(self, direction):
if direction in self.directions:
return self.directions[direction]
return None
def _directionStr(self, direction):
return {
Direction.North: "North",
Direction.East: "East",
Direction.South: "South",
Direction.West: "West"
}[direction]
def _strDirection(self, directionStr):
return {
"north": Direction.North,
"east": Direction.East,
"south": Direction.South,
"west": Direction.West
}[directionStr]
def processCommand(self, command):
if command == "look":
return self.on_look()
if command in {"north", "south", "east", "west"}:
return self.on_move(self._strDirection(command))
def on_look(self):
directions = [self._directionStr(key) for key, value in self.directions.iteritems() if value is not None]
if directions:
return "%s Directions you can move are: %s" % (self.description, ", ".join(directions))
return "%s You are stuck!" % self.description
def on_move(self, direction):
if self.directions[direction] is None:
return "You cannot move in that direction."
scene = self.walk(direction)
return scene, scene.on_look()
if __name__ == "__main__":
street = Scene("You are on the street in front of your home.")
home = Scene("You are at home.")
home.connect(Direction.North, street)
world = World(home)
print world.scene.on_look()
print street.on_look()
|
{"/example/gameserver.py": ["/prompt.py"], "/example/game1.py": ["/prompt.py"]}
|
32,747
|
milesizzo/prompt
|
refs/heads/master
|
/example/gameserver.py
|
from SimpleWebSocketServer import SimpleWebSocketServer
from prompt import PromptServer
class GameServer(PromptServer):
def makeCommandProcessor(self):
return self.makeGame()
def makeGame(self):
raise NotImplementedError
|
{"/example/gameserver.py": ["/prompt.py"], "/example/game1.py": ["/prompt.py"]}
|
32,748
|
milesizzo/prompt
|
refs/heads/master
|
/example/game1.py
|
from world import World, Scene, Direction
import gameserver
import prompt
class Game1Server(gameserver.GameServer):
def makeGame(self):
street = Scene("You are on the street in front of your home.")
home = Scene("You are at home.")
home.connect(Direction.North, street)
return World(home)
if __name__ == "__main__":
prompt.run(Game1Server)
|
{"/example/gameserver.py": ["/prompt.py"], "/example/game1.py": ["/prompt.py"]}
|
32,749
|
milesizzo/prompt
|
refs/heads/master
|
/commands.py
|
class CommandProcessor:
def __init__(self):
pass
def processCommand(self, command):
raise NotImplementedError
|
{"/example/gameserver.py": ["/prompt.py"], "/example/game1.py": ["/prompt.py"]}
|
32,750
|
milesizzo/prompt
|
refs/heads/master
|
/prompt.py
|
import json
from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer, SimpleSSLWebSocketServer
clients = set()
authenticated = set()
class PromptServer(WebSocket):
def handleMessage(self):
print "%s: %s" % (self.formatAddress(), self.data)
data = self.processor.processCommand(self.data)
if data is None:
data = "Invalid command: \"%s\"" % self.data
print "%s replying" % self.formatAddress()
self.sendMessage(unicode(data))
def handleConnected(self):
clients.add(self)
self.processor = self.makeCommandProcessor()
print "%s connected (%d total)" % (self.formatAddress(), len(clients))
def handleClose(self):
clients.discard(self)
authenticated.discard(self)
self.processor = None
print "%s disconnected (%d still connected)" % (self.formatAddress(), len(clients))
def formatAddress(self):
return "[%s:%d]" % self.address
def makeCommandProcessor(self):
raise NotImplementedError
def printState(self):
print 'clients connected:'
for client in clients:
print client.formatAddress()
def run(serverType, port=5167):
print "Starting server (port %d)" % port
server = SimpleWebSocketServer('', port, serverType)
server.serveforever()
|
{"/example/gameserver.py": ["/prompt.py"], "/example/game1.py": ["/prompt.py"]}
|
32,752
|
PucheKrunch/MexBank
|
refs/heads/main
|
/app/website/forms.py
|
from django import forms
from .models import Empleado,Cliente,C_tarjeta,D_tarjeta
class EmpleadoForm(forms.ModelForm):
class Meta:
model = Empleado
fields = ["name","l_names","superior_id","sex","b_date"]
class ClienteForm(forms.ModelForm):
class Meta:
model = Cliente
fields = ["name","l_names","works_with","sex","b_date","ct_id","dt_id"]
class D_tarjetaForm(forms.ModelForm):
class Meta:
model = D_tarjeta
fields = ["num_tarjeta","balance","fecha_valida","cliente_id"]
class C_tarjetaForm(forms.ModelForm):
class Meta:
model = C_tarjeta
fields = ["num_tarjeta","credito","c_disponible","saldo","dia_corte","fecha_valida","cliente_id"]
class del_objectForm(forms.Form):
object_id = forms.IntegerField()
class up_employeeForm(forms.ModelForm):
object_id = forms.IntegerField()
class Meta:
model = Empleado
fields = ["name","l_names","superior_id","sex","b_date"]
class up_clientForm(forms.ModelForm):
object_id = forms.IntegerField()
class Meta:
model = Cliente
fields = ["name","l_names","works_with","sex","b_date","ct_id","dt_id"]
class up_cardForm(forms.ModelForm):
object_id = forms.IntegerField()
class Meta:
model = D_tarjeta
fields = ["num_tarjeta","balance","fecha_valida","cliente_id"]
class up_ccardForm(forms.ModelForm):
object_id = forms.IntegerField()
class Meta:
model = C_tarjeta
fields = ["num_tarjeta","credito","c_disponible","saldo","dia_corte","fecha_valida","cliente_id"]
|
{"/app/website/forms.py": ["/app/website/models.py"], "/app/website/views.py": ["/app/website/models.py", "/app/website/forms.py"], "/app/website/admin.py": ["/app/website/models.py"]}
|
32,753
|
PucheKrunch/MexBank
|
refs/heads/main
|
/app/website/migrations/0007_auto_20210602_1221.py
|
# Generated by Django 3.2.3 on 2021-06-02 17:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0006_auto_20210602_0152'),
]
operations = [
migrations.RenameField(
model_name='cliente',
old_name='emp_id',
new_name='works_with',
),
migrations.AddField(
model_name='cliente',
name='b_date',
field=models.DateField(null=True),
),
]
|
{"/app/website/forms.py": ["/app/website/models.py"], "/app/website/views.py": ["/app/website/models.py", "/app/website/forms.py"], "/app/website/admin.py": ["/app/website/models.py"]}
|
32,754
|
PucheKrunch/MexBank
|
refs/heads/main
|
/app/website/migrations/0005_auto_20210602_0129.py
|
# Generated by Django 3.2.3 on 2021-06-02 06:29
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('website', '0004_auto_20210601_2354'),
]
operations = [
migrations.CreateModel(
name='C_tarjeta',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('credito', models.FloatField()),
('c_disponible', models.FloatField()),
('saldo', models.FloatField()),
('dia_corte', models.IntegerField()),
('fecha_valida', models.DateField()),
],
),
migrations.CreateModel(
name='D_tarjeta',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('balance', models.FloatField()),
('fecha_valida', models.DateField()),
],
),
migrations.AlterField(
model_name='empleado',
name='superior_id',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='website.empleado'),
),
migrations.CreateModel(
name='Cliente',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('l_names', models.CharField(max_length=100)),
('sex', models.CharField(choices=[('H', 'Hombre'), ('M', 'Mujer'), ('O', 'Otro')], max_length=1)),
('ct_id', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='website.c_tarjeta')),
('dt_id', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='website.d_tarjeta')),
('emp_id', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='website.empleado')),
],
),
]
|
{"/app/website/forms.py": ["/app/website/models.py"], "/app/website/views.py": ["/app/website/models.py", "/app/website/forms.py"], "/app/website/admin.py": ["/app/website/models.py"]}
|
32,755
|
PucheKrunch/MexBank
|
refs/heads/main
|
/app/website/models.py
|
from django.db import models
# Create your models here.
class Empleado(models.Model):
sex_choices = (
('H','Hombre'),
('M','Mujer'),
('O','Otro'),
)
name = models.CharField(max_length=50)
l_names = models.CharField(max_length=100)
superior_id = models.ForeignKey("self",on_delete=models.SET_NULL,null=True,blank=True)
sex = models.CharField(max_length=1,choices=sex_choices)
b_date = models.DateField()
def __str__(self):
return self.name + " " + self.l_names
class Cliente(models.Model):
sex_choices = (
('H','Hombre'),
('M','Mujer'),
('O','Otro'),
)
name = models.CharField(max_length=50)
l_names = models.CharField(max_length=100)
works_with = models.ForeignKey("Empleado",on_delete=models.SET_NULL,null=True)
sex = models.CharField(max_length=1,choices=sex_choices)
b_date = models.DateField(null=True)
ct_id = models.ForeignKey("C_tarjeta",on_delete=models.SET_NULL,null=True,blank=True)
dt_id = models.ForeignKey("D_tarjeta",on_delete=models.SET_NULL,null=True,blank=True)
def __str__(self):
return self.name + " " + self.l_names
class C_tarjeta(models.Model):
num_tarjeta = models.CharField(max_length=16,null=True,blank=True)
credito = models.FloatField()
c_disponible = models.FloatField(null=True,blank=True)
saldo = models.FloatField(default=0,null=True,blank=True)
dia_corte = models.IntegerField(null=True,blank=True)
fecha_valida = models.DateField(null=True,blank=True)
cliente_id = models.ForeignKey("Cliente",on_delete=models.CASCADE,null=True,blank=True)
def __str__(self):
number = str(self.num_tarjeta)
return number[0:4] + '-' + number[4:8] + '-' + number[8:12] + '-' + number[12:]
class D_tarjeta(models.Model):
num_tarjeta = models.CharField(max_length=16,null=True,blank=True)
balance = models.FloatField()
fecha_valida = models.DateField(null=True,blank=True)
cliente_id = models.ForeignKey("Cliente",on_delete=models.CASCADE,null=True,blank=True)
def __str__(self):
number = str(self.num_tarjeta)
return number[0:4] + '-' + number[4:8] + '-' + number[8:12] + '-' + number[12:]
|
{"/app/website/forms.py": ["/app/website/models.py"], "/app/website/views.py": ["/app/website/models.py", "/app/website/forms.py"], "/app/website/admin.py": ["/app/website/models.py"]}
|
32,756
|
PucheKrunch/MexBank
|
refs/heads/main
|
/app/website/urls.py
|
from django.urls import path
from . import views
urlpatterns = [
path('',views.home, name="home"),
path('employee',views.add_emp, name="employee"),
path('employees',views.render_emp, name="employees"),
path('client',views.add_client, name="client"),
path('clients',views.render_client, name="clients"),
path('card',views.add_card, name="card"),
path('cards',views.render_card, name="cards"),
path('ccard',views.add_ccard, name="ccard"),
path('ccards',views.render_ccard, name="ccards"),
path('del_employee',views.delete_emp, name="del_employee"),
path('del_client',views.delete_client, name="del_client"),
path('del_card',views.delete_card, name="del_card"),
path('del_ccard',views.delete_ccard, name="del_ccard"),
path('s_queries',views.s_queries,name="s_queries"),
path('c_queries',views.c_queries,name="c_queries"),
path('a_queries',views.a_queries,name="a_queries"),
path('up_employee',views.up_employee,name="up_employee"),
path('up_client',views.up_client,name="up_client"),
path('up_card',views.up_card,name="up_card"),
path('up_ccard',views.up_ccard,name="up_ccard"),
path('backup',views.backup,name="backup"),
]
|
{"/app/website/forms.py": ["/app/website/models.py"], "/app/website/views.py": ["/app/website/models.py", "/app/website/forms.py"], "/app/website/admin.py": ["/app/website/models.py"]}
|
32,757
|
PucheKrunch/MexBank
|
refs/heads/main
|
/app/website/migrations/0004_auto_20210601_2354.py
|
# Generated by Django 3.2.3 on 2021-06-02 04:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('website', '0003_rename_members_member'),
]
operations = [
migrations.CreateModel(
name='Empleado',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('l_names', models.CharField(max_length=100)),
('sex', models.CharField(choices=[('H', 'Hombre'), ('M', 'Mujer'), ('O', 'Otro')], max_length=1)),
('b_date', models.DateField()),
('superior_id', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='website.empleado')),
],
),
migrations.DeleteModel(
name='Member',
),
]
|
{"/app/website/forms.py": ["/app/website/models.py"], "/app/website/views.py": ["/app/website/models.py", "/app/website/forms.py"], "/app/website/admin.py": ["/app/website/models.py"]}
|
32,758
|
PucheKrunch/MexBank
|
refs/heads/main
|
/app/website/migrations/0006_auto_20210602_0152.py
|
# Generated by Django 3.2.3 on 2021-06-02 06:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('website', '0005_auto_20210602_0129'),
]
operations = [
migrations.AddField(
model_name='c_tarjeta',
name='cliente_id',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='website.cliente'),
),
migrations.AddField(
model_name='c_tarjeta',
name='num_tarjeta',
field=models.CharField(max_length=16, null=True),
),
migrations.AddField(
model_name='d_tarjeta',
name='cliente_id',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='website.cliente'),
),
migrations.AddField(
model_name='d_tarjeta',
name='num_tarjeta',
field=models.CharField(max_length=16, null=True),
),
]
|
{"/app/website/forms.py": ["/app/website/models.py"], "/app/website/views.py": ["/app/website/models.py", "/app/website/forms.py"], "/app/website/admin.py": ["/app/website/models.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.