index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
42,287,801
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/tests/media_app/migrations/0001_initial.py
|
# Generated by Django 1.11.24 on 2019-09-14 10:45
import django.db.models.deletion
from django.db import migrations, models
import djangocms_blog.media.base
class Migration(migrations.Migration):
initial = True
dependencies = [
("cms", "0020_old_tree_cleanup"),
]
operations = [
migrations.CreateModel(
name="Vimeo",
fields=[
(
"cmsplugin_ptr",
models.OneToOneField(
auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
parent_link=True,
primary_key=True,
related_name="media_app_vimeo",
serialize=False,
to="cms.CMSPlugin",
),
),
("url", models.URLField(verbose_name="Video URL")),
],
options={
"abstract": False,
},
bases=(djangocms_blog.media.base.MediaAttachmentPluginMixin, "cms.cmsplugin"),
),
migrations.CreateModel(
name="YoutTubeVideo",
fields=[
(
"cmsplugin_ptr",
models.OneToOneField(
auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
parent_link=True,
primary_key=True,
related_name="media_app_youttubevideo",
serialize=False,
to="cms.CMSPlugin",
),
),
("url", models.URLField(verbose_name="video URL")),
],
options={
"abstract": False,
},
bases=(djangocms_blog.media.base.MediaAttachmentPluginMixin, "cms.cmsplugin"),
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,802
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0007_auto_20150719_0933.py
|
import django.db.models.deletion
import django.utils.timezone
import djangocms_text_ckeditor.fields
import filer.fields.image
from django.conf import settings
from django.db import migrations, models
from filer.settings import FILER_IMAGE_MODEL
from djangocms_blog.models import thumbnail_model
ACTUAL_FILER_IMAGE_MODEL = FILER_IMAGE_MODEL or "filer.Image"
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0006_auto_20150214_1907"),
migrations.swappable_dependency(ACTUAL_FILER_IMAGE_MODEL),
("filer", "0003_thumbnailoption"),
]
operations = [
migrations.AlterModelOptions(
name="blogcategorytranslation",
options={"managed": True, "verbose_name": "blog category Translation", "default_permissions": ()},
),
migrations.AlterModelOptions(
name="posttranslation",
options={"managed": True, "verbose_name": "blog article Translation", "default_permissions": ()},
),
migrations.AlterField(
model_name="authorentriesplugin",
name="authors",
field=models.ManyToManyField(verbose_name="authors", to=settings.AUTH_USER_MODEL),
preserve_default=True,
),
migrations.AlterField(
model_name="authorentriesplugin",
name="latest_posts",
field=models.IntegerField(
help_text="The number of author articles to be displayed.", verbose_name="articles", default=5
),
preserve_default=True,
),
migrations.AlterField(
model_name="blogcategorytranslation",
name="language_code",
field=models.CharField(db_index=True, verbose_name="Language", max_length=15),
preserve_default=True,
),
migrations.AlterField(
model_name="latestpostsplugin",
name="categories",
field=models.ManyToManyField(
blank=True,
help_text="Show only the blog articles tagged with chosen categories.",
verbose_name="filter by category",
to="djangocms_blog.BlogCategory",
),
preserve_default=True,
),
migrations.AlterField(
model_name="latestpostsplugin",
name="latest_posts",
field=models.IntegerField(
help_text="The number of latests articles to be displayed.", verbose_name="articles", default=5
),
preserve_default=True,
),
migrations.AlterField(
model_name="latestpostsplugin",
name="tags",
field=models.ManyToManyField(
blank=True,
help_text="Show only the blog articles tagged with chosen tags.",
verbose_name="filter by tag",
to="taggit.Tag",
),
preserve_default=True,
),
migrations.AlterField(
model_name="post",
name="author",
field=models.ForeignKey(
blank=True,
verbose_name="author",
to=settings.AUTH_USER_MODEL,
related_name="djangocms_blog_post_author",
null=True,
on_delete=models.deletion.PROTECT,
),
preserve_default=True,
),
migrations.AlterField(
model_name="post",
name="date_created",
field=models.DateTimeField(auto_now_add=True, verbose_name="created"),
preserve_default=True,
),
migrations.AlterField(
model_name="post",
name="date_modified",
field=models.DateTimeField(auto_now=True, verbose_name="last modified"),
preserve_default=True,
),
migrations.AlterField(
model_name="post",
name="date_published",
field=models.DateTimeField(verbose_name="published Since", default=django.utils.timezone.now),
preserve_default=True,
),
migrations.AlterField(
model_name="post",
name="date_published_end",
field=models.DateTimeField(blank=True, verbose_name="published Until", null=True),
preserve_default=True,
),
migrations.AlterField(
model_name="post",
name="enable_comments",
field=models.BooleanField(verbose_name="enable comments on post", default=True),
preserve_default=True,
),
migrations.AlterField(
model_name="post",
name="main_image",
field=filer.fields.image.FilerImageField(
on_delete=django.db.models.deletion.SET_NULL,
blank=True,
verbose_name="main image",
to=ACTUAL_FILER_IMAGE_MODEL,
related_name="djangocms_blog_post_image",
null=True,
),
preserve_default=True,
),
migrations.AlterField(
model_name="post",
name="main_image_full",
field=models.ForeignKey(
on_delete=django.db.models.deletion.SET_NULL,
blank=True,
verbose_name="main image full",
to=thumbnail_model,
related_name="djangocms_blog_post_full",
null=True,
),
preserve_default=True,
),
migrations.AlterField(
model_name="post",
name="main_image_thumbnail",
field=models.ForeignKey(
on_delete=django.db.models.deletion.SET_NULL,
blank=True,
verbose_name="main image thumbnail",
to=thumbnail_model,
related_name="djangocms_blog_post_thumbnail",
null=True,
),
preserve_default=True,
),
migrations.AlterField(
model_name="post",
name="publish",
field=models.BooleanField(verbose_name="publish", default=False),
preserve_default=True,
),
migrations.AlterField(
model_name="posttranslation",
name="abstract",
field=djangocms_text_ckeditor.fields.HTMLField(verbose_name="abstract"),
preserve_default=True,
),
migrations.AlterField(
model_name="posttranslation",
name="language_code",
field=models.CharField(db_index=True, verbose_name="Language", max_length=15),
preserve_default=True,
),
migrations.AlterField(
model_name="posttranslation",
name="meta_description",
field=models.TextField(blank=True, verbose_name="post meta description", default=""),
preserve_default=True,
),
migrations.AlterField(
model_name="posttranslation",
name="meta_keywords",
field=models.TextField(blank=True, verbose_name="post meta keywords", default=""),
preserve_default=True,
),
migrations.AlterField(
model_name="posttranslation",
name="meta_title",
field=models.CharField(
blank=True,
help_text="used in title tag and social sharing",
verbose_name="post meta title",
max_length=255,
default="",
),
preserve_default=True,
),
migrations.AlterField(
model_name="posttranslation",
name="post_text",
field=djangocms_text_ckeditor.fields.HTMLField(blank=True, verbose_name="text", default=""),
preserve_default=True,
),
migrations.AlterField(
model_name="posttranslation",
name="title",
field=models.CharField(verbose_name="title", max_length=255),
preserve_default=True,
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,803
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0037_auto_20190806_0743.py
|
# Generated by Django 2.1.11 on 2019-08-06 05:43
import django.db.models.deletion
import parler.fields
import taggit_autosuggest.managers
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0036_auto_20180913_1809"),
]
operations = [
migrations.AlterField(
model_name="authorentriesplugin",
name="authors",
field=models.ManyToManyField(
limit_choices_to={"djangocms_blog_post_author__publish": True},
to=settings.AUTH_USER_MODEL,
verbose_name="authors",
),
),
migrations.AlterField(
model_name="blogcategorytranslation",
name="master",
field=parler.fields.TranslationsForeignKey(
editable=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="translations",
to="djangocms_blog.BlogCategory",
),
),
migrations.AlterField(
model_name="blogconfigtranslation",
name="master",
field=parler.fields.TranslationsForeignKey(
editable=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="translations",
to="djangocms_blog.BlogConfig",
),
),
migrations.AlterField(
model_name="latestpostsplugin",
name="tags",
field=taggit_autosuggest.managers.TaggableManager(
blank=True,
help_text="Show only the blog articles tagged with chosen tags.",
related_name="djangocms_blog_latest_post",
through="taggit.TaggedItem",
to="taggit.Tag",
verbose_name="filter by tag",
),
),
migrations.AlterField(
model_name="post",
name="tags",
field=taggit_autosuggest.managers.TaggableManager(
blank=True,
help_text="Type a tag and hit tab, or start typing and select from autocomplete list.",
related_name="djangocms_blog_tags",
through="taggit.TaggedItem",
to="taggit.Tag",
verbose_name="Tags",
),
),
migrations.AlterField(
model_name="posttranslation",
name="master",
field=parler.fields.TranslationsForeignKey(
editable=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="translations",
to="djangocms_blog.Post",
),
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,804
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/tests/test_utils/models.py
|
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
sites = models.ManyToManyField("sites.Site")
def get_sites(self):
return self.sites
from cms.models import PlaceholderField # noqa isort:skip
from djangocms_blog.models import Post # noqa isort:skip
class PostExtension(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="extension")
some_field = models.CharField(max_length=10)
class PostPlaceholderExtension(models.Model):
post = models.OneToOneField(Post, on_delete=models.CASCADE, related_name="placeholder")
some_placeholder = PlaceholderField("some_placeholder", related_name="some_placeholder")
def delete(self):
super().delete()
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,805
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/liveblog/migrations/0001_initial.py
|
import django.db.models.deletion
import filer.fields.image
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("cms", "0013_urlconfrevision"),
("filer", "0003_thumbnailoption"),
]
operations = [
migrations.CreateModel(
name="Liveblog",
fields=[
(
"cmsplugin_ptr",
models.OneToOneField(
parent_link=True,
auto_created=True,
primary_key=True,
serialize=False,
to="cms.CMSPlugin",
on_delete=django.db.models.deletion.CASCADE,
),
),
("body", models.TextField(verbose_name="body")),
("publish", models.BooleanField(default=False, verbose_name="publish liveblog entry")),
(
"image",
filer.fields.image.FilerImageField(
related_name="djangocms_blog_liveblog_image",
on_delete=django.db.models.deletion.SET_NULL,
verbose_name="image",
blank=True,
to="filer.Image",
null=True,
),
),
(
"thumbnail",
models.ForeignKey(
related_name="djangocms_blog_liveblog_thumbnail",
on_delete=django.db.models.deletion.SET_NULL,
verbose_name="thumbnail size",
blank=True,
to="filer.ThumbnailOption",
null=True,
),
),
],
options={
"verbose_name": "liveblog entry",
"verbose_name_plural": "liveblog entries",
},
bases=("cms.cmsplugin",),
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,806
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/taggit_urls.py
|
# This file is used on divio cloud only during automatic setup
from django.urls import path # pragma: no cover
from django.urls import include
urlpatterns = [ # pragma: no cover
path("taggit_autosuggest/", include("taggit_autosuggest.urls")),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,807
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/tests/test_setup.py
|
import sys
from cms.api import create_page, create_title
from cms.models import Page
from cms.utils import get_language_list
from django.utils.translation import override
from djangocms_blog.cms_appconfig import BlogConfig
from .base import BaseTest
try:
from django.test import override_settings
except ImportError:
from django.test.utils import override_settings
@override_settings(BLOG_AUTO_SETUP=True)
class SetupTest(BaseTest):
@classmethod
def setUpClass(cls):
# Skipping initialization to start with clean database
super(BaseTest, cls).setUpClass()
def setUp(self):
super().setUp()
from cms.apphook_pool import apphook_pool
delete = [
"djangocms_blog",
"djangocms_blog.cms_app",
"djangocms_blog.cms_apps",
]
for module in delete:
if module in sys.modules:
del sys.modules[module]
BlogConfig.cmsapp = None
apphook_pool.clear()
def test_setup_from_url(self):
# Tests starts with no page and no config
self.assertFalse(Page.objects.exists())
self.assertFalse(BlogConfig.objects.exists())
# importing cms_app triggers the auto setup
from djangocms_blog import cms_apps # NOQA
# Home and blog, published and draft
self.assertEqual(Page.objects.count(), 4)
self.assertEqual(BlogConfig.objects.count(), 1)
def test_setup_filled(self):
# Tests starts with no page and no config
self.assertFalse(Page.objects.exists())
self.assertFalse(BlogConfig.objects.exists())
set_home = hasattr(Page, "set_as_homepage")
langs = get_language_list()
home = None
for lang in langs:
with override(lang):
if not home:
home = create_page(
"a new home", language=lang, template="blog.html", in_navigation=True, published=True
)
if set_home:
home.set_as_homepage()
else:
create_title(language=lang, title="a new home", page=home)
home.publish(lang)
# importing cms_app triggers the auto setup
from djangocms_blog import cms_apps # NOQA
# Home and blog, published and draft
self.assertEqual(Page.objects.count(), 4)
self.assertEqual(BlogConfig.objects.count(), 1)
home = Page.objects.get_home()
for lang in langs:
self.assertEqual(home.get_title(lang), "a new home")
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,808
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0034_merge.py
|
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0022_auto_20170304_1040"),
("djangocms_blog", "0033_auto_20180226_1410"),
]
operations = []
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,809
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0001_initial.py
|
import cms.models.fields
import django.utils.timezone
import djangocms_text_ckeditor.fields
import filer.fields.image
import meta.models
import taggit_autosuggest.managers
from django.conf import settings
from django.db import migrations, models
from filer.settings import FILER_IMAGE_MODEL
from djangocms_blog.models import thumbnail_model
ACTUAL_FILER_IMAGE_MODEL = FILER_IMAGE_MODEL or "filer.Image"
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
migrations.swappable_dependency(ACTUAL_FILER_IMAGE_MODEL),
("cms", "0020_old_tree_cleanup"),
("taggit", "__first__"),
("filer", "0003_thumbnailoption"),
]
operations = [
migrations.CreateModel(
name="AuthorEntriesPlugin",
fields=[
(
"cmsplugin_ptr",
models.OneToOneField(
parent_link=True,
auto_created=True,
primary_key=True,
serialize=False,
to="cms.CMSPlugin",
on_delete=models.deletion.CASCADE,
),
),
(
"latest_posts",
models.IntegerField(
default=5, help_text="The number of author articles to be displayed.", verbose_name="Articles"
),
),
("authors", models.ManyToManyField(to=settings.AUTH_USER_MODEL, verbose_name="Authors")),
],
options={
"abstract": False,
},
bases=("cms.cmsplugin",),
),
migrations.CreateModel(
name="BlogCategory",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("date_created", models.DateTimeField(auto_now_add=True, verbose_name="created at")),
("date_modified", models.DateTimeField(auto_now=True, verbose_name="modified at")),
(
"parent",
models.ForeignKey(
verbose_name="parent",
blank=True,
to="djangocms_blog.BlogCategory",
null=True,
on_delete=models.deletion.CASCADE,
),
),
],
options={
"verbose_name": "blog category",
"verbose_name_plural": "blog categories",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="BlogCategoryTranslation",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
(
"language_code",
models.CharField(
db_index=True, max_length=15, verbose_name="Language", choices=settings.LANGUAGES
),
),
("name", models.CharField(max_length=255, verbose_name="name")),
("slug", models.SlugField(verbose_name="slug", blank=True)),
(
"master",
models.ForeignKey(
related_name="translations",
editable=False,
to="djangocms_blog.BlogCategory",
null=True,
on_delete=models.deletion.CASCADE,
),
),
],
options={
"db_table": "djangocms_blog_blogcategory_translation",
"verbose_name": "blog category Translation",
"default_permissions": (),
},
bases=(models.Model,),
),
migrations.CreateModel(
name="LatestPostsPlugin",
fields=[
(
"cmsplugin_ptr",
models.OneToOneField(
parent_link=True,
auto_created=True,
primary_key=True,
serialize=False,
to="cms.CMSPlugin",
on_delete=models.deletion.CASCADE,
),
),
(
"latest_posts",
models.IntegerField(
default=5, help_text="The number of latests articles to be displayed.", verbose_name="Articles"
),
),
(
"categories",
models.ManyToManyField(
help_text="Show only the blog articles tagged with chosen categories.",
to="djangocms_blog.BlogCategory",
blank=True,
),
),
(
"tags",
models.ManyToManyField(
help_text="Show only the blog articles tagged with chosen tags.", to="taggit.Tag", blank=True
),
),
],
options={
"abstract": False,
},
bases=("cms.cmsplugin",),
),
migrations.CreateModel(
name="Post",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("date_created", models.DateTimeField(auto_now_add=True)),
("date_modified", models.DateTimeField(auto_now=True)),
(
"date_published",
models.DateTimeField(default=django.utils.timezone.now, verbose_name="Published Since"),
),
("date_published_end", models.DateTimeField(null=True, verbose_name="Published Until", blank=True)),
("publish", models.BooleanField(default=False, verbose_name="Publish")),
("enable_comments", models.BooleanField(default=True, verbose_name="Enable comments on post")),
(
"author",
models.ForeignKey(
related_name="djangocms_blog_post_author",
verbose_name="Author",
blank=True,
to=settings.AUTH_USER_MODEL,
null=True,
on_delete=models.deletion.PROTECT,
),
),
(
"categories",
models.ManyToManyField(
related_name="blog_posts", verbose_name="category", to="djangocms_blog.BlogCategory"
),
),
(
"content",
cms.models.fields.PlaceholderField(
slotname="post_content", editable=False, to="cms.Placeholder", null=True
),
),
(
"main_image",
filer.fields.image.FilerImageField(
related_name="djangocms_blog_post_image",
verbose_name="Main image",
blank=True,
to=ACTUAL_FILER_IMAGE_MODEL,
null=True,
on_delete=models.deletion.SET_NULL,
),
),
(
"main_image_full",
models.ForeignKey(
related_name="djangocms_blog_post_full",
verbose_name="Main image full",
blank=True,
to=thumbnail_model,
null=True,
on_delete=models.deletion.SET_NULL,
),
),
(
"main_image_thumbnail",
models.ForeignKey(
related_name="djangocms_blog_post_thumbnail",
verbose_name="Main image thumbnail",
blank=True,
to=thumbnail_model,
null=True,
on_delete=models.deletion.SET_NULL,
),
),
(
"tags",
taggit_autosuggest.managers.TaggableManager(
to="taggit.Tag",
through="taggit.TaggedItem",
blank=True,
help_text="A comma-separated list of tags.",
verbose_name="Tags",
),
),
],
options={
"ordering": ("-date_published", "-date_created"),
"get_latest_by": "date_published",
"verbose_name": "blog article",
"verbose_name_plural": "blog articles",
},
bases=(meta.models.ModelMeta, models.Model),
),
migrations.CreateModel(
name="PostTranslation",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
(
"language_code",
models.CharField(
db_index=True, max_length=15, verbose_name="Language", choices=settings.LANGUAGES
),
),
("title", models.CharField(max_length=255, verbose_name="Title")),
("slug", models.SlugField(verbose_name="slug", blank=True)),
("abstract", djangocms_text_ckeditor.fields.HTMLField(verbose_name="Abstract")),
("meta_description", models.TextField(default="", verbose_name="Post meta description", blank=True)),
("meta_keywords", models.TextField(default="", verbose_name="Post meta keywords", blank=True)),
(
"meta_title",
models.CharField(
default="",
help_text="used in title tag and social sharing",
max_length=255,
verbose_name="Post meta title",
blank=True,
),
),
("post_text", djangocms_text_ckeditor.fields.HTMLField(default="", verbose_name="Text", blank=True)),
(
"master",
models.ForeignKey(
related_name="translations",
editable=False,
to="djangocms_blog.Post",
null=True,
on_delete=models.deletion.CASCADE,
),
),
],
options={
"db_table": "djangocms_blog_post_translation",
"verbose_name": "blog article Translation",
"default_permissions": (),
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name="posttranslation",
unique_together={("language_code", "master"), ("language_code", "slug")},
),
migrations.AlterUniqueTogether(
name="blogcategorytranslation",
unique_together={("language_code", "master"), ("language_code", "slug")},
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,810
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/liveblog/cms_plugins.py
|
from cms.plugin_pool import plugin_pool
from django.utils.translation import gettext_lazy as _
from djangocms_text_ckeditor.cms_plugins import TextPlugin
from djangocms_blog.settings import get_setting
from .models import Liveblog
@plugin_pool.register_plugin
class LiveblogPlugin(TextPlugin):
module = get_setting("PLUGIN_MODULE_NAME")
name = _("Liveblog item")
model = Liveblog
fields = ("title", "publish", "body", "post_date")
render_template = "liveblog/plugins/liveblog.html"
def save_model(self, request, obj, form, change):
super().save_model(request, obj, form, change)
if obj.publish:
obj.send(request)
def render(self, context, instance, placeholder):
context = super().render(context, instance, placeholder)
instance.content = context["body"]
context["instance"] = instance
return context
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,811
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0018_thumbnail_move2.py
|
from django.db import migrations, models
from djangocms_blog.models import thumbnail_model
class Migration(migrations.Migration):
if "cmsplugin_filer" not in thumbnail_model:
dependencies = [
("djangocms_blog", "0017_thumbnail_move"),
]
operations = [
migrations.AddField(
model_name="post",
name="main_image_full_new",
field=models.ForeignKey(
related_name="djangocms_blog_post_full",
verbose_name="Main image full",
blank=True,
to=thumbnail_model,
null=True,
on_delete=models.deletion.SET_NULL,
),
),
migrations.AddField(
model_name="post",
name="main_image_thumbnail_new",
field=models.ForeignKey(
related_name="djangocms_blog_post_thumbnail",
verbose_name="Main image thumbnail",
blank=True,
to=thumbnail_model,
null=True,
on_delete=models.deletion.SET_NULL,
),
),
]
else:
dependencies = [
("filer", "__first__"),
("cmsplugin_filer_image", "__first__"),
("djangocms_blog", "0017_thumbnail_move"),
]
operations = []
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,812
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0035_posttranslation_subtitle.py
|
# Generated by Django 1.11 on 2018-04-13 14:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0034_merge"),
]
operations = [
migrations.AddField(
model_name="posttranslation",
name="subtitle",
field=models.CharField(blank=True, default="", max_length=767, verbose_name="subtitle"),
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,813
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/liveblog/models.py
|
from operator import itemgetter
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from cms.models import CMSPlugin
from cms.utils.plugins import reorder_plugins
from django.db import models
from django.template import Context
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
from djangocms_text_ckeditor.models import AbstractText
from filer.fields.image import FilerImageField
from djangocms_blog.models import Post, thumbnail_model
from djangocms_blog.settings import DATE_FORMAT
class LiveblogInterface(models.Model):
"""
Abstract Liveblog plugin model, reusable to customize the liveblogging
plugins.
When implementing this, you **must** call ``self._post_save()`` in the
concrete plugin model ``save`` method.
"""
publish = models.BooleanField(_("publish liveblog entry"), default=False)
post_date = models.DateTimeField(_("post date"), blank=True, default=now)
class Meta:
verbose_name = _("liveblog entry")
verbose_name_plural = _("liveblog entries")
abstract = True
def __str__(self):
return str(self.pk)
def _post_save(self):
"""
Reorder plugins according to the post_date value. All (and only)
subclasses of LiveblogInterface are taken into consideration and
reordered together
"""
items = []
for model in LiveblogInterface.__subclasses__():
items.extend(model.objects.filter(placeholder=self.placeholder).values("pk", "post_date"))
order = reversed([item["pk"] for item in sorted(items, key=itemgetter("post_date"))])
reorder_plugins(self.placeholder, None, self.language, order)
@property
def liveblog_group(self):
post = Post.objects.language(self.language).filter(liveblog=self.placeholder).first()
if post:
return post.liveblog_group
def render(self, request):
context = Context({"request": request})
from cms.plugin_rendering import ContentRenderer
renderer = ContentRenderer(request)
return renderer.render_plugin(
instance=self,
context=context,
placeholder=self.placeholder,
)
def send(self, request):
"""
Render the content and send to the related group
"""
if self.liveblog_group:
content = self.render(request)
notification = {
"id": self.pk,
"content": content,
"creation_date": self.post_date.strftime(DATE_FORMAT),
"changed_date": self.changed_date.strftime(DATE_FORMAT),
"type": "send.json",
}
channel_layer = get_channel_layer()
group = self.liveblog_group
async_to_sync(channel_layer.group_send)(group, notification)
class Liveblog(LiveblogInterface, AbstractText):
"""
Basic liveblog plugin model
"""
cmsplugin_ptr = models.OneToOneField(
CMSPlugin, related_name="%(app_label)s_%(class)s", primary_key=True, parent_link=True, on_delete=models.CASCADE
)
title = models.CharField(_("title"), max_length=255)
image = FilerImageField(
verbose_name=_("image"),
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name="djangocms_blog_liveblog_image",
)
thumbnail = models.ForeignKey(
thumbnail_model,
verbose_name=_("thumbnail size"),
on_delete=models.SET_NULL,
blank=True,
null=True,
related_name="djangocms_blog_liveblog_thumbnail",
)
class Meta:
verbose_name = _("liveblog entry")
verbose_name_plural = _("liveblog entries")
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
self._post_save()
def __str__(self):
return AbstractText.__str__(self)
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,814
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/tests/test_media.py
|
import os
from unittest.mock import MagicMock, patch
from cms.api import add_plugin
from djangocms_blog.templatetags.djangocms_blog import media_images, media_plugins
from .base import BaseTest
class MediaTest(BaseTest):
def setUp(self):
super().setUp()
self.get_pages()
posts = self.get_posts()
self.post = posts[0]
self.youtube = add_plugin(
self.post.media, "YouTubePlugin", language="en", url="https://www.youtube.com/watch?v=szbGc7ymFhQ"
)
self.vimeo = add_plugin(self.post.media, "VimeoPlugin", language="en", url="https://vimeo.com/12915013")
self.media_text = add_plugin(self.post.media, "TextPlugin", language="en", body="random text")
self.general_text = add_plugin(self.post.content, "TextPlugin", language="en", body="body text")
def _get_request_mock(self, json_path):
response = self.read_json(json_path)
response_mock = MagicMock()
response_mock.json.return_value = response
return response_mock
def test_no_media_plugins(self):
self.post.media.get_plugins().delete()
context = {"request": self.request("/")}
plugins = media_plugins(context, self.post)
self.assertEqual(0, len(plugins))
def test_media_plugins(self):
context = {"request": self.request("/")}
plugins = media_plugins(context, self.post)
self.assertEqual(3, len(plugins))
self.assertIn(self.youtube, plugins)
self.assertIn(self.vimeo, plugins)
self.assertIn(self.media_text, plugins)
self.assertNotIn(self.general_text, plugins)
@patch("tests.media_app.models.Vimeo.vimeo_data")
def test_djangocms_video_plugins(self, vimeo_data):
vimeo_data.return_value = {
"main_url": "https://i.vimeocdn.com/video/73266401_200x150.jpg",
"thumb_url": "https://i.vimeocdn.com/video/73266401_200x150.jpg",
}
filer_image = self.create_filer_image_object()
src_thumbs = [
"https://img.youtube.com/vi/szbGc7ymFhQ/hqdefault.jpg",
"https://i.vimeocdn.com/video/73266401_200x150.jpg",
filer_image.url,
]
add_plugin(self.post.media, "VideoPlayerPlugin", language="en", poster=filer_image)
context = {"request": self.request("/")}
images = media_images(context, self.post, main=False)
self.assertEqual(3, len(images))
self.assertEqual(images, src_thumbs)
@patch("tests.media_app.models.requests.get")
def test_media_images(self, get_request):
src_images = [
"https://img.youtube.com/vi/szbGc7ymFhQ/maxresdefault.jpg",
"https://i.vimeocdn.com/video/73266401_640.jpg",
]
src_thumbs = [
"https://img.youtube.com/vi/szbGc7ymFhQ/hqdefault.jpg",
"https://i.vimeocdn.com/video/73266401_200x150.jpg",
]
get_request.return_value = self._get_request_mock(os.path.join("fixtures", "vimeo.json"))
context = {"request": self.request("/")}
images = media_images(context, self.post)
self.assertEqual(2, len(images))
self.assertEqual(images, src_images)
images = media_images(context, self.post, main=False)
self.assertEqual(2, len(images))
self.assertEqual(images, src_thumbs)
@patch("tests.media_app.models.requests.get")
def test_media_attributes(self, get_request):
src_ids = ["szbGc7ymFhQ", "12915013"]
get_request.return_value = self._get_request_mock(os.path.join("fixtures", "vimeo.json"))
context = {"request": self.request("/")}
plugins = media_plugins(context, self.post)
dst_ids = [media.media_id for media in plugins if hasattr(media, "media_id")]
self.assertEqual(dst_ids, src_ids)
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,815
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0004_auto_20150108_1435.py
|
import django.db.models.deletion
import filer.fields.image
from django.db import migrations, models
from filer.settings import FILER_IMAGE_MODEL
from djangocms_blog.models import thumbnail_model
ACTUAL_FILER_IMAGE_MODEL = FILER_IMAGE_MODEL or "filer.Image"
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(ACTUAL_FILER_IMAGE_MODEL),
("djangocms_blog", "0003_auto_20141201_2252"),
("filer", "0003_thumbnailoption"),
]
operations = [
migrations.AlterField(
model_name="post",
name="main_image",
field=filer.fields.image.FilerImageField(
related_name="djangocms_blog_post_image",
on_delete=django.db.models.deletion.SET_NULL,
verbose_name="Main image",
blank=True,
to=ACTUAL_FILER_IMAGE_MODEL,
null=True,
),
preserve_default=True,
),
migrations.AlterField(
model_name="post",
name="main_image_full",
field=models.ForeignKey(
related_name="djangocms_blog_post_full",
on_delete=django.db.models.deletion.SET_NULL,
verbose_name="Main image full",
blank=True,
to=thumbnail_model,
null=True,
),
preserve_default=True,
),
migrations.AlterField(
model_name="post",
name="main_image_thumbnail",
field=models.ForeignKey(
related_name="djangocms_blog_post_thumbnail",
on_delete=django.db.models.deletion.SET_NULL,
verbose_name="Main image thumbnail",
blank=True,
to=thumbnail_model,
null=True,
),
preserve_default=True,
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,816
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0029_post_related.py
|
# Generated by Django 1.10.5 on 2017-04-07 07:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0028_auto_20170304_1040"),
]
operations = [
migrations.AddField(
model_name="post",
name="related",
field=models.ManyToManyField(blank=True, to="djangocms_blog.Post", verbose_name="Related Posts"),
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,817
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/models.py
|
import hashlib
from aldryn_apphooks_config.fields import AppHookConfigField
from aldryn_apphooks_config.managers.parler import AppHookConfigTranslatableManager
from cms.models import CMSPlugin, PlaceholderField
from django.conf import settings as dj_settings
from django.contrib.auth import get_user_model
from django.contrib.sites.shortcuts import get_current_site
from django.core.cache import cache
from django.db import models
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from django.urls import reverse
from django.utils import timezone
from django.utils.encoding import force_bytes, force_str
from django.utils.functional import cached_property
from django.utils.html import strip_tags
from django.utils.translation import get_language, gettext, gettext_lazy as _
from djangocms_text_ckeditor.fields import HTMLField
from easy_thumbnails.files import get_thumbnailer
from filer.fields.image import FilerImageField
from filer.models import ThumbnailOption
from meta.models import ModelMeta
from parler.models import TranslatableModel, TranslatedFields
from parler.utils.context import switch_language
from sortedm2m.fields import SortedManyToManyField
from taggit_autosuggest.managers import TaggableManager
from .cms_appconfig import BlogConfig
from .fields import slugify
from .managers import GenericDateTaggedManager
from .settings import get_setting
BLOG_CURRENT_POST_IDENTIFIER = get_setting("CURRENT_POST_IDENTIFIER")
BLOG_CURRENT_NAMESPACE = get_setting("CURRENT_NAMESPACE")
BLOG_PLUGIN_TEMPLATE_FOLDERS = get_setting("PLUGIN_TEMPLATE_FOLDERS")
thumbnail_model = "{}.{}".format(ThumbnailOption._meta.app_label, ThumbnailOption.__name__)
try:
from knocker.mixins import KnockerModel
except ImportError: # pragma: no cover
class KnockerModel:
"""
Stub class if django-knocker is not installed
"""
pass
def _get_language(instance, language):
available_languages = instance.get_available_languages()
if language and language in available_languages:
return language
language = get_language()
if language and language in available_languages:
return language
language = instance.get_current_language()
if language and language in available_languages:
return language
if get_setting("USE_FALLBACK_LANGUAGE_IN_URL"):
for fallback_language in instance.get_fallback_languages():
if fallback_language in available_languages:
return fallback_language
return language
class BlogMetaMixin(ModelMeta):
def get_meta_attribute(self, param):
"""
Retrieves django-meta attributes from apphook config instance
:param param: django-meta attribute passed as key
"""
return self._get_meta_value(param, getattr(self.app_config, param)) or ""
def get_locale(self):
return self.get_current_language()
def get_full_url(self):
"""
Return the url with protocol and domain url
"""
return self.build_absolute_uri(self.get_absolute_url())
class BlogCategory(BlogMetaMixin, TranslatableModel):
"""
Blog category
"""
parent = models.ForeignKey(
"self", verbose_name=_("parent"), null=True, blank=True, related_name="children", on_delete=models.CASCADE
)
date_created = models.DateTimeField(_("created at"), auto_now_add=True)
date_modified = models.DateTimeField(_("modified at"), auto_now=True)
app_config = AppHookConfigField(BlogConfig, null=True, verbose_name=_("app. config"))
translations = TranslatedFields(
name=models.CharField(_("name"), max_length=752),
slug=models.SlugField(_("slug"), max_length=752, blank=True, db_index=True),
meta_description=models.TextField(verbose_name=_("category meta description"), blank=True, default=""),
meta={"unique_together": (("language_code", "slug"),)},
)
objects = AppHookConfigTranslatableManager()
_metadata = {
"title": "get_title",
"description": "get_description",
"og_description": "get_description",
"twitter_description": "get_description",
"schemaorg_description": "get_description",
"schemaorg_type": "get_meta_attribute",
"locale": "get_locale",
"object_type": "get_meta_attribute",
"og_type": "get_meta_attribute",
"og_app_id": "get_meta_attribute",
"og_profile_id": "get_meta_attribute",
"og_publisher": "get_meta_attribute",
"og_author_url": "get_meta_attribute",
"og_author": "get_meta_attribute",
"twitter_type": "get_meta_attribute",
"twitter_site": "get_meta_attribute",
"twitter_author": "get_meta_attribute",
"url": "get_absolute_url",
}
class Meta:
verbose_name = _("blog category")
verbose_name_plural = _("blog categories")
def descendants(self):
children = []
if self.children.exists():
children.extend(self.children.all())
for child in self.children.all():
children.extend(child.descendants())
return children
@cached_property
def linked_posts(self):
return self.blog_posts.namespace(self.app_config.namespace)
@cached_property
def count(self):
return self.linked_posts.published().count()
@cached_property
def count_all_sites(self):
return self.linked_posts.published(current_site=False).count()
def get_absolute_url(self, lang=None):
lang = _get_language(self, lang)
if self.has_translation(lang):
slug = self.safe_translation_getter("slug", language_code=lang)
return reverse(
"%s:posts-category" % self.app_config.namespace,
kwargs={"category": slug},
current_app=self.app_config.namespace,
)
# in case category doesn't exist in this language, gracefully fallback
# to posts-latest
return reverse("%s:posts-latest" % self.app_config.namespace, current_app=self.app_config.namespace)
def __str__(self):
default = gettext("BlogCategory (no translation)")
return self.safe_translation_getter("name", any_language=True, default=default)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
for lang in self.get_available_languages():
self.set_current_language(lang)
if not self.slug and self.name:
self.slug = slugify(force_str(self.name))
self.save_translations()
def get_title(self):
title = self.safe_translation_getter("name", any_language=True)
return title.strip()
def get_description(self):
description = self.safe_translation_getter("meta_description", any_language=True)
return strip_tags(description).strip()
class Post(KnockerModel, BlogMetaMixin, TranslatableModel):
"""
Blog post
"""
author = models.ForeignKey(
dj_settings.AUTH_USER_MODEL,
verbose_name=_("author"),
null=True,
blank=True,
related_name="djangocms_blog_post_author",
on_delete=models.PROTECT,
)
date_created = models.DateTimeField(_("created"), auto_now_add=True)
date_modified = models.DateTimeField(_("last modified"), auto_now=True)
date_published = models.DateTimeField(_("published since"), null=True, blank=True)
date_published_end = models.DateTimeField(_("published until"), null=True, blank=True)
date_featured = models.DateTimeField(_("featured date"), null=True, blank=True)
publish = models.BooleanField(_("publish"), default=False)
include_in_rss = models.BooleanField(_("include in RSS feed"), default=True)
categories = models.ManyToManyField(
"djangocms_blog.BlogCategory", verbose_name=_("category"), related_name="blog_posts", blank=True
)
main_image = FilerImageField(
verbose_name=_("main image"),
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name="djangocms_blog_post_image",
)
main_image_thumbnail = models.ForeignKey(
thumbnail_model,
verbose_name=_("main image thumbnail"),
related_name="djangocms_blog_post_thumbnail",
on_delete=models.SET_NULL,
blank=True,
null=True,
)
main_image_full = models.ForeignKey(
thumbnail_model,
verbose_name=_("main image full"),
related_name="djangocms_blog_post_full",
on_delete=models.SET_NULL,
blank=True,
null=True,
)
enable_comments = models.BooleanField(
verbose_name=_("enable comments on post"), default=get_setting("ENABLE_COMMENTS")
)
sites = models.ManyToManyField(
"sites.Site",
verbose_name=_("Site(s)"),
blank=True,
help_text=_(
"Select sites in which to show the post. "
"If none is set it will be "
"visible in all the configured sites."
),
)
app_config = AppHookConfigField(BlogConfig, null=True, verbose_name=_("app. config"))
translations = TranslatedFields(
title=models.CharField(_("title"), max_length=752),
slug=models.SlugField(
_("slug"), max_length=752, blank=True, db_index=True, allow_unicode=get_setting("UNICODE_SLUGS")
),
subtitle=models.CharField(verbose_name=_("subtitle"), max_length=767, blank=True, default=""),
abstract=HTMLField(_("abstract"), blank=True, default="", configuration="BLOG_ABSTRACT_CKEDITOR"),
meta_description=models.TextField(verbose_name=_("post meta description"), blank=True, default=""),
meta_keywords=models.TextField(verbose_name=_("post meta keywords"), blank=True, default=""),
meta_title=models.CharField(
verbose_name=_("post meta title"),
help_text=_("used in title tag and social sharing"),
max_length=2000,
blank=True,
default="",
),
post_text=HTMLField(_("text"), default="", blank=True, configuration="BLOG_POST_TEXT_CKEDITOR"),
meta={"unique_together": (("language_code", "slug"),)},
)
media = PlaceholderField("media", related_name="media")
content = PlaceholderField("post_content", related_name="post_content")
liveblog = PlaceholderField("live_blog", related_name="live_blog")
enable_liveblog = models.BooleanField(verbose_name=_("enable liveblog on post"), default=False)
objects = GenericDateTaggedManager()
tags = TaggableManager(
blank=True,
related_name="djangocms_blog_tags",
help_text=_("Type a tag and hit tab, or start typing and select from autocomplete list."),
)
related = SortedManyToManyField("self", verbose_name=_("Related Posts"), blank=True, symmetrical=False)
_metadata = {
"title": "get_title",
"description": "get_description",
"keywords": "get_keywords",
"og_description": "get_description",
"twitter_description": "get_description",
"schemaorg_description": "get_description",
"locale": "get_locale",
"image": "get_image_full_url",
"image_width": "get_image_width",
"image_height": "get_image_height",
"object_type": "get_meta_attribute",
"og_type": "get_meta_attribute",
"og_app_id": "get_meta_attribute",
"og_profile_id": "get_meta_attribute",
"og_publisher": "get_meta_attribute",
"og_author_url": "get_meta_attribute",
"og_author": "get_meta_attribute",
"twitter_type": "get_meta_attribute",
"twitter_site": "get_meta_attribute",
"twitter_author": "get_meta_attribute",
"schemaorg_type": "get_meta_attribute",
"published_time": "date_published",
"modified_time": "date_modified",
"expiration_time": "date_published_end",
"tag": "get_tags",
"url": "get_absolute_url",
}
class Meta:
verbose_name = _("blog article")
verbose_name_plural = _("blog articles")
ordering = ("-date_published", "-date_created")
get_latest_by = "date_published"
def __str__(self):
default = gettext("Post (no translation)")
return self.safe_translation_getter("title", any_language=True, default=default)
@property
def guid(self, language=None):
if not language:
language = self.get_current_language()
base_string = "-{0}-{2}-{1}-".format(
language,
self.app_config.namespace,
self.safe_translation_getter("slug", language_code=language, any_language=True),
)
return hashlib.sha256(force_bytes(base_string)).hexdigest()
@property
def date(self):
if self.date_featured:
return self.date_featured
return self.date_published
def save(self, *args, **kwargs):
"""
Handle some auto configuration during save
"""
if self.publish and self.date_published is None:
self.date_published = timezone.now()
if not self.slug and self.title:
self.slug = slugify(self.title)
super().save(*args, **kwargs)
def save_translation(self, translation, *args, **kwargs):
"""
Handle some auto configuration during save
"""
if not translation.slug and translation.title:
translation.slug = slugify(translation.title)
super().save_translation(translation, *args, **kwargs)
def get_absolute_url(self, lang=None):
lang = _get_language(self, lang)
with switch_language(self, lang):
category = self.categories.first()
kwargs = {}
if self.date_published:
current_date = self.date_published
else:
current_date = self.date_created
urlconf = get_setting("PERMALINK_URLS")[self.app_config.url_patterns]
if "<int:year>" in urlconf:
kwargs["year"] = current_date.year
if "<int:month>" in urlconf:
kwargs["month"] = "%02d" % current_date.month
if "<int:day>" in urlconf:
kwargs["day"] = "%02d" % current_date.day
if "<str:slug>" in urlconf or "<slug:slug>" in urlconf:
kwargs["slug"] = self.safe_translation_getter("slug", language_code=lang, any_language=True) # NOQA
if "<slug:category>" in urlconf or "<str:category>" in urlconf:
kwargs["category"] = category.safe_translation_getter(
"slug", language_code=lang, any_language=True
) # NOQA
return reverse(
"%s:post-detail" % self.app_config.namespace, kwargs=kwargs, current_app=self.app_config.namespace
)
def get_title(self):
title = self.safe_translation_getter("meta_title", any_language=True)
if not title:
title = self.safe_translation_getter("title", any_language=True)
return title.strip()
def get_keywords(self):
"""
Returns the list of keywords (as python list)
:return: list
"""
return self.safe_translation_getter("meta_keywords", default="").strip().split(",")
def get_description(self):
description = self.safe_translation_getter("meta_description", any_language=True)
if not description:
description = self.safe_translation_getter("abstract", any_language=True)
return strip_tags(description).strip()
def get_image_full_url(self):
if self.main_image:
thumbnail_options = get_setting("META_IMAGE_SIZE")
if thumbnail_options:
thumbnail_url = get_thumbnailer(self.main_image).get_thumbnail(thumbnail_options).url
return self.build_absolute_uri(thumbnail_url)
return self.build_absolute_uri(self.main_image.url)
return ""
def get_image_width(self):
if self.main_image:
thumbnail_options = get_setting("META_IMAGE_SIZE")
if thumbnail_options:
return get_thumbnailer(self.main_image).get_thumbnail(thumbnail_options).width
return self.main_image.width
def get_image_height(self):
if self.main_image:
thumbnail_options = get_setting("META_IMAGE_SIZE")
if thumbnail_options:
return get_thumbnailer(self.main_image).get_thumbnail(thumbnail_options).height
return self.main_image.height
def get_tags(self):
"""
Returns the list of object tags as comma separated list
"""
taglist = [tag.name for tag in self.tags.all()]
return ",".join(taglist)
def get_author(self):
"""
Return the author (user) objects
"""
return self.author
def _set_default_author(self, current_user):
if not self.author_id and self.app_config.set_author:
if get_setting("AUTHOR_DEFAULT") is True:
user = current_user
else:
user = get_user_model().objects.get(username=get_setting("AUTHOR_DEFAULT"))
self.author = user
def thumbnail_options(self):
if self.main_image_thumbnail_id:
return self.main_image_thumbnail.as_dict
else:
return get_setting("IMAGE_THUMBNAIL_SIZE")
def full_image_options(self):
if self.main_image_full_id:
return self.main_image_full.as_dict
else:
return get_setting("IMAGE_FULL_SIZE")
@property
def is_published(self):
"""
Checks wether the blog post is *really* published by checking publishing dates too
"""
return (
self.publish
and (self.date_published and self.date_published <= timezone.now())
and (self.date_published_end is None or self.date_published_end > timezone.now())
)
def should_knock(self, signal_type, created=False):
"""
Returns whether to emit knocks according to the post state
"""
new = self.app_config.send_knock_create and self.is_published and self.date_published == self.date_modified
updated = self.app_config.send_knock_update and self.is_published
return (new or updated) and signal_type in ("post_save", "post_delete")
def get_cache_key(self, language, prefix):
return "djangocms-blog:{2}:{0}:{1}".format(language, self.guid, prefix)
@property
def liveblog_group(self):
return "liveblog-{apphook}-{lang}-{post}".format(
lang=self.get_current_language(),
apphook=self.app_config.namespace,
post=self.safe_translation_getter("slug", any_language=True),
)
class BasePostPlugin(CMSPlugin):
app_config = AppHookConfigField(BlogConfig, null=True, verbose_name=_("app. config"), blank=True)
current_site = models.BooleanField(
_("current site"), default=True, help_text=_("Select items from the current site only")
)
template_folder = models.CharField(
max_length=200,
verbose_name=_("Plugin template"),
help_text=_("Select plugin template to load for this instance"),
default=BLOG_PLUGIN_TEMPLATE_FOLDERS[0][0],
choices=BLOG_PLUGIN_TEMPLATE_FOLDERS,
)
class Meta:
abstract = True
def optimize(self, qs):
"""
Apply select_related / prefetch_related to optimize the view queries
:param qs: queryset to optimize
:return: optimized queryset
"""
return qs.select_related("app_config").prefetch_related(
"translations", "categories", "categories__translations", "categories__app_config"
)
def post_queryset(self, request=None, published_only=True):
language = get_language()
posts = Post.objects
if self.app_config:
posts = posts.namespace(self.app_config.namespace)
if self.current_site:
posts = posts.on_site(get_current_site(request))
posts = posts.active_translations(language_code=language)
if (
published_only
or not request
or not getattr(request, "toolbar", False)
or not request.toolbar.edit_mode_active
):
posts = posts.published(current_site=self.current_site)
return self.optimize(posts.all())
class LatestPostsPlugin(BasePostPlugin):
latest_posts = models.IntegerField(
_("articles"),
default=get_setting("LATEST_POSTS"),
help_text=_("The number of latests " "articles to be displayed."),
)
tags = TaggableManager(
_("filter by tag"),
blank=True,
help_text=_("Show only the blog articles tagged with chosen tags."),
related_name="djangocms_blog_latest_post",
)
categories = models.ManyToManyField(
"djangocms_blog.BlogCategory",
blank=True,
verbose_name=_("filter by category"),
help_text=_("Show only the blog articles tagged " "with chosen categories."),
)
def __str__(self):
return force_str(_("%s latest articles by tag") % self.latest_posts)
def copy_relations(self, oldinstance):
for tag in oldinstance.tags.all():
self.tags.add(tag)
for category in oldinstance.categories.all():
self.categories.add(category)
def get_posts(self, request, published_only=True):
posts = self.post_queryset(request, published_only)
if self.tags.exists():
posts = posts.filter(tags__in=list(self.tags.all()))
if self.categories.exists():
posts = posts.filter(categories__in=list(self.categories.all()))
return self.optimize(posts.distinct())[: self.latest_posts]
class AuthorEntriesPlugin(BasePostPlugin):
authors = models.ManyToManyField(
dj_settings.AUTH_USER_MODEL,
verbose_name=_("authors"),
limit_choices_to={"djangocms_blog_post_author__publish": True},
)
latest_posts = models.IntegerField(
_("articles"),
default=get_setting("LATEST_POSTS"),
help_text=_("The number of author articles to be displayed."),
)
def __str__(self):
return force_str(_("%s latest articles by author") % self.latest_posts)
def copy_relations(self, oldinstance):
self.authors.set(oldinstance.authors.all())
def get_posts(self, request, published_only=True):
posts = self.post_queryset(request, published_only)
return posts
def get_authors(self, request):
authors = self.authors.all()
for author in authors:
qs = self.get_posts(request).filter(author=author)
# total nb of articles
author.count = qs.count()
# "the number of author articles to be displayed"
author.posts = qs[: self.latest_posts]
return authors
class FeaturedPostsPlugin(BasePostPlugin):
posts = SortedManyToManyField(Post, verbose_name=_("Featured posts"))
def __str__(self):
return _("Featured posts")
def copy_relations(self, oldinstance):
self.posts.set(oldinstance.posts.all())
def get_posts(self, request, published_only=True):
posts = self.post_queryset(request, published_only)
return posts
class GenericBlogPlugin(BasePostPlugin):
class Meta:
abstract = False
def __str__(self):
return force_str(_("generic blog plugin"))
@receiver(pre_delete, sender=Post)
def pre_delete_post(sender, instance, **kwargs):
for language in instance.get_available_languages():
key = instance.get_cache_key(language, "feed")
cache.delete(key)
@receiver(post_save, sender=Post)
def post_save_post(sender, instance, **kwargs):
for language in instance.get_available_languages():
key = instance.get_cache_key(language, "feed")
cache.delete(key)
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,818
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0013_auto_20160201_2235.py
|
# Generated by Django 1.9.2 on 2016-02-01 21:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0012_auto_20151220_1734"),
]
operations = [
migrations.AlterField(
model_name="post",
name="categories",
field=models.ManyToManyField(
blank=True, related_name="blog_posts", to="djangocms_blog.BlogCategory", verbose_name="category"
),
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,819
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0022_auto_20170304_1040.py
|
# Generated by Django 1.9.12 on 2017-03-04 09:40
from distutils.version import LooseVersion
import aldryn_apphooks_config
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0021_auto_20160823_2008"),
]
if LooseVersion(aldryn_apphooks_config.__version__) > LooseVersion("0.3.0"):
operations = [
migrations.AlterField(
model_name="blogconfig",
name="namespace",
field=models.CharField(default=None, max_length=100, unique=True, verbose_name="Instance namespace"),
),
migrations.AlterField(
model_name="blogconfig",
name="type",
field=models.CharField(max_length=100, verbose_name="Type"),
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,820
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/liveblog/apps.py
|
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class LiveBlogAppConfig(AppConfig):
name = "djangocms_blog.liveblog"
verbose_name = _("Liveblog")
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,821
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/cms_appconfig.py
|
from aldryn_apphooks_config.models import AppHookConfig
from aldryn_apphooks_config.utils import setup_config
from app_data import AppDataForm
from django import forms
from django.db import models
from django.utils.translation import gettext_lazy as _
from filer.models import ThumbnailOption
from parler.models import TranslatableModel, TranslatedFields
from .settings import MENU_TYPE_COMPLETE, get_setting
class BlogConfig(TranslatableModel, AppHookConfig):
"""
Adds translatable, per-app-instance fields.
"""
translations = TranslatedFields(
app_title=models.CharField(_("application title"), max_length=234),
object_name=models.CharField(_("object name"), max_length=234, default=get_setting("DEFAULT_OBJECT_NAME")),
)
class Meta:
verbose_name = _("blog config")
verbose_name_plural = _("blog configs")
def get_app_title(self):
return getattr(self, "app_title", _("untitled"))
@property
def schemaorg_type(self):
"""Compatibility shim to fetch data from legacy gplus_type field."""
return self.gplus_type
class BlogConfigForm(AppDataForm):
"""
Settings that can be changed per-apphook.
Their default value is the same as the corresponding Django settings,
but it can be customized per each apphook and changed at runtime.
"""
app_title = get_setting("AUTO_APP_TITLE")
"""
Free text title that can be used as title in templates
"""
object_name = get_setting("DEFAULT_OBJECT_NAME")
"""
Free text label for Blog items in django CMS Wizard
"""
#: Post published by default (default: :ref:`DEFAULT_PUBLISHED <DEFAULT_PUBLISHED>`)
default_published = forms.BooleanField(
label=_("Post published by default"), required=False, initial=get_setting("DEFAULT_PUBLISHED")
)
#: Default size of full images
default_image_full = forms.ModelChoiceField(
label=_("Default size of full images"),
queryset=ThumbnailOption.objects.all(),
required=False,
help_text=_("If left empty the image size will have to be set for every newly created post."),
)
#: Default size of thumbnail images
default_image_thumbnail = forms.ModelChoiceField(
label=_("Default size of thumbnail images"),
queryset=ThumbnailOption.objects.all(),
required=False,
help_text=_("If left empty the thumbnail image size will have to be set for every newly created post."),
)
#: Structure of permalinks (get_absolute_url); see :ref:`AVAILABLE_PERMALINK_STYLES <AVAILABLE_PERMALINK_STYLES>`
url_patterns = forms.ChoiceField(
label=_("Permalink structure"),
required=False,
initial=get_setting("AVAILABLE_PERMALINK_STYLES")[0][0],
choices=get_setting("AVAILABLE_PERMALINK_STYLES"),
)
#: Use placeholder and plugins for article body (default: :ref:`USE_PLACEHOLDER <USE_PLACEHOLDER>`)
use_placeholder = forms.BooleanField(
label=_("Use placeholder and plugins for article body"), required=False, initial=get_setting("USE_PLACEHOLDER")
)
#: Use abstract field (default: :ref:`USE_ABSTRACT <USE_ABSTRACT>`)
use_abstract = forms.BooleanField(
label=_("Use abstract field"), required=False, initial=get_setting("USE_ABSTRACT")
)
#: Enable related posts (default: :ref:`USE_RELATED <USE_RELATED>`)
use_related = forms.BooleanField(
label=_("Enable related posts"), required=False, initial=get_setting("USE_RELATED")
)
#: Set author by default (default: :ref:`AUTHOR_DEFAULT <AUTHOR_DEFAULT>`)
set_author = forms.BooleanField(
label=_("Set author"),
required=False,
help_text=_("Set author by default"),
initial=get_setting("AUTHOR_DEFAULT"),
)
#: When paginating list views, how many articles per page? (default: :ref:`PAGINATION <PAGINATION>`)
paginate_by = forms.IntegerField(
label=_("Paginate size"),
required=False,
initial=get_setting("PAGINATION"),
help_text=_("When paginating list views, how many articles per page?"),
)
#: Alternative directory to load the blog templates from (default: "")
template_prefix = forms.CharField(
label=_("Template prefix"),
required=False,
initial="",
help_text=_("Alternative directory to load the blog templates from"),
)
#: Menu structure (default: ``MENU_TYPE_COMPLETE``, see :ref:`MENU_TYPES <MENU_TYPES>`)
menu_structure = forms.ChoiceField(
label=_("Menu structure"),
required=True,
choices=get_setting("MENU_TYPES"),
initial=MENU_TYPE_COMPLETE,
help_text=_("Structure of the django CMS menu"),
)
#: Show empty categories in menu (default: :ref:`MENU_EMPTY_CATEGORIES <MENU_EMPTY_CATEGORIES>`)
menu_empty_categories = forms.BooleanField(
label=_("Show empty categories in menu"),
initial=get_setting("MENU_EMPTY_CATEGORIES"),
required=False,
help_text=_("Show categories with no post attached in the menu"),
)
#: Sitemap changefreq (default: :ref:`SITEMAP_CHANGEFREQ_DEFAULT <SITEMAP_CHANGEFREQ_DEFAULT>`,
#: see: :ref:`SITEMAP_CHANGEFREQ <SITEMAP_CHANGEFREQ>`)
sitemap_changefreq = forms.ChoiceField(
label=_("Sitemap changefreq"),
required=True,
choices=get_setting("SITEMAP_CHANGEFREQ"),
initial=get_setting("SITEMAP_CHANGEFREQ_DEFAULT"),
help_text=_("Changefreq attribute for sitemap items"),
)
#: Sitemap priority (default: :ref:`SITEMAP_PRIORITY_DEFAULT <SITEMAP_PRIORITY_DEFAULT>`)
sitemap_priority = forms.CharField(
label=_("Sitemap priority"),
required=True,
initial=get_setting("SITEMAP_PRIORITY_DEFAULT"),
help_text=_("Priority attribute for sitemap items"),
)
#: Object type (default: :ref:`TYPE <TYPE>`, see :ref:`TYPES <TYPES>`)
object_type = forms.ChoiceField(
label=_("Object type"), required=False, choices=get_setting("TYPES"), initial=get_setting("TYPE")
)
#: Facebook type (default: :ref:`FB_TYPE <FB_TYPE>`, see :ref:`FB_TYPES <FB_TYPES>`)
og_type = forms.ChoiceField(
label=_("Facebook type"), required=False, choices=get_setting("FB_TYPES"), initial=get_setting("FB_TYPE")
)
#: Facebook application ID (default: :ref:`FB_PROFILE_ID <FB_PROFILE_ID>`)
og_app_id = forms.CharField(
max_length=200, label=_("Facebook application ID"), required=False, initial=get_setting("FB_PROFILE_ID")
)
#: Facebook profile ID (default: :ref:`FB_PROFILE_ID <FB_PROFILE_ID>`)
og_profile_id = forms.CharField(
max_length=200, label=_("Facebook profile ID"), required=False, initial=get_setting("FB_PROFILE_ID")
)
#: Facebook page URL (default: :ref:`FB_PUBLISHER <FB_PUBLISHER>`)
og_publisher = forms.CharField(
max_length=200, label=_("Facebook page URL"), required=False, initial=get_setting("FB_PUBLISHER")
)
#: Facebook author URL (default: :ref:`FB_AUTHOR_URL <FB_AUTHOR_URL>`)
og_author_url = forms.CharField(
max_length=200, label=_("Facebook author URL"), required=False, initial=get_setting("FB_AUTHOR_URL")
)
#: Facebook author (default: :ref:`FB_AUTHOR <FB_AUTHOR>`)
og_author = forms.CharField(
max_length=200, label=_("Facebook author"), required=False, initial=get_setting("FB_AUTHOR")
)
#: Twitter type field (default: :ref:`TWITTER_TYPE <TWITTER_TYPE>`)
twitter_type = forms.ChoiceField(
label=_("Twitter type"),
required=False,
choices=get_setting("TWITTER_TYPES"),
initial=get_setting("TWITTER_TYPE"),
)
#: Twitter site handle (default: :ref:`TWITTER_SITE <TWITTER_SITE>`)
twitter_site = forms.CharField(
max_length=200, label=_("Twitter site handle"), required=False, initial=get_setting("TWITTER_SITE")
)
#: Twitter author handle (default: :ref:`TWITTER_AUTHOR <TWITTER_AUTHOR>`)
twitter_author = forms.CharField(
max_length=200, label=_("Twitter author handle"), required=False, initial=get_setting("TWITTER_AUTHOR")
)
#: Schema.org object type (default: :ref:`SCHEMAORG_TYPE <SCHEMAORG_TYPE>`)
gplus_type = forms.ChoiceField(
label=_("Schema.org type"),
required=False,
choices=get_setting("SCHEMAORG_TYPES"),
initial=get_setting("SCHEMAORG_TYPE"),
)
#: Schema.org author name abstract field (default: :ref:`SCHEMAORG_AUTHOR <SCHEMAORG_AUTHOR>`)
gplus_author = forms.CharField(
max_length=200, label=_("Schema.org author name"), required=False, initial=get_setting("SCHEMAORG_AUTHOR")
)
#: Send notifications on post update. Require channels integration
send_knock_create = forms.BooleanField(
label=_("Send notifications on post publish"),
required=False,
initial=False,
help_text=_("Emits a desktop notification -if enabled- when publishing a new post"),
)
#: Send notifications on post update. Require channels integration
send_knock_update = forms.BooleanField(
label=_("Send notifications on post update"),
required=False,
initial=False,
help_text=_("Emits a desktop notification -if enabled- when editing a published post"),
)
setup_config(BlogConfigForm, BlogConfig)
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,822
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0019_thumbnail_move3.py
|
from django.db import migrations
from djangocms_blog.models import thumbnail_model
def move_thumbnail_opt_to_filer(apps, schema_editor):
Post = apps.get_model("djangocms_blog", "Post")
for post in Post.objects.all():
post.main_image_full_new_id = post.main_image_full_id
post.main_image_thumbnail_new_id = post.main_image_thumbnail_id
post.save()
def move_thumbnail_opt_to_plugin(apps, schema_editor):
Post = apps.get_model("djangocms_blog", "Post")
for post in Post.objects.all():
post.main_image_full_id = post.main_image_full_new_id
post.main_image_thumbnail_id = post.main_image_thumbnail_new_id
post.save()
class Migration(migrations.Migration):
if "cmsplugin_filer" not in thumbnail_model:
dependencies = [
("djangocms_blog", "0018_thumbnail_move2"),
]
operations = [
migrations.RunPython(move_thumbnail_opt_to_filer, move_thumbnail_opt_to_plugin),
]
else:
dependencies = [
("filer", "__first__"),
("cmsplugin_filer_image", "__first__"),
("djangocms_blog", "0018_thumbnail_move2"),
]
operations = []
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,823
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/liveblog/routing.py
|
from channels.routing import URLRouter
from django.urls import path
from .consumers import LiveblogConsumer
channel_routing = URLRouter([path("<str:apphook>/<str:lang>/<str:post>/", LiveblogConsumer.as_asgi())])
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,824
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0023_auto_20160626_1539.py
|
# Generated by Django 1.9.6 on 2016-06-26 13:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0022_auto_20160605_2305"),
]
operations = [
migrations.AddField(
model_name="authorentriesplugin",
name="current_site",
field=models.BooleanField(
default=True, help_text="Select items from the current site only", verbose_name="current site"
),
),
migrations.AddField(
model_name="genericblogplugin",
name="current_site",
field=models.BooleanField(
default=True, help_text="Select items from the current site only", verbose_name="current site"
),
),
migrations.AddField(
model_name="latestpostsplugin",
name="current_site",
field=models.BooleanField(
default=True, help_text="Select items from the current site only", verbose_name="current site"
),
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,825
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/tests/test_wizards.py
|
import sys
from django.http import QueryDict
from djangocms_text_ckeditor.models import Text
from djangocms_blog.models import BlogCategory
from .base import BaseTest
class WizardTest(BaseTest):
def setUp(self):
from cms.wizards.wizard_pool import wizard_pool
delete = [
"djangocms_blog",
"djangocms_blog.cms_wizards",
]
for module in delete:
if module in sys.modules:
del sys.modules[module]
wizard_pool._reset()
super().setUp()
def get_querydict(self, source):
tmp = QueryDict(mutable=True)
tmp.update(source)
tmp._mutable = False
return tmp
def test_wizard(self):
"""
Test that Blog wizard is present and contains all items
"""
from cms.wizards.wizard_pool import wizard_pool
self.get_pages()
titles = [entry.title for entry in wizard_pool.get_entries()]
self.assertTrue("New Blog" in titles)
self.assertTrue("New Article" in titles)
def test_wizard_init(self):
from cms.utils.permissions import current_user
from cms.wizards.wizard_pool import wizard_pool
from djangocms_blog.models import Post
self.get_pages()
cat_1 = BlogCategory.objects.create(name="category 1 - blog 1", app_config=self.app_config_1)
cat_2 = BlogCategory.objects.create(name="category 1 - blog 2", app_config=self.app_config_2)
self.app_config_2.app_data.config.use_placeholder = False
self.app_config_2.save()
cats = {
self.app_config_1.pk: cat_1,
self.app_config_2.pk: cat_2,
}
with current_user(self.user_staff):
wizs = [entry for entry in wizard_pool.get_entries() if entry.model == Post]
for index, wiz in enumerate(wizs):
app_config = self.app_config_1.pk if wiz.title == "New Blog" else self.app_config_2.pk
form = wiz.form()
self.assertTrue(form.initial.get("app_config", False), app_config)
self.assertTrue(form.fields["app_config"].widget.attrs["disabled"])
form = wiz.form(
data=self.get_querydict(
{
"1-title": "title{}".format(index),
"1-abstract": "abstract{}".format(index),
"1-categories": cats[app_config].pk,
"1-post_text": "Random text",
}
),
prefix=1,
)
self.assertEqual(form.default_appconfig, app_config)
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data["app_config"].pk, app_config)
instance = form.save()
self.assertEqual(instance.author, self.user_staff)
self.assertEqual(instance.post_text, "Random text")
if form.cleaned_data["app_config"].use_placeholder:
self.assertEqual(instance.content.get_plugins().filter(plugin_type="TextPlugin").count(), 1)
plugin = Text.objects.get(pk=instance.content.get_plugins().get(plugin_type="TextPlugin").pk)
self.assertEqual(plugin.body, "Random text")
else:
self.assertEqual(instance.content.get_plugins().filter(plugin_type="TextPlugin").count(), 0)
with self.settings(BLOG_AUTHOR_DEFAULT="normal"):
for index, wiz in enumerate(wizs):
app_config = self.app_config_1.pk if wiz.title == "New Blog" else self.app_config_2.pk
form = wiz.form(
data=self.get_querydict(
{
"1-title": "title-2{}".format(index),
"1-abstract": "abstract-2{}".format(index),
"1-categories": cats[app_config].pk,
}
),
prefix=1,
)
self.assertEqual(form.default_appconfig, app_config)
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data["app_config"].pk, app_config)
instance = form.save()
self.assertEqual(instance.author, self.user_normal)
self.app_config_2.app_data.config.use_placeholder = True
self.app_config_2.save()
def test_wizard_duplicate_slug(self):
from cms.utils.permissions import current_user
from cms.wizards.wizard_pool import wizard_pool
from djangocms_blog.models import Post
self.get_pages()
cat_2 = BlogCategory.objects.create(name="category 1 - blog 2", app_config=self.app_config_2)
with current_user(self.user_staff):
wiz = None
for wiz in wizard_pool.get_entries():
if wiz.model == Post and wiz.title == "New Blog":
break
form = wiz.form(
data=self.get_querydict(
{"1-title": "title article", "1-abstract": "abstract article", "1-categories": self.category_1.pk}
),
prefix=1,
)
self.assertEqual(form.default_appconfig, self.app_config_1.pk)
self.assertTrue(form.is_valid())
instance1 = form.save()
self.assertEqual(instance1.slug, "title-article")
form = wiz.form(
data=self.get_querydict(
{"1-title": "title article", "1-abstract": "abstract article", "1-categories": self.category_1.pk}
),
prefix=1,
)
self.assertEqual(form.default_appconfig, self.app_config_1.pk)
self.assertTrue(form.is_valid())
instance2 = form.save()
self.assertEqual(instance2.slug, "title-article-1")
for wiz in wizard_pool.get_entries():
if wiz.model == Post and wiz.title == "New Article":
break
form = wiz.form(
data=self.get_querydict(
{"1-title": "title article", "1-abstract": "abstract article", "1-categories": cat_2.pk}
),
prefix=1,
)
self.assertEqual(form.default_appconfig, self.app_config_2.pk)
self.assertTrue(form.is_valid())
instance3 = form.save()
self.assertEqual(instance3.slug, "title-article-2")
def test_wizard_init_categories_check(self):
from cms.utils.permissions import current_user
from cms.wizards.wizard_pool import wizard_pool
from djangocms_blog.models import Post
self.get_pages()
with current_user(self.user_staff):
wiz = None
for wiz in wizard_pool.get_entries():
if wiz.model == Post and wiz.title == "New Article":
break
form = wiz.form(
data=self.get_querydict(
{"1-title": "title article", "1-abstract": "abstract article", "1-categories": self.category_1.pk}
),
prefix=1,
)
self.assertEqual(form.default_appconfig, self.app_config_2.pk)
self.assertFalse(form.is_valid())
self.assertTrue("categories" in form.errors.keys())
def test_wizard_import(self):
# The following import should not fail in any django CMS version
pass
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,826
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/managers.py
|
from collections import Counter
from aldryn_apphooks_config.managers.parler import AppHookConfigTranslatableManager, AppHookConfigTranslatableQueryset
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.db import models
from django.utils.timezone import now
class TaggedFilterItem:
def tagged(self, other_model=None, queryset=None):
"""
Restituisce una queryset di elementi del model taggati,
o con gli stessi tag di un model o un queryset
"""
tags = self._taglist(other_model, queryset)
return self.get_queryset().filter(tags__in=tags).distinct()
def _taglist(self, other_model=None, queryset=None):
"""
Restituisce una lista di id di tag comuni al model corrente e al model
o queryset passati come argomento
"""
from taggit.models import TaggedItem
filters = None
if queryset is not None:
filters = set()
for item in queryset.all():
filters.update(item.tags.all())
filters = {tag.id for tag in filters}
elif other_model is not None:
filters = set(
TaggedItem.objects.filter(content_type__model=other_model.__name__.lower()).values_list(
"tag_id", flat=True
)
)
tags = set(
TaggedItem.objects.filter(content_type__model=self.model.__name__.lower()).values_list("tag_id", flat=True)
)
if filters is not None:
tags = tags.intersection(filters)
return list(tags)
def tag_list(self, other_model=None, queryset=None):
"""
Restituisce un queryset di tag comuni al model corrente e
al model o queryset passati come argomento
"""
from taggit.models import Tag
return Tag.objects.filter(id__in=self._taglist(other_model, queryset))
def tag_list_slug(self, other_model=None, queryset=None):
queryset = self.tag_list(other_model, queryset)
return queryset.values("slug")
def tag_cloud(self, other_model=None, queryset=None, published=True, on_site=False):
from taggit.models import TaggedItem
if on_site:
queryset = queryset.on_site()
tag_ids = self._taglist(other_model, queryset)
kwargs = {}
if published:
kwargs = {
"object_id__in": self.model.objects.published(),
"content_type": ContentType.objects.get_for_model(self.model),
}
kwargs["tag_id__in"] = tag_ids
counted_tags = dict(
TaggedItem.objects.filter(**kwargs)
.values("tag")
.annotate(count=models.Count("tag"))
.values_list("tag", "count")
)
tags = TaggedItem.tag_model().objects.filter(pk__in=counted_tags.keys())
for tag in tags:
tag.count = counted_tags[tag.pk]
return sorted(tags, key=lambda x: -x.count)
class GenericDateQuerySet(AppHookConfigTranslatableQueryset):
start_date_field = "date_published"
fallback_date_field = "date_modified"
end_date_field = "date_published_end"
publish_field = "publish"
def on_site(self, site=None):
if not site:
site = Site.objects.get_current()
return self.filter(models.Q(sites__isnull=True) | models.Q(sites=site.pk))
def published(self, current_site=True):
queryset = self.published_future(current_site)
if self.start_date_field:
return queryset.filter(**{"%s__lte" % self.start_date_field: now()})
else:
return queryset
def published_on_rss(self, current_site=True):
queryset = self.published_future(current_site)
return queryset.exclude(include_in_rss=False)
def published_future(self, current_site=True):
if current_site:
queryset = self.on_site()
else:
queryset = self
if self.end_date_field:
qfilter = models.Q(**{"%s__gte" % self.end_date_field: now()}) | models.Q(
**{"%s__isnull" % self.end_date_field: True}
)
queryset = queryset.filter(qfilter)
return queryset.filter(**{self.publish_field: True})
def archived(self, current_site=True):
if current_site:
queryset = self.on_site()
else:
queryset = self
if self.end_date_field:
qfilter = models.Q(**{"%s__lte" % self.end_date_field: now()})
queryset = queryset.filter(qfilter)
return queryset.filter(**{self.publish_field: True})
def available(self, current_site=True):
if current_site:
return self.on_site().filter(**{self.publish_field: True})
else:
return self.filter(**{self.publish_field: True})
def filter_by_language(self, language, current_site=True):
if current_site:
return self.active_translations(language_code=language).on_site()
else:
return self.active_translations(language_code=language)
class GenericDateTaggedManager(TaggedFilterItem, AppHookConfigTranslatableManager):
use_for_related_fields = True
queryset_class = GenericDateQuerySet
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs)
def published(self, current_site=True):
return self.get_queryset().published(current_site)
def published_on_rss(self, current_site=True):
return self.get_queryset().published_on_rss(current_site)
def available(self, current_site=True):
return self.get_queryset().available(current_site)
def archived(self, current_site=True):
return self.get_queryset().archived(current_site)
def published_future(self, current_site=True):
return self.get_queryset().published_future(current_site)
def filter_by_language(self, language, current_site=True):
return self.get_queryset().filter_by_language(language, current_site)
def on_site(self, site=None):
return self.get_queryset().on_site(site)
def get_months(self, queryset=None, current_site=True):
"""
Get months with aggregate count (how much posts is in the month).
Results are ordered by date.
"""
if queryset is None:
queryset = self.get_queryset()
if current_site:
queryset = queryset.on_site()
dates_qs = queryset.values_list(queryset.start_date_field, queryset.fallback_date_field)
dates = []
for blog_dates in dates_qs:
if blog_dates[0]:
current_date = blog_dates[0]
else:
current_date = blog_dates[1]
dates.append(
(
current_date.year,
current_date.month,
)
)
date_counter = Counter(dates)
dates = set(dates)
dates = sorted(dates, reverse=True)
return [
{"date": now().replace(year=year, month=month, day=1), "count": date_counter[year, month]}
for year, month in dates
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,827
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0022_auto_20160605_2305.py
|
# Generated by Django 1.9.7 on 2016-06-05 21:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0021_post_liveblog"),
]
operations = [
migrations.AddField(
model_name="post",
name="enable_liveblog",
field=models.BooleanField(default=False, verbose_name="enable liveblog on post"),
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,828
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/admin.py
|
from copy import deepcopy
from aldryn_apphooks_config.admin import BaseAppHookConfig, ModelAppHookConfig
from cms.admin.placeholderadmin import FrontendEditableAdminMixin, PlaceholderAdminMixin
from cms.models import CMSPlugin, ValidationError
from django.apps import apps
from django.conf import settings
from django.contrib import admin, messages
from django.contrib.admin.options import InlineModelAdmin
from django.contrib.sites.models import Site
from django.db import models
from django.db.models import signals
from django.http import HttpResponseRedirect
from django.urls import path, reverse
from django.utils import timezone
from django.utils.translation import get_language_from_request, gettext_lazy as _, ngettext as __
from parler.admin import TranslatableAdmin
from .cms_appconfig import BlogConfig
from .forms import CategoryAdminForm, PostAdminForm
from .models import BlogCategory, Post
from .settings import get_setting
signal_dict = {}
def register_extension(klass):
if issubclass(klass, InlineModelAdmin):
PostAdmin.inlines = type(PostAdmin.inlines)([klass]) + PostAdmin.inlines
return
if issubclass(klass, models.Model):
if klass in signal_dict:
raise Exception("Can not register {} twice.".format(klass))
signal_dict[klass] = create_post_post_save(klass)
signals.post_save.connect(signal_dict[klass], sender=Post, weak=False)
return
raise Exception("Can not register {} type. You can only register a Model or a TabularInline.".format(klass))
def unregister_extension(klass):
if issubclass(klass, InlineModelAdmin):
PostAdmin.inlines.remove(klass)
return
if issubclass(klass, models.Model):
if klass not in signal_dict:
raise Exception("Can not unregister {}. No signal found for this class.".format(klass))
signals.post_save.disconnect(signal_dict[klass], sender=Post)
del signal_dict[klass]
return
raise Exception("Can not unregister {} type. You can only unregister a Model or a TabularInline.".format(klass))
def create_post_post_save(model):
"""A wrapper for creating create_instance function for a specific model."""
def create_instance(sender, instance, created, **kwargs):
"""Create Model instance for every new Post."""
if created:
model.objects.create(post=instance)
return create_instance
class SiteListFilter(admin.SimpleListFilter):
title = _("site")
parameter_name = "sites"
def lookups(self, request, model_admin):
restricted_sites = model_admin.get_restricted_sites(request).values_list("id", flat=True)
qs = Site.objects.all()
if restricted_sites:
qs = qs.filter(id__in=restricted_sites)
return [(site.id, str(site.name)) for site in qs]
def queryset(self, request, queryset):
try:
if "sites" in self.used_parameters:
return queryset.on_site(Site.objects.get(pk=self.used_parameters["sites"]))
return queryset
except Site.DoesNotExist as e: # pragma: no cover
raise admin.options.IncorrectLookupParameters(e)
except ValidationError as e: # pragma: no cover
raise admin.options.IncorrectLookupParameters(e)
@admin.register(BlogCategory)
class BlogCategoryAdmin(ModelAppHookConfig, TranslatableAdmin):
form = CategoryAdminForm
list_display = [
"name",
"parent",
"app_config",
"all_languages_column",
]
def get_prepopulated_fields(self, request, obj=None):
app_config_default = self._app_config_select(request, obj)
if app_config_default is None and request.method == "GET":
return {}
return {"slug": ("name",)}
class Media:
css = {"all": ("{}djangocms_blog/css/{}".format(settings.STATIC_URL, "djangocms_blog_admin.css"),)}
@admin.register(Post)
class PostAdmin(PlaceholderAdminMixin, FrontendEditableAdminMixin, ModelAppHookConfig, TranslatableAdmin):
form = PostAdminForm
list_display = ["title", "author", "date_published", "app_config", "all_languages_column", "date_published_end"]
search_fields = ("translations__title",)
date_hierarchy = "date_published"
raw_id_fields = ["author"]
frontend_editable_fields = ("title", "abstract", "post_text")
enhance_exclude = ("main_image", "tags")
actions = [
"make_published",
"make_unpublished",
"enable_comments",
"disable_comments",
]
inlines = []
if apps.is_installed("djangocms_blog.liveblog"):
actions += ["enable_liveblog", "disable_liveblog"]
_fieldsets = [
(None, {"fields": ["title", "subtitle", "slug", "publish", "include_in_rss", ["categories", "app_config"]]}),
# left empty for sites, author and related fields
(None, {"fields": [[]]}),
(
_("Info"),
{
"fields": ["tags", ["date_published", "date_published_end", "date_featured"], ["enable_comments"]],
"classes": ("collapse",),
},
),
(
_("Images"),
{"fields": [["main_image", "main_image_thumbnail", "main_image_full"]], "classes": ("collapse",)},
),
(_("SEO"), {"fields": [["meta_description", "meta_title", "meta_keywords"]], "classes": ("collapse",)}),
]
"""
Default fieldsets structure.
Follow the normal Django fieldsets syntax.
When customizing the structure, check the :py:attr:`_fieldset_extra_fields_position` to ensure extra fields
position matches.
"""
_fieldset_extra_fields_position = {
"abstract": (0, 1),
"post_text": (0, 1),
"sites": (1, 1, 0),
"author": (1, 1, 0),
"enable_liveblog": (2, 1, 2),
"related": (1, 1, 0),
}
"""
Indexes where to append extra fields.
Key: Supported extra / optional field name
Value: None / 2 / 3 item tuple. If you want to hide the field in any case set ``None`` as dictionary value,
otherwise use a tuple containing the index of the the "fields" attribute of the selected fieldset row and
an optional third value if the target "fields" has subgroups.
"""
app_config_values = {"default_published": "publish"}
_sites = None
# Bulk actions for post admin
@admin.action(description=_("Publish selection"))
def make_published(self, request, queryset):
"""
Bulk action to mark selected posts as published.
If the date_published field is empty the current time is saved as date_published.
queryset must not be empty (ensured by django CMS).
"""
cnt1 = queryset.filter(
date_published__isnull=True,
publish=False,
).update(date_published=timezone.now(), publish=True)
cnt2 = queryset.filter(
date_published__isnull=False,
publish=False,
).update(publish=True)
messages.add_message(
request,
messages.INFO,
__("%(updates)d entry published.", "%(updates)d entries published.", cnt1 + cnt2)
% {"updates": cnt1 + cnt2},
)
@admin.action(description=_("Unpublish selection"))
def make_unpublished(self, request, queryset):
"""
Bulk action to mark selected posts as unpublished.
queryset must not be empty (ensured by django CMS).
"""
updates = queryset.filter(publish=True).update(publish=False)
messages.add_message(
request,
messages.INFO,
__("%(updates)d entry unpublished.", "%(updates)d entries unpublished.", updates) % {"updates": updates},
)
@admin.action(description=_("Enable comments for selection"))
def enable_comments(self, request, queryset):
"""
Bulk action to enable comments for selected posts.
queryset must not be empty (ensured by django CMS).
"""
updates = queryset.filter(enable_comments=False).update(enable_comments=True)
messages.add_message(
request,
messages.INFO,
__("Comments for %(updates)d entry enabled.", "Comments for %(updates)d entries enabled", updates)
% {"updates": updates},
)
@admin.action(description=_("Disable comments for selection "))
def disable_comments(self, request, queryset):
"""
Bulk action to disable comments for selected posts.
queryset must not be empty (ensured by django CMS).
"""
updates = queryset.filter(enable_comments=True).update(enable_comments=False)
messages.add_message(
request,
messages.INFO,
__("Comments for %(updates)d entry disabled.", "Comments for %(updates)d entries disabled.", updates)
% {"updates": updates},
)
@admin.action(description=_("Enable liveblog for selection"))
def enable_liveblog(self, request, queryset):
"""
Bulk action to enable comments for selected posts.
queryset must not be empty (ensured by django CMS).
"""
updates = queryset.filter(enable_liveblog=False).update(enable_liveblog=True)
messages.add_message(
request,
messages.INFO,
__("Liveblog for %(updates)d entry enabled.", "Liveblog for %(updates)d entries enabled.", updates)
% {"updates": updates},
)
@admin.action(description=_("Disable liveblog for selection "))
def disable_liveblog(self, request, queryset):
"""
Bulk action to disable comments for selected posts.
queryset must not be empty (ensured by django CMS).
"""
updates = queryset.filter(enable_liveblog=True).update(enable_liveblog=False)
messages.add_message(
request,
messages.INFO,
__("Liveblog for %(updates)d entry enabled.", "Liveblog for %(updates)d entries enabled.")
% {"updates": updates},
)
# Make bulk action menu entries localizable
def get_list_filter(self, request):
filters = ["app_config", "publish", "date_published"]
if get_setting("MULTISITE"):
filters.append(SiteListFilter)
try:
from taggit_helpers.admin import TaggitListFilter
filters.append(TaggitListFilter)
except ImportError: # pragma: no cover
try:
from taggit_helpers import TaggitListFilter
filters.append(TaggitListFilter)
except ImportError:
pass
return filters
def get_urls(self):
"""
Customize the modeladmin urls
"""
urls = [
path(
"publish/<int:pk>/",
self.admin_site.admin_view(self.publish_post),
name="djangocms_blog_publish_article",
),
]
urls.extend(super().get_urls())
return urls
def post_add_plugin(self, request, obj1, obj2=None):
if isinstance(obj1, CMSPlugin):
plugin = obj1
elif isinstance(obj2, CMSPlugin):
plugin = obj2
if plugin.plugin_type in get_setting("LIVEBLOG_PLUGINS"):
plugin = plugin.move(plugin.get_siblings().first(), "first-sibling")
if isinstance(obj1, CMSPlugin):
return super().post_add_plugin(request, plugin)
elif isinstance(obj2, CMSPlugin):
return super().post_add_plugin(request, obj1, plugin)
def publish_post(self, request, pk):
"""
Admin view to publish a single post
:param request: request
:param pk: primary key of the post to publish
:return: Redirect to the post itself (if found) or fallback urls
"""
language = get_language_from_request(request, check_path=True)
try:
post = Post.objects.get(pk=int(pk))
post.publish = True
post.save()
return HttpResponseRedirect(post.get_absolute_url(language))
except Exception:
try:
return HttpResponseRedirect(request.headers["referer"])
except KeyError:
return HttpResponseRedirect(reverse("djangocms_blog:posts-latest"))
def has_restricted_sites(self, request):
"""
Whether the current user has permission on one site only
:param request: current request
:return: boolean: user has permission on only one site
"""
sites = self.get_restricted_sites(request)
return sites and sites.count() == 1
def get_restricted_sites(self, request):
"""
The sites on which the user has permission on.
To return the permissions, the method check for the ``get_sites``
method on the user instance (e.g.: ``return request.user.get_sites()``)
which must return the queryset of enabled sites.
If the attribute does not exists, the user is considered enabled
for all the websites.
:param request: current request
:return: boolean or a queryset of available sites
"""
try:
return request.user.get_sites()
except AttributeError: # pragma: no cover
return Site.objects.none()
def _set_config_defaults(self, request, form, obj=None):
form = super()._set_config_defaults(request, form, obj)
sites = self.get_restricted_sites(request)
if "sites" in form.base_fields and sites.exists():
form.base_fields["sites"].queryset = self.get_restricted_sites(request).all()
return form
def _get_available_posts(self, config):
if config:
return self.model.objects.namespace(config.namespace).active_translations().exists()
return []
def get_fieldsets(self, request, obj=None):
"""
Customize the fieldsets according to the app settings
:param request: request
:param obj: post
:return: fieldsets configuration
"""
app_config_default = self._app_config_select(request, obj)
if app_config_default is None and request.method == "GET":
return super().get_fieldsets(request, obj)
if not obj:
config = app_config_default
else:
config = obj.app_config
fsets = deepcopy(self._fieldsets)
related_posts = []
if config:
abstract = bool(config.use_abstract)
placeholder = bool(config.use_placeholder)
related = bool(config.use_related)
else:
abstract = get_setting("USE_ABSTRACT")
placeholder = get_setting("USE_PLACEHOLDER")
related = get_setting("USE_RELATED")
if related:
related_posts = self._get_available_posts(config)
if abstract:
self._patch_fieldsets(fsets, "abstract")
if not placeholder:
self._patch_fieldsets(fsets, "post_text")
if get_setting("MULTISITE") and not self.has_restricted_sites(request):
self._patch_fieldsets(fsets, "sites")
if request.user.is_superuser:
self._patch_fieldsets(fsets, "author")
if apps.is_installed("djangocms_blog.liveblog"):
self._patch_fieldsets(fsets, "enable_liveblog")
filter_function = get_setting("ADMIN_POST_FIELDSET_FILTER")
if related_posts:
self._patch_fieldsets(fsets, "related")
if callable(filter_function):
fsets = filter_function(fsets, request, obj=obj)
return fsets
def _patch_fieldsets(self, fsets, field):
"""Patch the fieldsets list with additional fields, based on :py:attr:`_fieldset_extra_fields_position`."""
positions = self._get_extra_field_position(field)
if not positions or len(positions) not in (2, 3) or not all(True for i in positions[:2] if i is not None):
return fsets
if len(positions) == 2 or positions[2] is None:
fsets[positions[0]][positions[1]]["fields"].append(field)
elif len(positions) == 3:
fsets[positions[0]][positions[1]]["fields"][positions[2]].append(field)
return fsets
def _get_extra_field_position(self, field):
"""Return the position in the fieldset where to add the given field."""
return self._fieldset_extra_fields_position.get(field, (None, None, None))
def get_prepopulated_fields(self, request, obj=None):
return {"slug": ("title",)}
def save_model(self, request, obj, form, change):
obj._set_default_author(request.user)
super().save_model(request, obj, form, change)
def get_queryset(self, request):
qs = super().get_queryset(request)
sites = self.get_restricted_sites(request)
if sites.exists():
pks = list(sites.all().values_list("pk", flat=True))
qs = qs.filter(sites__in=pks)
# can't use distinct here because it prevents deleting records, but we need a unique list of posts because
# filters can cause duplicates
return super().get_queryset(request).filter(pk__in=qs.values_list("pk", flat=True))
def save_related(self, request, form, formsets, change):
if self.get_restricted_sites(request).exists():
if "sites" in form.cleaned_data:
form_sites = form.cleaned_data.get("sites", [])
removed = set(self.get_restricted_sites(request).all()).difference(form_sites)
diff_original = set(form.instance.sites.all()).difference(removed).union(form_sites)
form.cleaned_data["sites"] = diff_original
else:
form.instance.sites.add(*self.get_restricted_sites(request).all().values_list("pk", flat=True))
super().save_related(request, form, formsets, change)
class Media:
css = {"all": ("{}djangocms_blog/css/{}".format(settings.STATIC_URL, "djangocms_blog_admin.css"),)}
@admin.register(BlogConfig)
class BlogConfigAdmin(BaseAppHookConfig, TranslatableAdmin):
@property
def declared_fieldsets(self):
return self.get_fieldsets(None)
def get_fieldsets(self, request, obj=None):
"""
Fieldsets configuration
"""
return [
(None, {"fields": ("type", "namespace", "app_title", "object_name")}),
(
_("Generic"),
{
"fields": (
"config.default_published",
"config.use_placeholder",
"config.use_abstract",
"config.set_author",
"config.use_related",
)
},
),
(
_("Layout"),
{
"fields": (
"config.paginate_by",
"config.url_patterns",
"config.template_prefix",
"config.menu_structure",
"config.menu_empty_categories",
("config.default_image_full", "config.default_image_thumbnail"),
),
"classes": ("collapse",),
},
),
(
_("Notifications"),
{"fields": ("config.send_knock_create", "config.send_knock_update"), "classes": ("collapse",)},
),
(
_("Sitemap"),
{
"fields": (
"config.sitemap_changefreq",
"config.sitemap_priority",
),
"classes": ("collapse",),
},
),
(_("Meta"), {"fields": ("config.object_type",)}),
(
"Open Graph",
{
"fields": (
"config.og_type",
"config.og_app_id",
"config.og_profile_id",
"config.og_publisher",
"config.og_author_url",
"config.og_author",
),
"description": _("You can provide plain strings, Post model attribute or method names"),
},
),
(
"Twitter",
{
"fields": (
"config.twitter_type",
"config.twitter_site",
"config.twitter_author",
),
"description": _("You can provide plain strings, Post model attribute or method names"),
},
),
(
"Schema.org",
{
"fields": (
"config.gplus_type",
"config.gplus_author",
),
"description": _("You can provide plain strings, Post model attribute or method names"),
},
),
]
def save_model(self, request, obj, form, change):
"""
Clear menu cache when changing menu structure
"""
if "config.menu_structure" in form.changed_data:
from menus.menu_pool import menu_pool
menu_pool.clear(all=True)
return super().save_model(request, obj, form, change)
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,829
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0009_latestpostsplugin_tags_new.py
|
import taggit_autosuggest.managers
from django.contrib.contenttypes.models import ContentType
from django.db import migrations
def migrate_tags(apps, schema_editor):
LatestPostsPlugin = apps.get_model("djangocms_blog", "LatestPostsPlugin")
Tag = apps.get_model("taggit", "Tag")
TaggedItem = apps.get_model("taggit", "TaggedItem")
plugin_content_type = ContentType.objects.get_for_model(LatestPostsPlugin)
for tag in Tag.objects.all():
for plugin in tag.latestpostsplugin_set.all():
if not TaggedItem.objects.filter(
tag=tag, object_id=plugin.pk, content_type_id=plugin_content_type.pk
).exists():
TaggedItem.objects.create(tag=tag, object_id=plugin.pk, content_type_id=plugin_content_type.pk)
def migrate_tags_reverse(apps, schema_editor):
LatestPostsPlugin = apps.get_model("djangocms_blog", "LatestPostsPlugin")
apps.get_model("taggit", "Tag")
TaggedItem = apps.get_model("taggit", "TaggedItem")
plugin_content_type = ContentType.objects.get_for_model(LatestPostsPlugin)
for tagged in TaggedItem.objects.filter(content_type_id=plugin_content_type.pk):
post = LatestPostsPlugin.objects.get(pk=tagged.object_id)
post.tags.add(tagged.tag)
tagged.delete()
class Migration(migrations.Migration):
dependencies = [
("taggit", "__first__"),
("djangocms_blog", "0008_auto_20150814_0831"),
]
operations = [
migrations.AddField(
model_name="latestpostsplugin",
name="tags_new",
field=taggit_autosuggest.managers.TaggableManager(
to="taggit.Tag",
through="taggit.TaggedItem",
blank=True,
help_text="Show only the blog articles tagged with chosen tags.",
verbose_name="filter by tag",
),
preserve_default=True,
),
migrations.RunPython(migrate_tags, migrate_tags_reverse),
migrations.RemoveField(
model_name="latestpostsplugin",
name="tags",
),
migrations.RenameField(
model_name="latestpostsplugin",
old_name="tags_new",
new_name="tags",
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,830
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/cms_apps.py
|
from aldryn_apphooks_config.app_base import CMSConfigApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import gettext_lazy as _
from djangocms_apphook_setup.base import AutoCMSAppMixin
from .cms_appconfig import BlogConfig
from .cms_menus import BlogCategoryMenu
from .settings import get_setting
@apphook_pool.register
class BlogApp(AutoCMSAppMixin, CMSConfigApp):
name = _("Blog")
_urls = [get_setting("URLCONF")]
app_name = "djangocms_blog"
app_config = BlogConfig
_menus = [BlogCategoryMenu]
auto_setup = {
"enabled": get_setting("AUTO_SETUP"),
"home title": get_setting("AUTO_HOME_TITLE"),
"page title": get_setting("AUTO_BLOG_TITLE"),
"namespace": get_setting("AUTO_NAMESPACE"),
"config_fields": {},
"config_translated_fields": {
"app_title": get_setting("AUTO_APP_TITLE"),
"object_name": get_setting("DEFAULT_OBJECT_NAME"),
},
}
def get_urls(self, page=None, language=None, **kwargs):
return [get_setting("URLCONF")]
@property
def urls(self):
return self.get_urls()
@property
def menus(self):
return self._menus
BlogApp.setup()
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,831
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/settings.py
|
"""
List of settings that can be set in project django settings.
"""
from django.utils.translation import gettext_lazy as _
from meta import settings as meta_settings
MENU_TYPE_COMPLETE = "complete"
MENU_TYPE_CATEGORIES = "categories"
MENU_TYPE_POSTS = "posts"
MENU_TYPE_NONE = "none"
DATE_FORMAT = "%a %d %b %Y %H:%M"
PERMALINK_TYPE_FULL_DATE = "full_date"
PERMALINK_TYPE_SHORT_DATE = "short_date"
PERMALINK_TYPE_CATEGORY = "category"
PERMALINK_TYPE_SLUG = "slug"
BLOG_DEFAULT_PUBLISHED = False
"""
.. _DEFAULT_PUBLISHED:
Default post published status.
"""
PERMALINKS = ( # noqa
(PERMALINK_TYPE_FULL_DATE, _("Full date")),
(PERMALINK_TYPE_SHORT_DATE, _("Year / Month")),
(PERMALINK_TYPE_CATEGORY, _("Category")),
(PERMALINK_TYPE_SLUG, _("Just slug")),
)
"""
.. _PERMALINKS:
Permalinks styles.
"""
BLOG_UNICODE_SLUGS = True
"""
.. _UNICODE_SLUGS:
Allow unicode chars in auto-generated slugs.
"""
PERMALINKS_URLS = { # noqa
PERMALINK_TYPE_FULL_DATE: "<int:year>/<int:month>/<int:day>/<str:slug>/",
PERMALINK_TYPE_SHORT_DATE: "<int:year>/<int:month>/<str:slug>/",
PERMALINK_TYPE_CATEGORY: "<str:category>/<str:slug>/",
PERMALINK_TYPE_SLUG: "<str:slug>/",
}
"""
.. _PERMALINKS_URLS:
Permalinks urlconfs.
"""
MENU_TYPES = ( # noqa
(MENU_TYPE_COMPLETE, _("Categories and posts")),
(MENU_TYPE_CATEGORIES, _("Categories only")),
(MENU_TYPE_POSTS, _("Posts only")),
(MENU_TYPE_NONE, _("None")),
)
"""
.. _DEFAULT_MENU_TYPES:
Types of menu structure.
"""
SITEMAP_CHANGEFREQ_LIST = ( # noqa
("always", _("always")),
("hourly", _("hourly")),
("daily", _("daily")),
("weekly", _("weekly")),
("monthly", _("monthly")),
("yearly", _("yearly")),
("never", _("never")),
)
"""
.. _SITEMAP_CHANGEFREQ_LIST:
List of changefreqs defined in sitemaps.
"""
BLOG_IMAGE_THUMBNAIL_SIZE = {"size": "120x120", "crop": True, "upscale": False}
"""
.. _IMAGE_THUMBNAIL_SIZE:
Easy-thumbnail alias configuration for the post main image when shown on the post lists;
it's a dictionary with ``size``, ``crop`` and ``upscale`` keys.
"""
BLOG_IMAGE_FULL_SIZE = {"size": "640", "crop": True, "upscale": False}
"""
.. _IMAGE_FULL_SIZE:
Easy-thumbnail alias configuration for the post main image when shown on the post detail;
it's a dictionary with ``size``, ``crop`` and ``upscale`` keys.
"""
BLOG_META_IMAGE_SIZE = None
"""
.. _META_IMAGE_SIZE:
Easy-thumbnail alias configuration for the post meta image;
it's a dictionary with ``size``, ``crop`` and ``upscale`` keys.
Recommended values are {"size": (1200, 630), "crop": True, "upscale": False}
"""
BLOG_URLCONF = "djangocms_blog.urls"
"""
.. _URLCONF:
Standard Apphook URLConf.
"""
BLOG_PAGINATION = 10
"""
.. _PAGINATION:
Number of post per page.
"""
BLOG_LATEST_POSTS = 5
"""
.. _LATEST_POSTS:
Default number of post in the **Latest post** plugin.
"""
BLOG_POSTS_LIST_TRUNCWORDS_COUNT = 100
"""
.. _POSTS_LIST_TRUNCWORDS_COUNT:
Default number of words shown for abstract in the post list.
"""
BLOG_META_DESCRIPTION_LENGTH = 320
"""
.. _META_DESCRIPTION_LENGTH:
Maximum length for the Meta description field.
"""
BLOG_META_TITLE_LENGTH = 70
"""
.. _META_TITLE_LENGTH:
Maximum length for the Meta title field.
"""
BLOG_MENU_TYPES = MENU_TYPES
"""
.. _MENU_TYPES:
List of available menu types.
"""
BLOG_MENU_EMPTY_CATEGORIES = True
"""
.. _MENU_EMPTY_CATEGORIES:
Flag to show / hide categories without posts attached from the menu.
"""
BLOG_TYPE = "Article"
"""
.. _TYPE:
Generic type for the post object.
"""
BLOG_TYPES = meta_settings.OBJECT_TYPES
"""
.. _TYPES:
Choices of available blog types.
Available values are defined in to ``META_OBJECT_TYPES`` defined in `django-meta settings`_.
"""
BLOG_FB_TYPE = "Article"
"""
.. _FB_TYPE:
Open Graph type for the post object.
"""
BLOG_FB_TYPES = meta_settings.FB_TYPES
"""
.. _FB_TYPES:
Choices of available blog types.
Available values are defined in to ``META_FB_TYPES`` defined in `django-meta settings`_.
"""
BLOG_FB_APPID = meta_settings.FB_APPID
"""
.. _FB_APPID:
Facebook Application ID.
Default from ``FB_APPID`` defined in `django-meta settings`_.
"""
BLOG_FB_PROFILE_ID = meta_settings.FB_PROFILE_ID
"""
.. _FB_PROFILE_ID:
Facebook profile ID of the post author.
Default from ``FB_PROFILE_ID`` defined in `django-meta settings`_.
"""
BLOG_FB_PUBLISHER = meta_settings.FB_PUBLISHER
"""
.. _FB_PUBLISHER:
Facebook URL of the blog publisher.
Default from ``FB_PUBLISHER`` defined in `django-meta settings`_.
"""
BLOG_FB_AUTHOR_URL = "get_author_url"
"""
.. _FB_AUTHOR_URL:
Facebook profile URL of the post author.
"""
BLOG_FB_AUTHOR = "get_author_name"
"""
.. _FB_AUTHOR:
Facebook profile URL of the post author.
"""
BLOG_TWITTER_TYPE = "summary"
"""
.. _TWITTER_TYPE:
Twitter Card type for the post object.
"""
BLOG_TWITTER_TYPES = meta_settings.TWITTER_TYPES
"""
.. _TWITTER_TYPES:
Choices of available blog types for twitter.
Default from ``TWITTER_TYPES`` defined in `django-meta settings`_.
"""
BLOG_TWITTER_SITE = meta_settings.TWITTER_SITE
"""
.. _TWITTER_SITE:
Twitter account of the site.
Default from ``TWITTER_SITE`` defined in `django-meta settings`_.
"""
BLOG_TWITTER_AUTHOR = "get_author_twitter"
"""
.. _TWITTER_AUTHOR:
Twitter account of the post author.
"""
BLOG_SCHEMAORG_TYPE = "Blog"
"""
.. _SCHEMAORG_TYPE:
Schema.org type for the post object.
"""
BLOG_SCHEMAORG_TYPES = meta_settings.SCHEMAORG_TYPES
"""
.. _SCHEMAORG_TYPES:
Choices of available Schema.org types.
Default from ``SCHEMAORG_TYPES`` defined in `django-meta settings`_.
"""
BLOG_SCHEMAORG_AUTHOR = "get_author_schemaorg"
"""
.. _SCHEMAORG_AUTHOR:
Google+ account of the post author (deprecated).
"""
BLOG_ENABLE_COMMENTS = True
"""
.. _ENABLE_COMMENTS:
Whether to enable comments by default on posts
While ``djangocms_blog`` does not ship any comment system, this flag
can be used to control the chosen comments framework.
"""
BLOG_USE_ABSTRACT = True
"""
.. _USE_ABSTRACT:
Use an abstract field for the post.
If ``False`` no abstract field is available for posts.
"""
BLOG_USE_PLACEHOLDER = True
"""
.. _USE_PLACEHOLDER:
Post content is managed via placeholder
If ``False`` a HTMLField is provided instead.
"""
BLOG_USE_RELATED = True
"""
.. _USE_RELATED:
Enable related posts to link one post to others.
"""
BLOG_MULTISITE = True
"""
.. _MULTISITE:
Add support for multisite setup.
"""
BLOG_AUTHOR_DEFAULT = True
"""
.. _AUTHOR_DEFAULT:
Use a default if not specified:
* ``True``: the current user is set as the default author;
* ``False``: no default author is set;
* any other string: the user with the provided username is used;
"""
BLOG_ADMIN_POST_FIELDSET_FILTER = False
"""
.. _ADMIN_POST_FIELDSET_FILTER:
Callable function to change (add or filter) fields to fieldsets for admin post edit form.
See :ref:`admin_filter_function` for more details.
"""
BLOG_AVAILABLE_PERMALINK_STYLES = PERMALINKS
"""
.. _AVAILABLE_PERMALINK_STYLES:
Choices of permalinks styles.
"""
BLOG_PERMALINK_URLS = PERMALINKS_URLS
"""
.. _PERMALINK_URLS:
URLConf corresponding to :ref:`BLOG_AVAILABLE_PERMALINK_STYLES <AVAILABLE_PERMALINK_STYLES>`.
"""
BLOG_DEFAULT_OBJECT_NAME = "Article"
"""
.. _DEFAULT_OBJECT_NAME:
Default label for Blog item (used in django CMS Wizard).
"""
BLOG_AUTO_SETUP = True
"""
.. _AUTO_SETUP:
Enable the blog :ref:`auto_setup` feature.
"""
BLOG_AUTO_HOME_TITLE = "Home"
"""
.. _AUTO_HOME_TITLE:
Title of the home page created by :ref:`auto_setup`.
"""
BLOG_AUTO_BLOG_TITLE = "Blog"
"""
.. _AUTO_BLOG_TITLE:
Title of the blog page created by :ref:`auto_setup`.
"""
BLOG_AUTO_APP_TITLE = "Blog"
"""
.. _AUTO_APP_TITLE:
Title of the ``BlogConfig`` instance created by :ref:`auto_setup`.
"""
BLOG_AUTO_NAMESPACE = "Blog"
"""
.. _AUTO_NAMESPACE:
Namespace of the ``BlogConfig`` instance created by :ref:`auto_setup`.
"""
BLOG_SITEMAP_PRIORITY_DEFAULT = "0.5"
"""
.. _SITEMAP_PRIORITY_DEFAULT:
Default priority for sitemap items.
"""
BLOG_SITEMAP_CHANGEFREQ = SITEMAP_CHANGEFREQ_LIST
"""
.. _SITEMAP_CHANGEFREQ:
List for available changefreqs for sitemap items.
"""
BLOG_SITEMAP_CHANGEFREQ_DEFAULT = "monthly"
"""
.. _SITEMAP_CHANGEFREQ_DEFAULT:
Default changefreq for sitemap items.
"""
BLOG_ABSTRACT_CKEDITOR = True
"""
.. _ABSTRACT_CKEDITOR:
Configuration for the CKEditor of the abstract field.
See https://github.com/divio/djangocms-text-ckeditor/#customizing-htmlfield-editor for details.
"""
BLOG_POST_TEXT_CKEDITOR = True
"""
.. _POST_TEXT_CKEDITOR:
Configuration for the CKEditor of the post content field.
See https://github.com/divio/djangocms-text-ckeditor/#customizing-htmlfield-editor for details.
"""
BLOG_ENABLE_SEARCH = True
"""
.. _ENABLE_SEARCH:
Enable ``aldryn-search`` (i.e.: ``django-haystack``) indexes.
"""
BLOG_CURRENT_POST_IDENTIFIER = "djangocms_post_current"
"""
.. _CURRENT_POST_IDENTIFIER:
Current post identifier in request.
Name of the request attribute used in :py:class:`djangocms_blog.cms_toolbars.BlogToolbar` to detect if
request match a post detail.
"""
BLOG_CURRENT_NAMESPACE = "djangocms_post_current_config"
"""
.. _CURRENT_NAMESPACE:
Current post config identifier in request.
Name of the request attribute used in :py:class:`djangocms_blog.cms_toolbars.BlogToolbar` to detect the
current apphook namespace.
"""
BLOG_ENABLE_THROUGH_TOOLBAR_MENU = False
"""
.. _ENABLE_THROUGH_TOOLBAR_MENU:
Show djangocms-blog toolbar in any page, even when outside the blog apphooks.
"""
BLOG_PLUGIN_MODULE_NAME = _("Blog")
"""
.. _PLUGIN_MODULE_NAME:
Name of the djangocms-blog plugins module (group).
"""
BLOG_LATEST_ENTRIES_PLUGIN_NAME = _("Latest Blog Articles")
"""
.. _LATEST_ENTRIES_PLUGIN_NAME:
Name of the plugin showing the list of latest posts.
"""
BLOG_LATEST_ENTRIES_PLUGIN_NAME_CACHED = _("Latest Blog Articles - Cache")
"""
.. _LATEST_ENTRIES_PLUGIN_NAME_CACHED:
Name of the plugin showing the list of latest posts (cached version).
"""
BLOG_AUTHOR_POSTS_PLUGIN_NAME = _("Author Blog Articles")
"""
.. _AUTHOR_POSTS_PLUGIN_NAME:
Name of the plugin showing the list of blog posts authors.
"""
BLOG_AUTHOR_POSTS_LIST_PLUGIN_NAME = _("Author Blog Articles List")
"""
.. _AUTHOR_POSTS_LIST_PLUGIN_NAME:
Name of the plugin showing the list of posts per authors.
"""
BLOG_TAGS_PLUGIN_NAME = _("Tags")
"""
.. _TAGS_PLUGIN_NAME:
Name of the plugin showing the tag blog cloud.
"""
BLOG_CATEGORY_PLUGIN_NAME = _("Categories")
"""
.. _CATEGORY_PLUGIN_NAME:
Name of the plugin showing the list of blog categories.
"""
BLOG_ARCHIVE_PLUGIN_NAME = _("Archive")
"""
.. _ARCHIVE_PLUGIN_NAME:
Name of the plugin showing the blog archive index.
"""
BLOG_FEATURED_POSTS_PLUGIN_NAME = _("Featured Posts")
"""
.. _FEATURED_POSTS_PLUGIN_NAME:
Name of the plugin showing the selected posts.
"""
BLOG_FEATURED_POSTS_PLUGIN_NAME_CACHED = _("Featured Posts - Cache")
"""
.. _FEATURED_POSTS_PLUGIN_NAME_CACHED:
Name of the plugin showing the selected posts (cached version).
"""
BLOG_FEED_CACHE_TIMEOUT = 3600
"""
.. _FEED_CACHE_TIMEOUT:
Cache timeout for RSS feeds.
"""
BLOG_FEED_INSTANT_ITEMS = 50
"""
.. _FEED_INSTANT_ITEMS:
Number of items in Instant Article feed.
"""
BLOG_FEED_LATEST_ITEMS = 10
"""
.. _FEED_LATEST_ITEMS:
Number of items in latest items feed.
"""
BLOG_FEED_TAGS_ITEMS = 10
"""
.. _FEED_TAGS_ITEMS:
Number of items in per tags feed.
"""
BLOG_LIVEBLOG_PLUGINS = ("LiveblogPlugin",)
"""
.. _LIVEBLOG_PLUGINS:
List of plugins implementing the :ref:`liveblog` feature.
"""
BLOG_PLUGIN_TEMPLATE_FOLDERS = (("plugins", _("Default template")),)
"""
.. _PLUGIN_TEMPLATE_FOLDERS:
(Sub-)folder from which the plugin templates are loaded.
The default folder is ``plugins``.
See :ref:`plugin_templates` for more details.
"""
BLOG_USE_FALLBACK_LANGUAGE_IN_URL = False
"""
.. _USE_FALLBACK_LANGUAGE_IN_URL:
When displaying URL, prefer URL in the fallback language if an article or category is not available in the
current language.
"""
BLOG_WIZARD_CONTENT_PLUGIN = "TextPlugin"
"""
.. _WIZARD_CONTENT_PLUGIN:
Name of the plugin created by wizard for the text content.
"""
BLOG_WIZARD_CONTENT_PLUGIN_BODY = "body"
"""
.. _WIZARD_CONTENT_PLUGIN_BODY:
Name of the plugin field to add wizard text.
"""
params = {param: value for param, value in locals().items() if param.startswith("BLOG_")}
"""
.. _django-meta settings: https://github.com/nephila/django-meta#settings
"""
def get_setting(name):
"""Get setting value from django settings with fallback to globals defaults."""
from django.conf import settings
return getattr(settings, "BLOG_%s" % name, params["BLOG_%s" % name])
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,832
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/tests/test_namespace.py
|
from contextlib import contextmanager
from cms.api import create_page
from django.test import Client
from django.utils.encoding import force_str
from .base import BaseTest
try:
from knocker.signals import pause_knocks
except ImportError:
@contextmanager
def pause_knocks(obj):
yield
class AdminTest(BaseTest):
def add_blog_config(self, page, namespace, config_id):
self.client = Client()
self.client.login(username=self._admin_user_username, password=self._admin_user_password)
response = self.client.post(
"/en/admin/cms/page/{}/advanced-settings/?language=en".format(page.pk),
{
"language": "nl",
"overwrite_url": "",
"redirect": "",
"template": "blog.html",
"reverse_id": "",
"navigation_extenders": "",
"application_urls": "BlogApp",
"application_namespace": namespace,
"application_configs": config_id,
"xframe_options": "0",
"_save": "Save",
},
follow=True,
)
self.client.logout()
return response
def test_add_blog_config(self):
"""
Adjust advanced settings of a page with blog config create.
"""
page = create_page("Blog2", "blog.html", "en", published=True)
response = self.add_blog_config(page, "Blog2", "")
content = force_str(response.content)
self.assertNotRegex(content, r"Please correct the error below.")
self.assertNotRegex(content, r"An application instance using this configuration already exists.")
response = self.client.get("/en/blog2/")
content = force_str(response.content)
self.assertRegex(content, r"Blog2")
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,833
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0031_auto_20170610_1744.py
|
# Generated by Django 1.10.5 on 2017-06-10 12:14
import sortedm2m.fields
from django.db import migrations
from sortedm2m.operations import AlterSortedManyToManyField
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0030_auto_20170509_1831"),
]
operations = [
AlterSortedManyToManyField(
model_name="post",
name="related",
field=sortedm2m.fields.SortedManyToManyField(
blank=True, help_text=None, to="djangocms_blog.Post", verbose_name="Related Posts"
),
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,834
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/tests/test_plugins.py
|
import os.path
import re
from cms.api import add_plugin
from cms.models import Page
from cms.test_utils.util.fuzzy_int import FuzzyInt
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.test import override_settings
from django.urls import reverse
from django.utils.http import urlencode
from django.utils.timezone import now
from taggit.models import Tag
from djangocms_blog.models import BlogCategory
from .base import BaseTest
User = get_user_model()
class PluginTest(BaseTest):
def test_plugin_latest_cached(self):
pages = self.get_pages()
posts = self.get_posts()
posts[0].tags.add("tag 1")
posts[0].publish = True
posts[0].save()
ph = pages[0].placeholders.get(slot="content")
plugin = add_plugin(ph, "BlogLatestEntriesPluginCached", language="en", app_config=self.app_config_1)
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
try:
self.assertTrue(rendered.find("cms-plugin-djangocms_blog-post-abstract-%s" % posts[0].pk) > -1)
except AssertionError:
self.assertTrue(rendered.find("cms_plugin-djangocms_blog-post-abstract-%s" % posts[0].pk) > -1)
self.assertTrue(rendered.find("<p>first line</p>") > -1)
self.assertTrue(rendered.find('<article id="post-first-post"') > -1)
self.assertTrue(rendered.find(posts[0].get_absolute_url()) > -1)
plugin_nocache = add_plugin(ph, "BlogLatestEntriesPlugin", language="en", app_config=self.app_config_1)
# FIXME: Investigate the correct number of queries expected here
with self.assertNumQueries(FuzzyInt(17, 18)):
self.render_plugin(pages[0], "en", plugin_nocache)
with self.assertNumQueries(FuzzyInt(17, 18)):
self.render_plugin(pages[0], "en", plugin)
with self.assertNumQueries(FuzzyInt(17, 18)):
rendered = self.render_plugin(pages[0], "en", plugin)
self.assertTrue(rendered.find("<p>first line</p>") > -1)
self.assertTrue(rendered.find('<article id="post-first-post"') > -1)
self.assertTrue(rendered.find(posts[0].get_absolute_url()) > -1)
def test_plugin_latest(self):
pages = self.get_pages()
posts = self.get_posts()
posts[0].tags.add("tag 1")
posts[0].publish = True
posts[0].save()
ph = pages[0].placeholders.get(slot="content")
plugin = add_plugin(ph, "BlogLatestEntriesPlugin", language="en", app_config=self.app_config_1)
tag = Tag.objects.get(slug="tag-1")
plugin.tags.add(tag)
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
try:
self.assertTrue(rendered.find("cms-plugin-djangocms_blog-post-abstract-%s" % posts[0].pk) > -1)
except AssertionError:
self.assertTrue(rendered.find("cms_plugin-djangocms_blog-post-abstract-%s" % posts[0].pk) > -1)
self.assertTrue(rendered.find(reverse("sample_app:posts-tagged", kwargs={"tag": tag.slug})) > -1)
self.assertTrue(rendered.find("<p>first line</p>") > -1)
self.assertTrue(rendered.find('<article id="post-first-post"') > -1)
self.assertTrue(rendered.find(posts[0].get_absolute_url()) > -1)
category_2 = BlogCategory.objects.create(name="category 2", app_config=self.app_config_1)
category_2.set_current_language("it", initialize=True)
category_2.name = "categoria 2"
category_2.save()
category_2.set_current_language("en")
posts[1].categories.add(category_2)
plugin = add_plugin(ph, "BlogLatestEntriesPlugin", language="en", app_config=self.app_config_1)
plugin.categories.add(category_2)
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
try:
self.assertTrue(rendered.find("cms-plugin-djangocms_blog-post-abstract-%s" % posts[1].pk) > -1)
except AssertionError:
self.assertTrue(rendered.find("cms_plugin-djangocms_blog-post-abstract-%s" % posts[1].pk) > -1)
self.assertTrue(rendered.find(reverse("sample_app:posts-category", kwargs={"category": category_2.slug})) > -1)
self.assertTrue(rendered.find("<p>second post first line</p>") > -1)
self.assertTrue(rendered.find('<article id="post-second-post"') > -1)
self.assertTrue(rendered.find(posts[1].get_absolute_url()) > -1)
# Checking copy relations
ph = pages[0].placeholders.get(slot="content")
original = ph.get_plugins("en")
pages[0].publish("en")
published = pages[0].get_public_object()
ph = published.placeholders.get(slot="content")
new = ph.get_plugins("en")
self.assertNotEqual(original, new)
casted_tags, __ = new[0].get_plugin_instance()
casted_categories, __ = new[1].get_plugin_instance()
self.assertEqual(casted_tags.tags.count(), 1)
self.assertEqual(casted_tags.categories.count(), 0)
self.assertEqual(casted_categories.tags.count(), 0)
self.assertEqual(casted_categories.categories.count(), 1)
posts[1].sites.add(self.site_2)
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
self.assertFalse(rendered.find("<p>second post first line</p>") > -1)
posts[1].sites.remove(self.site_2)
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
self.assertTrue(rendered.find("<p>second post first line</p>") > -1)
plugin = add_plugin(ph, "BlogLatestEntriesPlugin", language="en")
rendered = self.render_plugin(pages[0], "en", plugin, edit=False)
# data is picked from both apphook configs
self.assertTrue(rendered.find('<article id="post-first-post"') > -1)
self.assertTrue(rendered.find('<article id="post-different-appconfig"') > -1)
def test_plugin_featured_cached(self):
pages = self.get_pages()
posts = self.get_posts()
ph = pages[0].placeholders.get(slot="content")
plugin = add_plugin(ph, "BlogFeaturedPostsPluginCached", language="en", app_config=self.app_config_1)
plugin.posts.add(posts[0])
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
try:
self.assertTrue(rendered.find("cms-plugin-djangocms_blog-post-abstract-%s" % posts[0].pk) > -1)
except AssertionError:
self.assertTrue(rendered.find("cms_plugin-djangocms_blog-post-abstract-%s" % posts[0].pk) > -1)
self.assertTrue(rendered.find("<p>first line</p>") > -1)
self.assertTrue(rendered.find('<article id="post-first-post"') > -1)
self.assertTrue(rendered.find(posts[0].get_absolute_url()) > -1)
plugin_nocache = add_plugin(ph, "BlogFeaturedPostsPlugin", language="en", app_config=self.app_config_1)
plugin_nocache.posts.add(posts[0])
# FIXME: Investigate the correct number of queries expected here
with self.assertNumQueries(FuzzyInt(14, 15)):
self.render_plugin(pages[0], "en", plugin_nocache)
with self.assertNumQueries(FuzzyInt(14, 15)):
self.render_plugin(pages[0], "en", plugin)
with self.assertNumQueries(FuzzyInt(14, 15)):
rendered = self.render_plugin(pages[0], "en", plugin)
self.assertTrue(rendered.find("<p>first line</p>") > -1)
self.assertTrue(rendered.find('<article id="post-first-post"') > -1)
self.assertTrue(rendered.find(posts[0].get_absolute_url()) > -1)
def test_plugin_featured(self):
pages = self.get_pages()
posts = self.get_posts()
posts[1].publish = True
posts[1].save()
ph = pages[0].placeholders.get(slot="content")
plugin = add_plugin(ph, "BlogFeaturedPostsPlugin", language="en", app_config=self.app_config_1)
plugin.posts.add(posts[0], posts[1])
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
try:
self.assertTrue(rendered.find("cms-plugin-djangocms_blog-post-abstract-%s" % posts[0].pk) > -1)
self.assertTrue(rendered.find("cms-plugin-djangocms_blog-post-abstract-%s" % posts[1].pk) > -1)
except AssertionError:
self.assertTrue(rendered.find("cms_plugin-djangocms_blog-post-abstract-%s" % posts[0].pk) > -1)
self.assertTrue(rendered.find("cms_plugin-djangocms_blog-post-abstract-%s" % posts[1].pk) > -1)
self.assertTrue(rendered.find("<p>first line</p>") > -1)
self.assertTrue(rendered.find("<p>second post first line</p>") > -1)
self.assertTrue(rendered.find('<article id="post-first-post"') > -1)
self.assertTrue(rendered.find('<article id="post-second-post"') > -1)
self.assertTrue(rendered.find(posts[0].get_absolute_url()) > -1)
self.assertTrue(rendered.find(posts[1].get_absolute_url()) > -1)
def test_plugin_tags(self):
pages = self.get_pages()
posts = self.get_posts()
posts[0].tags.add("tag 1", "tag 2", "test tag")
posts[0].publish = True
posts[0].save()
posts[1].tags.add("test tag", "another tag")
posts[1].publish = True
posts[1].save()
ph = pages[0].placeholders.get(slot="content")
plugin = add_plugin(ph, "BlogTagsPlugin", language="en", app_config=self.app_config_1)
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
for tag in Tag.objects.all():
self.assertTrue(rendered.find(reverse("sample_app:posts-tagged", kwargs={"tag": tag.slug})) > -1)
if tag.slug == "test-tag":
rf = r"\s+{}\s+<span>\(\s+{} articles".format(tag.name, 2)
else:
rf = r"\s+{}\s+<span>\(\s+{} article".format(tag.name, 1)
rx = re.compile(rf)
self.assertEqual(len(rx.findall(rendered)), 1)
def test_blog_archive_plugin(self):
pages = self.get_pages()
posts = self.get_posts()
posts[0].publish = True
posts[0].save()
posts[1].publish = True
posts[1].save()
ph = pages[0].placeholders.get(slot="content")
plugin = add_plugin(ph, "BlogArchivePlugin", language="en", app_config=self.app_config_1)
plugin_class = plugin.get_plugin_class_instance()
context = self.get_plugin_context(pages[0], "en", plugin, edit=True)
context = plugin_class.render(context, plugin, ph)
self.assertEqual(
context["dates"][0]["date"].date(), now().replace(year=now().year, month=now().month, day=1).date()
)
self.assertEqual(context["dates"][0]["count"], 2)
posts[1].publish = False
posts[1].save()
context = plugin_class.render(context, plugin, ph)
self.assertEqual(
context["dates"][0]["date"].date(), now().replace(year=now().year, month=now().month, day=1).date()
)
self.assertEqual(context["dates"][0]["count"], 1)
def test_templates(self):
def _test_custom_templates_path(parts):
templates_path = os.path.join(os.path.dirname(__file__), "test_utils", "templates")
self.app_config_1.app_data.config.template_prefix = parts[0]
self.app_config_1.save()
tmp = plugin.template_folder
plugin.template_folder = parts[1]
plugin.save()
dir_parts = (templates_path,) + parts
template_parts = parts + (plugin_class.base_render_template,)
try:
os.makedirs(os.path.join(*dir_parts))
except OSError:
pass
fake_template = os.path.join(*template_parts)
with open(os.path.join(templates_path, fake_template), "w"):
self.assertEqual(plugin_class.get_render_template(context, plugin, ph), fake_template)
plugin.template_folder = tmp
plugin.save()
self.app_config_1.app_data.config.template_prefix = ""
self.app_config_1.save()
os.unlink(os.path.join(templates_path, fake_template))
self.get_posts()
pages = self.get_pages()
ph = pages[0].placeholders.get(slot="content")
plugin = add_plugin(ph, "BlogLatestEntriesPlugin", language="en", app_config=self.app_config_1)
context = self.get_plugin_context(pages[0], "en", plugin)
plugin_class = plugin.get_plugin_class_instance()
self.assertEqual(
plugin_class.get_render_template(context, plugin, ph),
os.path.join("djangocms_blog", plugin.template_folder, plugin_class.base_render_template),
)
custom_parts = ("whatever", "whereever")
_test_custom_templates_path(custom_parts)
custom_parts = ("djangocms_blog", "whereever")
_test_custom_templates_path(custom_parts)
class PluginTest10(BaseTest):
def test_plugin_authors(self):
pages = self.get_pages()
posts = self.get_posts()
posts[0].publish = True
posts[0].save()
posts[1].publish = True
posts[1].save()
ph = pages[0].placeholders.get(slot="content")
plugin = add_plugin(ph, "BlogAuthorPostsPlugin", language="en", app_config=self.app_config_1)
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
self.assertTrue(rendered.find("No author found") > -1)
plugin.authors.add(self.user)
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
self.assertTrue(rendered.find("/en/page-two/author/admin/") > -1)
self.assertTrue(rendered.find("2 articles") > -1)
plugin.authors.add(self.user_staff)
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
self.assertTrue(rendered.find("/en/page-two/author/staff/") > -1)
self.assertTrue(rendered.find("0 articles") > -1)
plugin.authors.add(self.user_normal)
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
self.assertTrue(rendered.find("/en/page-two/author/normal/") > -1)
self.assertTrue(rendered.find("0 articles") > -1)
# Checking copy relations
ph = pages[0].placeholders.get(slot="content")
original = ph.get_plugins("en")
pages[0].publish("en")
published = pages[0].get_public_object()
ph = published.placeholders.get(slot="content")
new = ph.get_plugins("en")
self.assertNotEqual(original, new)
casted_authors, __ = new[0].get_plugin_instance()
self.assertEqual(casted_authors.authors.count(), 3)
def test_plugin_authors_admin(self):
other_author = User.objects.create(username="other_author")
non_author = User.objects.create(username="non_author")
unpublished_author = User.objects.create(username="unpublished_author")
pages = self.get_pages()
posts = self.get_posts()
posts[0].publish = True
posts[0].save()
posts[1].publish = True
posts[1].author = other_author
posts[1].save()
posts[2].publish = False
posts[2].author = unpublished_author
posts[2].save()
ph = pages[0].placeholders.get(slot="content")
page_admin = admin.site._registry[Page]
parms = {
"cms_path": "/en/",
"placeholder_id": ph.pk,
"plugin_type": "BlogAuthorPostsPlugin",
"plugin_language": "en",
}
path = "/en/?%s" % urlencode(parms)
request = self.get_request(pages[0], "en", user=self.user, path=path)
response = page_admin.add_plugin(request)
form_authors = response.context_data["adminform"].form.fields["authors"].queryset
self.assertEqual(form_authors.count(), 2)
self.assertIn(other_author, form_authors)
self.assertIn(self.user, form_authors)
self.assertNotIn(unpublished_author, form_authors)
self.assertNotIn(non_author, form_authors)
def test_plugin_templates_field_single_template(self):
pages = self.get_pages()
ph = pages[0].placeholders.get(slot="content")
plugins = [
"BlogLatestEntriesPlugin",
"BlogLatestEntriesPluginCached",
"BlogAuthorPostsPlugin",
"BlogAuthorPostsListPlugin",
"BlogTagsPlugin",
"BlogArchivePlugin",
"BlogCategoryPlugin",
"BlogFeaturedPostsPlugin",
"BlogFeaturedPostsPluginCached",
]
for plugin in plugins:
page_admin = admin.site._registry[Page]
parms = {
"cms_path": "/en/",
"placeholder_id": ph.pk,
"plugin_type": plugin,
"plugin_language": "en",
}
path = "/en/?%s" % urlencode(parms)
request = self.get_request(pages[0], "en", user=self.user, path=path)
response = page_admin.add_plugin(request)
with self.assertRaises(KeyError):
template_folder_field = response.context_data["adminform"].form.fields["template_folder"] # noqa: F841
@override_settings(
BLOG_PLUGIN_TEMPLATE_FOLDERS=(
("default", "Default template"),
("vertical", "Vertical timeline"),
)
)
def test_plugin_templates_field_multi_template(self):
pages = self.get_pages()
ph = pages[0].placeholders.get(slot="content")
plugins = [
"BlogLatestEntriesPlugin",
"BlogLatestEntriesPluginCached",
"BlogAuthorPostsPlugin",
"BlogAuthorPostsListPlugin",
"BlogTagsPlugin",
"BlogArchivePlugin",
"BlogCategoryPlugin",
"BlogFeaturedPostsPlugin",
"BlogFeaturedPostsPluginCached",
]
for plugin in plugins:
page_admin = admin.site._registry[Page]
parms = {
"cms_path": "/en/",
"placeholder_id": ph.pk,
"plugin_type": plugin,
"plugin_language": "en",
}
path = "/en/?%s" % urlencode(parms)
request = self.get_request(pages[0], "en", user=self.user, path=path)
response = page_admin.add_plugin(request)
template_folder_field = response.context_data["adminform"].form.fields["template_folder"]
self.assertEqual(len(template_folder_field.choices), 2)
self.assertEqual(sorted(dict(template_folder_field.choices).keys()), sorted(["default", "vertical"]))
class PluginTest2(BaseTest):
def test_blog_category_plugin(self):
pages = self.get_pages()
posts = self.get_posts()
self.category_1.set_current_language("en")
posts[0].publish = True
posts[0].save()
posts[1].publish = True
posts[1].save()
posts[1].sites.add(self.site_2)
new_category = BlogCategory.objects.create(name="category 2", app_config=self.app_config_1)
posts[1].categories.add(new_category)
ph = pages[0].placeholders.get(slot="content")
plugin = add_plugin(ph, "BlogCategoryPlugin", language="en", app_config=self.app_config_1)
plugin_class = plugin.get_plugin_class_instance()
context = self.get_plugin_context(pages[0], "en", plugin, edit=True)
context = plugin_class.render(context, plugin, ph)
self.assertTrue(context["categories"])
self.assertEqual(list(context["categories"]), [self.category_1])
plugin.current_site = False
plugin.save()
context = plugin_class.render(context, plugin, ph)
self.assertEqual(list(context["categories"]), [self.category_1, new_category])
plugin.current_site = True
plugin.save()
with self.settings(SITE_ID=2):
context = plugin_class.render(context, plugin, ph)
self.assertEqual(list(context["categories"]), [self.category_1, new_category])
plugin.current_site = False
plugin.save()
with self.settings(SITE_ID=2):
context = plugin_class.render(context, plugin, ph)
self.assertEqual(list(context["categories"]), [self.category_1, new_category])
empty_category = BlogCategory.objects.create(name="empty 2", app_config=self.app_config_1)
self.app_config_1.app_data.config.menu_empty_categories = False
self.app_config_1.save()
context = plugin_class.render(context, plugin, ph)
self.assertEqual(list(context["categories"]), [self.category_1, new_category])
self.app_config_1.app_data.config.menu_empty_categories = True
self.app_config_1.save()
context = plugin_class.render(context, plugin, ph)
self.assertEqual(list(context["categories"]), [self.category_1, new_category, empty_category])
class PluginTestNamespace(BaseTest):
def test_plugin_latest_namespace(self):
pages = self.get_pages()
posts = self.get_posts()
self.category_1.set_current_language("en")
category_2 = BlogCategory.objects.create(name="category 2", app_config=self.app_config_2)
category_2.set_current_language("en")
ph = pages[0].placeholders.get(slot="content")
plugin = add_plugin(ph, "BlogLatestEntriesPlugin", language="en", app_config=self.app_config_1)
plugin.categories.add(self.category_1)
plugin.save()
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
self.assertTrue(
rendered.find(reverse("sample_app:posts-category", kwargs={"category": self.category_1.slug})) > -1
)
self.assertFalse(
rendered.find(reverse("sample_app2:posts-category", kwargs={"category": category_2.slug})) > -1
)
plugin.categories.add(category_2)
plugin.save()
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
self.assertTrue(
rendered.find(reverse("sample_app:posts-category", kwargs={"category": self.category_1.slug})) > -1
)
self.assertFalse(
rendered.find(reverse("sample_app2:posts-category", kwargs={"category": category_2.slug})) > -1
)
plugin.app_config = self.app_config_2
plugin.save()
posts[3].categories.remove(self.category_1)
posts[3].categories.add(category_2)
posts[3].save()
rendered = self.render_plugin(pages[0], "en", plugin, edit=True)
self.assertFalse(
rendered.find(reverse("sample_app:posts-category", kwargs={"category": self.category_1.slug})) > -1
)
self.assertTrue(
rendered.find(reverse("sample_app2:posts-category", kwargs={"category": category_2.slug})) > -1
)
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,835
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/tests/media_app/cms_plugins.py
|
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Vimeo, YoutTubeVideo
@plugin_pool.register_plugin
class YouTubePlugin(CMSPluginBase):
model = YoutTubeVideo
module = "Media"
name = "You Tube"
render_template = "media_app/youtube.html"
@plugin_pool.register_plugin
class VimeoPlugin(CMSPluginBase):
model = Vimeo
module = "Media"
name = "Vimeo"
render_template = "media_app/vimeo.html"
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,836
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0025_auto_20160803_0858.py
|
# Generated by Django 1.9.9 on 2016-08-03 06:58
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0024_auto_20160706_1524"),
]
operations = [
migrations.AlterField(
model_name="blogcategory",
name="parent",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="children",
to="djangocms_blog.BlogCategory",
verbose_name="parent",
),
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,837
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0040_post_include_in_rss.py
|
# Generated by Django 2.2 on 2021-10-25 12:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0039_auto_20200331_2227"),
]
operations = [
migrations.AddField(
model_name="post",
name="include_in_rss",
field=models.BooleanField(default=True, verbose_name="include in RSS feed"),
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,838
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/tests/test_utils/routing.py
|
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from djangocms_blog.liveblog.routing import channel_routing as djangocms_blog_routing
from knocker.routing import channel_routing as knocker_routing
application = ProtocolTypeRouter(
{
"websocket": AuthMiddlewareStack(
URLRouter([path("knocker/", knocker_routing), path("liveblog/", djangocms_blog_routing)])
),
}
)
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,839
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/liveblog/consumers.py
|
from channels.generic.websocket import JsonWebsocketConsumer
from ..models import Post
class LiveblogConsumer(JsonWebsocketConsumer):
def _get_post(self, kwargs):
apphook = kwargs.get("apphook")
lang = kwargs.get("lang")
slug = kwargs.get("post")
try:
return Post.objects.namespace(apphook).language(lang).active_translations(slug=slug).get()
except Post.DoesNotExist:
return
def websocket_connect(self, message):
self.groups = self.get_groups()
return super().websocket_connect(message)
def get_groups(self):
"""
Connect users to the group of the post according to the URL parameters
"""
post = self._get_post(self.scope["url_route"]["kwargs"])
if post:
return [post.liveblog_group]
else:
return []
def send_json(self, content, close=False):
return super().send_json(content, close)
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,840
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/tests/test_utils/admin.py
|
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _
from djangocms_blog.admin import PostAdmin
from .models import CustomUser, PostExtension
@admin.register(CustomUser)
class CustomUserAdmin(UserAdmin):
model = CustomUser
fieldsets = (
(None, {"fields": ("username", "password")}),
(_("Personal info"), {"fields": ("first_name", "last_name", "email")}),
(_("Permissions"), {"fields": ("is_active", "is_staff", "is_superuser", "groups", "user_permissions")}),
(_("Important dates"), {"fields": ("last_login", "date_joined")}),
(_("Sites"), {"fields": ("sites",)}),
)
class CustomPostAdmin(PostAdmin):
_fieldsets = [
(None, {"fields": ["title", "subtitle", "slug", "publish", "categories"]}),
(
_("Info"),
{
"fields": [
["tags"],
["date_published", "date_published_end", "date_featured"],
"app_config",
"enable_comments",
],
"classes": ("collapse",),
},
),
(
_("Images"),
{"fields": [["main_image", "main_image_thumbnail", "main_image_full"]], "classes": ("collapse",)},
),
(_("SEO"), {"fields": [["meta_description", "meta_title", "meta_keywords"]], "classes": ("collapse",)}),
]
_fieldset_extra_fields_position = {
"abstract": [0, 1],
"post_text": [0, 1],
"sites": [1, 1, 0],
"author": [1, 1],
"enable_liveblog": None,
"related": None,
}
class PostExtensionInline(admin.TabularInline):
model = PostExtension
fields = ["some_field"]
classes = ["collapse"]
extra = 1
can_delete = False
verbose_name = "PostExtension"
verbose_name_plural = "PostExtensions"
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,841
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/migrations/0006_auto_20150214_1907.py
|
import djangocms_text_ckeditor.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("djangocms_blog", "0005_auto_20150212_1118"),
]
operations = [
migrations.AlterField(
model_name="posttranslation",
name="abstract",
field=djangocms_text_ckeditor.fields.HTMLField(verbose_name="Abstract", blank=True, default=""),
preserve_default=True,
),
]
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,287,842
|
fsbraun/djangocms-blog
|
refs/heads/develop
|
/djangocms_blog/media/base.py
|
class MediaAttachmentPluginMixin:
"""
Base class for media-enabled plugins.
Items that needs implementation in subclasses:
* media_id: property that provides the object id on the external platform
* media_url: property that provides the media public URL
* _media_autoconfiguration: configuration dictionary (see documentation for details)
"""
_media_autoconfiguration = {
"params": [],
"thumb_url": "",
"main_url": "",
"callable": None,
}
"""
Configuration dictionary. **All** the keys are required:
* ``'params'``: one or more regular expressions to retrieve the media ID
according to the provided ``media_url``. It **must** contain a capturing
group called ``media_id`` (see examples below).
* ``'thumb_url'``: URL of the intermediate resolution media cover (depending
on the plaform).
It supports string formatting via ``format`` by providing the return json
for the media according to the plugic specification.
* ``'main_url'``: URL of the maximum resolution media cover (depending
on the plaform).
It supports string formatting via ``%``-formatting by providing the
return json for the media according to the plugic specification.
* ``'callable'``: in case the above information are not recoverable from the
object URL, provide here the name of a method on the plugin model instance
taking the ``media_id`` as parameter and that builds the data required by
``thumb_url``, ``media_url`` strings to build the correct cover urls.
"""
_cached_params = None
@property
def media_params(self):
"""
Retrieves the media information.
Minimal keys returned:
* ``media_id``: object id on the external platform
* ``url``: full url to the public version of the media
In case the ``'callable'`` key in py:attr:` _media_autoconfiguration` is not ``None``, it
will be called instead (as method on the current model instance) to retrieve the
information with any required logic.
:return: media information dictionary
:rtype: dict
"""
if not self._cached_params:
for pattern in self._media_autoconfiguration["params"]:
match = pattern.match(self.media_url)
if match:
if self._media_autoconfiguration["callable"]:
self._cached_params = getattr(self, self._media_autoconfiguration["callable"])(
**match.groupdict()
)
else:
self._cached_params = match.groupdict()
self._cached_params["url"] = self.media_url
return self._cached_params
@property
def media_url(self):
"""
Public URL of the object on the remote media.
As you will likely have a ``URL`` on the plugin model,
it's usually enough to return that value, but you are free to implement
any way to retrieve it.
:rtype: str
"""
raise NotImplementedError
@property
def media_id(self):
"""
ID of the object on the remote media.
:rtype: str
"""
try:
return self.media_params["media_id"]
except KeyError: # pragma: no cover
return None
def get_main_image(self):
"""
URL of the media cover at maximum resolution
:rtype: str
"""
return self._media_autoconfiguration["main_url"] % self.media_params
def get_thumb_image(self):
"""
URL of the media cover at intermediate resolution
:rtype: str
"""
return self._media_autoconfiguration["thumb_url"] % self.media_params
|
{"/djangocms_blog/cms_apps.py": ["/djangocms_blog/models.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/settings.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/cms_appconfig.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/urls_hub.py": ["/djangocms_blog/urls_base.py"], "/djangocms_blog/cms_toolbars.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py"], "/djangocms_blog/utils.py": ["/djangocms_blog/models.py"], "/djangocms_blog/views.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0043_postcontent.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_config.py": ["/djangocms_blog/models.py", "/djangocms_blog/views.py"], "/djangocms_blog/urls_base.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/djangocms_blog/admin.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/utils.py", "/djangocms_blog/cms_appconfig.py"], "/djangocms_blog/migrations/0044_copy_plugins.py": ["/djangocms_blog/models.py"], "/djangocms_blog/templatetags/djangocms_blog.py": ["/djangocms_blog/models.py"], "/djangocms_blog/urls.py": ["/djangocms_blog/urls_base.py"], "/tests/base_test.py": ["/tests/utils.py"], "/tests/test_menu.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/tests/base.py"], "/tests/test_utils/blog_urls.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/settings.py", "/djangocms_blog/views.py"], "/tests/test_utils/urls.py": ["/djangocms_blog/sitemaps/__init__.py"], "/tests/test_liveblog.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/liveblog/models.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/routing.py"], "/tests/test_toolbar.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_extension.py": ["/djangocms_blog/admin.py", "/djangocms_blog/models.py", "/tests/base.py", "/tests/test_utils/admin.py", "/tests/test_utils/models.py"], "/djangocms_blog/forms.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/tests/base.py", "/tests/test_utils/admin.py"], "/djangocms_blog/sitemaps/__init__.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/media_app/models.py": ["/djangocms_blog/media/base.py"], "/tests/test_indexing.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/djangocms_blog/feeds.py": ["/djangocms_blog/settings.py", "/djangocms_blog/views.py", "/djangocms_blog/models.py"], "/djangocms_blog/migrations/0021_auto_20160823_2008.py": ["/djangocms_blog/models.py"], "/djangocms_blog/cms_plugins.py": ["/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0024_auto_20160706_1524.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/cms_wizards.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/forms.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/djangocms_blog/cms_menus.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/base.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/cms_menus.py", "/djangocms_blog/models.py"], "/tests/test_views.py": ["/djangocms_blog/feeds.py", "/djangocms_blog/models.py", "/djangocms_blog/settings.py", "/djangocms_blog/sitemaps/__init__.py", "/djangocms_blog/views.py", "/tests/base.py"], "/djangocms_blog/fields.py": ["/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0011_auto_20151024_1809.py": ["/djangocms_blog/settings.py"], "/tests/media_app/migrations/0001_initial.py": ["/djangocms_blog/media/base.py"], "/djangocms_blog/migrations/0007_auto_20150719_0933.py": ["/djangocms_blog/models.py"], "/tests/test_utils/models.py": ["/djangocms_blog/models.py"], "/tests/test_setup.py": ["/djangocms_blog/cms_appconfig.py", "/tests/base.py"], "/djangocms_blog/migrations/0001_initial.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/cms_plugins.py": ["/djangocms_blog/settings.py", "/djangocms_blog/liveblog/models.py"], "/djangocms_blog/migrations/0018_thumbnail_move2.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/models.py": ["/djangocms_blog/models.py", "/djangocms_blog/settings.py"], "/tests/test_media.py": ["/djangocms_blog/templatetags/djangocms_blog.py", "/tests/base.py"], "/djangocms_blog/migrations/0004_auto_20150108_1435.py": ["/djangocms_blog/models.py"], "/djangocms_blog/models.py": ["/djangocms_blog/cms_appconfig.py", "/djangocms_blog/fields.py", "/djangocms_blog/managers.py", "/djangocms_blog/settings.py"], "/djangocms_blog/migrations/0019_thumbnail_move3.py": ["/djangocms_blog/models.py"], "/djangocms_blog/liveblog/routing.py": ["/djangocms_blog/liveblog/consumers.py"], "/tests/test_wizards.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/test_namespace.py": ["/tests/base.py"], "/tests/test_plugins.py": ["/djangocms_blog/models.py", "/tests/base.py"], "/tests/media_app/cms_plugins.py": ["/tests/media_app/models.py"], "/tests/test_utils/routing.py": ["/djangocms_blog/liveblog/routing.py"], "/djangocms_blog/liveblog/consumers.py": ["/djangocms_blog/models.py"], "/tests/test_utils/admin.py": ["/djangocms_blog/admin.py", "/tests/test_utils/models.py"]}
|
42,416,869
|
Ojashwa/peerXP
|
refs/heads/main
|
/Support/migrations/0002_userlogin_date_created.py
|
# Generated by Django 3.1.2 on 2020-10-23 17:07
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('Support', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='userlogin',
name='date_created',
field=models.DateField(auto_now_add=True, default=datetime.datetime(2020, 10, 23, 17, 7, 31, 84846, tzinfo=utc)),
preserve_default=False,
),
]
|
{"/Support/views.py": ["/Support/forms.py"]}
|
42,416,870
|
Ojashwa/peerXP
|
refs/heads/main
|
/Support/forms.py
|
from django import forms
from django.forms import ModelForm
from.models import Userlogin
class UserloginForms(forms.ModelForm):
'''registration form of modal class'''
class Meta:
modal = Userlogin
fields = ['name','email','password']
class TokenForm(forms.Form):
'''token form '''
category = forms.CharField(max_length=200)
webUrl = forms.CharField(max_length=200)
subject = forms.CharField(max_length=150)
description = forms.CharField(max_length=150)
email = forms.CharField(max_length=100)
priority = forms.CharField(max_length=100)
departmentId = forms.CharField(max_length=200)
contactId = forms.CharField(max_length=200)
|
{"/Support/views.py": ["/Support/forms.py"]}
|
42,416,871
|
Ojashwa/peerXP
|
refs/heads/main
|
/Support/views.py
|
import requests
import json
from django.shortcuts import render,HttpResponse,redirect
from dateutil import parser
from django.utils import timezone
from datetime import datetime
from django.contrib import messages
from.models import Userlogin
from.forms import TokenForm
# Create your views here.
def login(request):
'''insert the data to userlogin table in databse'''
if request.method =='POST':
name = request.POST['name']
email = request.POST['email']
password = request.POST['password']
if Userlogin.objects.filter(email=email).exists():
pass
else:
query = Userlogin(email=email,password=password,name=name)
query.save(force_insert=True)
request.session['username'] = name
request.session['email'] = email
messages.success(request,"Welcome "+name)
return render(request,"index.html")
return render(request,"login.html")
def index(request):
return render(request,"index.html")
def tokens(request):
'''This function handel the api request and show genrated tokens'''
headers = {
'orgId': '60001280952',
'Authorization': '9446933330c7f886fbdf16782906a9e0',
'Content-Type': 'application/json',
}
if request.method == 'POST':
form = TokenForm(request.POST)
# return HttpResponse(form)
if form.is_valid():
data = json.dumps(form.cleaned_data)
print(type(data))
print(data)
#send the POST request to inject data in API
post_response = requests.post('https://desk.zoho.in/api/v1/tickets', headers=headers,data=data)
#show response of POST
print(post_response.status_code)
#response save to post_token variable
# post_token = post_response.json()
messages.success(request,"Token created successfully")
return redirect('tokens')
#send GET request to API
get_response = requests.get('https://desk.zoho.in/api/v1/tickets', headers=headers)
# shows the response code of GET
print("response from the server--->",get_response.status_code)
token_get = get_response.json()
token_list = token_get['data']
# print(token_list)
for date in token_list:
localtz = str(parser.parse(date['createdTime']).astimezone())
localtime = datetime.strptime((localtz)[:19],"%Y-%m-%d %H:%M:%S")
date['createdTime'] = localtime
return render(request,"token_details.html",{'token_dict':token_list})
def token_details(request,tokenId_token):
'''retrive specific ticket data'''
token_Id = tokenId_token.split("_")[1]
token = tokenId_token.split("_")[0]
headers = {
'orgId': '60001280952',
'Authorization': '9446933330c7f886fbdf16782906a9e0',
'Content-Type': 'application/json',
}
#send GET request to API
get_response = requests.get('https://desk.zoho.in/api/v1/tickets/'+token_Id+'', headers=headers)
# shows the response code of GET
print(get_response.status_code)
token_get = get_response.json()
localtz = str(parser.parse(token_get['createdTime']).astimezone())
localtime = datetime.strptime((localtz)[:19],"%Y-%m-%d %H:%M:%S")
request.session['token'] = token
return render(request,"tokens.html",{'token_get':token_get,'created_date':localtime})
|
{"/Support/views.py": ["/Support/forms.py"]}
|
42,416,872
|
Ojashwa/peerXP
|
refs/heads/main
|
/Support/migrations/0004_auto_20201024_1031.py
|
# Generated by Django 3.1.2 on 2020-10-24 05:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Support', '0003_userlogin_name'),
]
operations = [
migrations.AlterField(
model_name='userlogin',
name='name',
field=models.CharField(max_length=100),
),
]
|
{"/Support/views.py": ["/Support/forms.py"]}
|
42,446,860
|
seigneurao/HarmonyPrises
|
refs/heads/master
|
/src/RFSignals.py
|
'''
Created on 20 janv. 2018
@author: Lionel
'''
import time
import sys
import RPi.GPIO as GPIO
'''
1 : short on, long off
0 : long on, short off
'''
OUTLET1_ON_SIGNAL = "1110101011101010110011001"
OUTLET1_OFF_SIGNAL = "1110101011101010110000111"
OUTLET2_ON_SIGNAL = "1110101011101010001111001"
OUTLET2_OFF_SIGNAL = "1110101011101010001100111"
OUTLET3_ON_SIGNAL = "1110101011101000111111001"
OUTLET3_OFF_SIGNAL = "1110101011101000111100111"
one_short_delay = 0.00009
one_long_delay = 0.00055
zero_short_delay = 0.00020
zero_long_delay = 0.00045
extended_delay = 0.00481
NUM_ATTEMPTS = 10
TRANSMIT_PIN = 2
def switchOnOutlet1():
emitRFSignal(OUTLET1_ON_SIGNAL)
def switchOffOutlet1():
emitRFSignal(OUTLET1_OFF_SIGNAL)
def switchOnOutlet2():
emitRFSignal(OUTLET2_ON_SIGNAL)
def switchOffOutlet2():
emitRFSignal(OUTLET2_OFF_SIGNAL)
def switchOnOutlet3():
emitRFSignal(OUTLET3_ON_SIGNAL)
def switchOffOutlet3():
emitRFSignal(OUTLET3_OFF_SIGNAL)
def emitRFSignal(signalCode):
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRANSMIT_PIN, GPIO.OUT)
for t in range(NUM_ATTEMPTS):
for i in signalCode:
if i == '1':
GPIO.output(TRANSMIT_PIN, 1)
time.sleep(one_short_delay)
GPIO.output(TRANSMIT_PIN, 0)
time.sleep(one_long_delay)
elif i == '0':
GPIO.output(TRANSMIT_PIN, 1)
time.sleep(zero_long_delay)
GPIO.output(TRANSMIT_PIN, 0)
time.sleep(zero_short_delay)
else:
continue
GPIO.output(TRANSMIT_PIN, 0)
time.sleep(extended_delay)
GPIO.cleanup()
|
{"/app.py": ["/src/SendRFSignals.py"]}
|
42,502,916
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/forms.py
|
from django.forms import ModelForm
from django import forms
from .models import Client, ScheduleEvent
from django.core.exceptions import ValidationError
from .validations import fix_phone_number
# from django.utils.translation import gettext_lazy as _
class ClientForm(ModelForm):
name = forms.CharField(
error_messages={"invalid": "Client with the same name already exists"}
)
name.widget.attrs.update(
{"placeholder": "required", "autocomplete": "new-password"}
)
address = forms.CharField()
address.widget.attrs.update(
{"autocomplete": "new-password", "placeholder": "required"}
)
phone_number = forms.RegexField(
regex=r"^(\+?1?)\D*(\d{3})\D*(\d{3})\D*(\d{4})\D*$",
error_messages={
"invalid": "Phone number must be entered in the format: '+1-333-666-9999'",
},
required=False,
widget=forms.TextInput(
attrs={
"placeholder": "Example: +1-323-627-8956 (optional)",
"autocomplete": "new-password",
}
),
)
email_address = forms.EmailField(required=False)
email_address.widget.attrs.update(
{"placeholder": "optional", "autocomplete": "new-password"}
)
class Meta:
model = Client
fields = ["name", "address", "phone_number", "email_address"]
def clean_phone_number(self):
data = self.cleaned_data["phone_number"]
data = fix_phone_number(data)
return data
class SearchForm(forms.Form):
query = forms.CharField(max_length=100, required=False)
class EventForm(ModelForm):
date = forms.DateField(
required=True,
widget=forms.widgets.DateTimeInput(
attrs={"type": "date", "placeholder": "mm/dd/yyyy"}
),
error_messages={
"invalid": "Enter a valid date. 'mm/dd/yyyy'",
},
)
duration = forms.CharField(
required=False,
widget=forms.widgets.TextInput(attrs={"placeholder": "example: 2h45min"}),
)
class Meta:
model = ScheduleEvent
fields = ["date", "duration", "work_order", "client", "description"]
def __init__(self, user, *args, **kwargs):
super(EventForm, self).__init__(*args, **kwargs)
self.fields["client"].queryset = Client.objects.filter(user=user)
class EventFormEdit(ModelForm):
class Meta:
model = ScheduleEvent
fields = ["date", "duration", "work_order", "client", "description"]
class SortByForm(forms.Form):
sortby = forms.ChoiceField(
label="Sort by",
choices=[
("-pk", "Last created (most recent)"),
("-date", "Date (Newest to oldest)"),
("date", "Date (Oldest to newest)"),
("client__name", "Client name (A-Z)"),
("-client__name", "Client name (Z-A)"),
],
)
# def __init__(self, request, *args, **kwargs):
# super(SortByForm, self).__init__(self, *args, **kwargs)
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,502,917
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/migrations/0010_auto_20210501_2106.py
|
# Generated by Django 3.2 on 2021-05-01 21:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('JobTrackingApp', '0009_alter_scheduleevent_duration'),
]
operations = [
migrations.RemoveField(
model_name='scheduleevent',
name='user',
),
migrations.AlterField(
model_name='scheduleevent',
name='description',
field=models.TextField(blank=True, max_length=2000),
),
]
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,502,918
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/migrations/0012_remove_scheduleevent_user.py
|
# Generated by Django 3.2 on 2021-05-02 02:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('JobTrackingApp', '0011_scheduleevent_user'),
]
operations = [
migrations.RemoveField(
model_name='scheduleevent',
name='user',
),
]
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,502,919
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py
|
# Generated by Django 3.2 on 2021-05-01 20:55
import JobTrackingApp.validations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('JobTrackingApp', '0008_alter_scheduleevent_duration'),
]
operations = [
migrations.AlterField(
model_name='scheduleevent',
name='duration',
field=models.CharField(blank=True, max_length=100, validators=[JobTrackingApp.validations.validate_duration]),
),
]
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,502,920
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py
|
# Generated by Django 3.2 on 2021-05-01 20:12
import JobTrackingApp.validations
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('JobTrackingApp', '0007_alter_scheduleevent_duration'),
]
operations = [
migrations.AlterField(
model_name='scheduleevent',
name='duration',
field=models.CharField(max_length=100, null=True, validators=[JobTrackingApp.validations.validate_duration]),
),
]
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,502,921
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/migrations/0006_rename_time_scheduleevent_duration.py
|
# Generated by Django 3.2 on 2021-05-01 18:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('JobTrackingApp', '0005_alter_scheduleevent_time'),
]
operations = [
migrations.RenameField(
model_name='scheduleevent',
old_name='time',
new_name='duration',
),
]
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,502,922
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/models.py
|
from django.db import models
from django import forms
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
from .validations import validate_duration, format_duration
# Create your models here.
class Client(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
address = models.CharField(max_length=60)
phone_number = models.CharField(blank=True, max_length=30)
email_address = models.EmailField(blank=True, max_length=30)
def __str__(self):
return f"{self.name}"
class ScheduleEvent(models.Model):
date = models.DateField()
duration = models.CharField(
max_length=100,
validators=[validate_duration],
blank=True,
)
work_order = models.CharField(
default="-",
max_length=20,
)
client = models.ForeignKey(Client, on_delete=models.CASCADE)
description = models.TextField(max_length=2000, blank=True)
def __str__(self):
return f"{self.client.name} --- {self.client.address} --- {self.date}"
def save(self, *args, **kwargs):
data = self.duration
formated_duration = format_duration(data)
self.duration = formated_duration
super().save(*args, **kwargs)
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,502,923
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/validations.py
|
import re
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
def validate_duration(value):
pattern = re.compile(r"^((?P<h>\d+)\s?h[a-zA-Z]*)?\s?((?P<m>\d+)\s?m[a-zA-Z]*)?$")
result = pattern.match(value)
if result:
if result.groupdict().get("h", False) or result.groupdict().get("m", False):
pass
else:
raise ValidationError(
_('%(value)s is not valid. Example of valid format:"2h45min"'),
params={"value": value},
)
else:
raise ValidationError(
_('%(value)s is not valid. Example of valid format:"2h45min"'),
params={"value": value},
)
def format_duration(value):
pattern = re.compile(r"^((?P<h>\d+)\s?h[a-zA-Z]*)?\s?((?P<m>\d+)\s?m[a-zA-Z]*)?$")
result = pattern.match(value)
data_value = ""
if result:
hours = result.groupdict().get("h", False)
minutes = result.groupdict().get("m", False)
if hours:
data_value += f"{hours}h "
if minutes:
data_value += f"{minutes}min"
return data_value
def fix_phone_number(phone_number):
if phone_number:
pattern = re.compile(r"^(\+?1?)\D*(\d{3})\D*(\d{3})\D*(\d{4})\D*$")
results = pattern.match(phone_number)
country_code = "+1"
group_list = results.groups()
area_code = group_list[1]
left_phone_number = group_list[2]
right_phone_number = group_list[3]
formed_phone_number = f"+1-{area_code}-{left_phone_number}-{right_phone_number}"
return formed_phone_number
else:
return ""
if __name__ == "__main__":
phone_number = "(323)-626-8959"
print(fix_phone_number(phone_number))
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,502,924
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/admin.py
|
from django.contrib import admin
from .models import ScheduleEvent, Client
# Register your models here.
admin.site.register(Client)
admin.site.register(ScheduleEvent)
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,502,925
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/migrations/0003_scheduleevent_time.py
|
# Generated by Django 3.2 on 2021-05-01 17:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('JobTrackingApp', '0002_auto_20210501_1557'),
]
operations = [
migrations.AddField(
model_name='scheduleevent',
name='time',
field=models.TimeField(null=True),
),
]
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,502,926
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/migrations/0005_alter_scheduleevent_time.py
|
# Generated by Django 3.2 on 2021-05-01 18:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('JobTrackingApp', '0004_scheduleevent_user'),
]
operations = [
migrations.AlterField(
model_name='scheduleevent',
name='time',
field=models.DurationField(null=True),
),
]
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,502,927
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/migrations/0007_alter_scheduleevent_duration.py
|
# Generated by Django 3.2 on 2021-05-01 18:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('JobTrackingApp', '0006_rename_time_scheduleevent_duration'),
]
operations = [
migrations.AlterField(
model_name='scheduleevent',
name='duration',
field=models.CharField(max_length=100, null=True),
),
]
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,502,928
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/tests.py
|
from django.test import TestCase
from django.urls import reverse, resolve
from django.contrib.auth.models import User
from . import views
from .models import ScheduleEvent, Client
import datetime
# Testing index view (events view)
class EventsTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.userInstance = User.objects.create_user(username='testUser', password='password123')
cls.clientInstance = Client.objects.create(user=cls.userInstance, name='Michael Rodrigo', address='whatever 123')
cls.eventInstance = ScheduleEvent.objects.create(date=datetime.date.today(), duration='', client=cls.clientInstance, description='apples are apples')
def setUp(self):
''' Both login ways are valid!
self.client.login(username='testUser', password='password123')
'''
self.client.post(reverse('login'), {'username':'testUser', 'password': 'password123'})
def test_home_view_status_code(self):
url = reverse('index')
response = self.client.get(url)
self.assertEquals(url, '/')
self.assertEquals(response.status_code, 200)
def test_home_view_template_names(self):
url = reverse('index')
response = self.client.get(url)
self.assertEquals(response.templates[0].name, 'JobTrackingApp/index.html')
self.assertEquals(response.templates[1].name, 'JobTrackingApp/base.html')
def test_home_view_func_name(self):
url = reverse('index')
response = self.client.get(url)
# response.resolver_match is equal to resolve(url)
self.assertEquals(response.resolver_match.func, views.index)
self.assertEquals(response.resolver_match.view_name, 'index')
def test_edit_event_view_status_code(self):
url = reverse('editEvent',kwargs={'pk': 1})
response = self.client.get(url)
self.assertEquals(url, '/events/1/edit')
self.assertEquals(response.status_code, 200)
def test_edit_event_template_names(self):
url = reverse('editEvent', kwargs={'pk': 1})
response = self.client.get(url)
self.assertEquals(response.templates[0].name, 'JobTrackingApp/eventEditView.html')
def test_edit_event_func_name(self):
url = reverse('editEvent', kwargs={'pk': 1})
response = self.client.get(url)
self.assertEquals(response.resolver_match.func, views.editEvent)
self.assertEquals(response.resolver_match.view_name, 'editEvent')
def test_edit_event_POST_redirect(self):
url = reverse('editEvent', kwargs={'pk': 1})
response = self.client.post(url, {
'date': "12/24/2018",
'duration': '1hr',
'work_order': '-',
'client': '1',
'description': 'nedys'}, follow=True)
redirect_url, status_code = response.redirect_chain[0]
self.assertEquals(redirect_url, reverse('index'))
self.assertEquals(status_code, 302)
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,502,929
|
nedas-dev/job-tracking-app
|
refs/heads/main
|
/JobTrackingApp/views.py
|
from django.shortcuts import render
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.shortcuts import redirect, get_object_or_404
from django.http import JsonResponse, HttpResponseNotFound
from . import views
from .forms import ClientForm, SearchForm, EventForm, EventFormEdit, SortByForm
from .models import Client, ScheduleEvent
from django.core.exceptions import ValidationError
from .validations import fix_phone_number
from django.core.paginator import Paginator
from django.contrib import messages
from django.db.models import Q
@login_required
def index(request):
context = {}
query = ""
eventForm = EventForm(user=request.user)
events = ScheduleEvent.objects.filter(client__user=request.user)
sortbyform = SortByForm(request.GET)
searchForm = SearchForm(request.GET)
if request.method == "GET" and request.GET.get("action", False) == "search":
if searchForm.is_valid() and searchForm.cleaned_data["query"]:
data = searchForm.cleaned_data
query = data["query"]
if query:
events = events.filter(
Q(client__name__icontains=query)
| Q(description__icontains=query)
| Q(client__address__icontains=query)
| Q(work_order__icontains=query)
)
elif request.method == "GET" and request.GET.get("action", False) == "sort":
if sortbyform.is_valid():
data = sortbyform.cleaned_data
request.session["sortby"] = data.get("sortby", "-pk")
elif request.method == "POST":
eventForm = EventForm(request.user, request.POST)
if eventForm.is_valid():
eventForm.save()
messages.success(request, "You have successfully created an event!")
return redirect(reverse("index"))
else:
eventForm = EventForm(request.user, request.POST)
events = events.order_by(f'{request.session.get("sortby", "-pk")}')
page_number = request.GET.get("page", 1)
paginator = Paginator(events, 12)
pageList = paginator.get_page(page_number)
context["sortbyForm"] = sortbyform
context["searchForm"] = searchForm
context["search"] = query
context["eventForm"] = eventForm
context["paginator"] = paginator
context["is_paginated"] = True
context["page_obj"] = pageList
return render(request, "JobTrackingApp/index.html", context)
@login_required
def editEvent(request, pk):
context = {}
if request.method == "GET":
instance = get_object_or_404(ScheduleEvent, pk=pk)
eventForm = EventFormEdit(instance=instance)
context["eventForm"] = eventForm
elif request.method == "POST":
instance = get_object_or_404(ScheduleEvent, pk=pk)
eventForm = EventFormEdit(request.POST, instance=instance)
if eventForm.is_valid():
eventForm.save()
messages.success(request, "You successfully updated an event!")
return redirect(reverse("index"))
else:
context["eventForm"] = eventForm
context["pk"] = pk
return render(request, "JobTrackingApp/eventEditView.html", context)
@login_required
def deleteEvent(request, pk):
eventObj = ScheduleEvent.objects.filter(client__user=request.user).filter(pk=pk)
object_exists = eventObj.exists()
if object_exists:
context = {"event_obj": eventObj[0]}
else:
return HttpResponseNotFound("Something went wrong")
if (
request.method == "POST"
and object_exists
and request.POST.get("action") == "Yes"
):
eventObj[0].delete()
messages.success(request, f"You have successfully deleted an event!")
return redirect(reverse("index"))
elif (
request.method == "POST"
and object_exists
and request.POST.get("action") == "No"
):
return redirect(reverse("editEvent", args=[pk]))
return render(request, "JobTrackingApp/eventDeleteView.html", context=context)
@login_required
def clients(request):
query = ""
clientList = Client.objects.filter(user=request.user).order_by("name")
searchForm = SearchForm(request.GET)
if request.method == "GET":
form = ClientForm()
if searchForm.is_valid():
data = searchForm.cleaned_data
query = data["query"]
if query:
clientList = clientList.filter(name__icontains=query)
elif request.method == "POST":
form = ClientForm(request.POST)
if form.is_valid():
data = form.cleaned_data
if not clientList.filter(name=data["name"]).exists():
phone_number = fix_phone_number(data["phone_number"])
client = Client(
user=request.user,
address=data["address"],
name=data["name"],
phone_number=phone_number,
email_address=data["email_address"],
)
client.save()
messages.success(request, "You have successfully created a new client!")
return redirect(reverse("clients"))
else:
form.add_error("name", "Client with the same name already exists")
page_number = request.GET.get("page", 1)
paginator = Paginator(clientList, 10)
pageList = paginator.get_page(page_number)
context = {
"paginator": paginator,
"page_obj": pageList,
"form": form,
"searchForm": searchForm,
"is_paginated": True,
"search": query,
}
return render(
request,
"JobTrackingApp/clients.html",
context,
)
@login_required
def clientDetailView(request, pk):
clientObj = Client.objects.filter(user=request.user).filter(pk=pk)
exists = clientObj.exists()
context = {}
context["pk"] = pk
if exists and request.method == "GET":
form = ClientForm(instance=clientObj[0])
context["form"] = form
return render(
request,
"JobTrackingApp/clientDetailView.html",
context,
)
elif exists and request.method == "POST":
form = ClientForm(request.POST, instance=clientObj[0])
context["form"] = form
if form.is_valid():
data = form.cleaned_data
exists = (
Client.objects.filter(user=request.user)
.filter(name=data["name"])
.exclude(pk=pk)
.exists()
)
if exists:
form.add_error("name", "A client with the same name already exists.")
return render(
request,
"JobTrackingApp/clientDetailView.html",
context,
)
form.save()
messages.success(
request,
f"You have successfully updated {data['name']}!",
)
return redirect(reverse("clients"))
else:
return render(
request,
"JobTrackingApp/clientDetailView.html",
context=context,
)
else:
return HttpResponseNotFound("404 Page not found")
@login_required
def clientDeleteView(request, pk):
clientObj = Client.objects.filter(user=request.user).filter(pk=pk)
client_exists = clientObj.exists()
if client_exists:
context = {"client_obj": clientObj[0]}
else:
return HttpResponseNotFound("Something went wrong")
if (
request.method == "POST"
and client_exists
and request.POST.get("action") == "Yes"
):
name = clientObj[0].name
clientObj[0].delete()
messages.success(request, f"You have successfully deleted {name}!")
return redirect(reverse("clients"))
elif (
request.method == "POST"
and client_exists
and request.POST.get("action") == "No"
):
return redirect(reverse("client-detail", args=[pk]))
return render(request, "JobTrackingApp/clientDeleteView.html", context=context)
|
{"/JobTrackingApp/forms.py": ["/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0009_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/migrations/0008_alter_scheduleevent_duration.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/models.py": ["/JobTrackingApp/validations.py"], "/JobTrackingApp/admin.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/tests.py": ["/JobTrackingApp/models.py"], "/JobTrackingApp/views.py": ["/JobTrackingApp/forms.py", "/JobTrackingApp/models.py", "/JobTrackingApp/validations.py"]}
|
42,532,518
|
adefelicibus/koala-server
|
refs/heads/master
|
/lib/koala/classe.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# util/__init__
# import sys
# utils/input.py
# import string
# import shutil
# import subprocess
# import os
# utils/path
# import stat
# utils/mail.py
# import smtplib
# utils/__init__
# import re
# import datetime
# import zipfile
# utils/__init__
# import fnmatch
# utils/mail.py
# from email.Utils import formatdate
# from email import encoders
# from email.mime.base import MIMEBase
# from email.mime.multipart import MIMEMultipart
# from email.mime.text import MIMEText
# util/__init__
# import getpass
# utils/output
# import urllib2
# ordered_dict/default.py
# from collections import OrderedDict, Callable
# utils/path
# import random
# ordered_dict/default.py
# class DefaultOrderedDict(OrderedDict):
# # Source: http://stackoverflow.com/a/6190500/562769
# def __init__(self, default_factory=None, *a, **kw):
# if (default_factory is not None and
# not isinstance(default_factory, Callable)):
# raise TypeError('first argument must be callable')
# OrderedDict.__init__(self, *a, **kw)
# self.default_factory = default_factory
# def __getitem__(self, key):
# try:
# return OrderedDict.__getitem__(self, key)
# except KeyError:
# return self.__missing__(key)
# def __missing__(self, key):
# if self.default_factory is None:
# raise KeyError(key)
# self[key] = value = self.default_factory()
# return value
# def __reduce__(self):
# if self.default_factory is None:
# args = tuple()
# else:
# args = self.default_factory,
# return type(self), args, None, None, self.items()
# def copy(self):
# return self.__copy__()
# def __copy__(self):
# return type(self)(self.default_factory, self)
# def __deepcopy__(self, memo):
# import copy
# return type(self)(self.default_factory,
# copy.deepcopy(self.items()))
# def __repr__(self):
# return 'OrderedDefaultDict(%s, %s)' % (
# self.default_factory, OrderedDict.__repr__(self))
class IcmcGalaxy(object):
"""docstring for IcmcGalaxy"""
# frameworks/params.py
# general_parametersMEAMT = [
# ('num_geracoes', '0'),
# ('tam_population', '400'),
# ('pop_vdw', '25'),
# ('pop_charge', '25'),
# ('pop_solv', '25'),
# ('pop_hbond', '25'),
# ('pop_nondom', '25'),
# ('pop_pond1', '25'),
# ('pop_pond2', '25'),
# ('pop_pond3', '25'),
# ('pop_pond4', '25'),
# ('pop_pond5', '25'),
# ('pop_pond6', '25'),
# ('pop_pond7', '25'),
# ('pop_pond8', '25'),
# ('pop_pond9', '25'),
# ('pop_pond10', '25'),
# ('pop_pond11', '25'),
# ('unknown1', '0'),
# ('unknown2', '0'),
# ('vdw_w', '1'),
# ('charge_w', '0.5'),
# ('unknown3', '0'),
# ('unknown4', '0'),
# ('unknown5', '0'),
# ('unknown6', '0'),
# ('unknown7', '0'),
# ('solv_w', '0.5'),
# ('hbond_w', '0.5'),
# ('inputfasta', 'fasta.txt'),
# ('resultTxt', 'result_1vii.txt'),
# ('inputPop', 'pop_meamt.txt'),
# ('inputPDB', '1vii.pdb'),
# ('saida1', 'saida1.txt'),
# ('angles', 'angles.txt'),
# ('unknown8', '0'),
# ('meat', '1vii_meat.txt'),
# ]
# meamt_param = DefaultOrderedDict(list)
# for k, v in general_parametersMEAMT:
# meamt_param[k].append(v)
# general_parameters = {
# 'gromacs_energy_min': 'ener_implicit',
# 'NumberProcessor': '8',
# 'NumberObjective': '1',
# 'NumberGeration': '1',
# 'SizePopulation': '1',
# 'MonteCarloSteps': '50',
# 'FrequencyMC': '5',
# 'TemperatureMC': '370',
# 'Fitness_Energy': 'Potential',
# 'NativeProtein': '/home/faccioli/Execute/1VII_teste_1_1/1VII.pdb',
# 'SequenceAminoAcidsPathFileName':
# '/home/faccioli/Execute/1VII_teste_1_1/1VII.fasta.txt',
# 'NameExecutation': '1VII_teste_1',
# 'Local_Execute': '/home/faccioli/Execute/1VII_teste_1_1/',
# 'Database':
# '/home/faccioli/workspace/2pg_build_conformation/Database/',
# 'rotamer_library': 'cad_tuffery',
# 'top_file': 'top_protein.top',
# 'IniPopFileName': 'pop_0.pdb',
# 'Started_Generation': '-1',
# 'z_matrix_fileName': 'z_matrix',
# 'Path_Gromacs_Programs':
# '/home/faccioli/programs/gmx-4.6.5/no_mpi/bin/',
# 'Computed_Energies_Gromacs_File':
# 'file_energy_computed.ener.edr',
# 'Energy_File_xvg': 'energy.xvg',
# 'Computed_Areas_g_sas_File': 'file_g_sas_areas.xvg',
# 'Computed_Energy_Value_File': 'energy_computed.xvg',
# 'Computed_Radius_g_gyrate_File': 'file_g_gyrate_radius.xvg',
# 'Computed_g_hbond_File': 'file_g_hbond.xvg',
# 'How_Many_Rotation': '1',
# 'min_angle_mutation_phi': '-10',
# 'max_angle_mutation_phi': '10',
# 'min_angle_mutation_psi': '-10',
# 'max_angle_mutation_psi': '10',
# 'min_angle_mutation_omega': '-10',
# 'max_angle_mutation_omega': '10',
# 'min_angle_mutation_side_chain': '-10',
# 'max_angle_mutation_side_chain': '10',
# 'apply_crossover': 'yes',
# 'Individual_Mutation_Rate': '0.60',
# 'mdp_file_min': 'energy_minimization_implicit.mdp',
# 'mdp_file_name': 'compute_energy_implicit.mdp',
# 'c_terminal_charge': 'none',
# 'n_terminal_charge': 'none',
# 'force_field': 'amber99sb-ildn',
# 'objective_analisys': 'none',
# 'objective_analisys_dimo_source':
# '/home/faccioli/workspace/dimo/DIMO2',
# 'Program_Run_GreedyTreeGenerator2PG':
# '/2pg_cartesian/scripts/dimo/call_GreedyTreeGenerator2PG.sh',
# '1_point_cros_Rate': '0.80',
# 'StepNumber': '100',
# }
# general_parameters_eda = [
# ('[Config]', ''),
# ('SaveOutput', 'yes'),
# ('RandomSeed', '0'),
# ('PrintDetails', 'no'),
# ('RedirectToNull', 'no'),
# ('RunMode', 'CreateRun'),
# ('OptimMethod', 'eda'),
# ('OutputFolder', 'out'),
# ('Threshold', '0.0001'),
# ('MaxEval', '1000000'),
# ('Fitness', 'psp'),
# ('SaveData', 'no'),
# ('OverwriteData', 'no'),
# ('PopFile', 'null'),
# ('ExpsMode', 'no'),
# ('SetsNumber', '4'),
# ('[Optimization]', ''),
# ('CellList', 'yes'),
# ('CLOpenMP', 'no'),
# ('SASAGPU', 'no'),
# ('[FitnessPSP]', ''),
# ('VanderWaals', '1.0'),
# ('SASA', '0.0'),
# ('Coulomb', '0.0'),
# ('Solvatation', '0.0'),
# ('HydrogenBond', '0.0'),
# ('Torsion', '0.0'),
# ('SequenceFile', 'fasta.txt'),
# ('UseAngleDB', 'no'),
# ('AminoAcidL', 'yes'),
# ('SideChainMulti', 'no'),
# ('SinglePDB', 'no'),
# ('ChiDB', 'no'),
# ]
# protpred_eda_param = DefaultOrderedDict(list)
# for k, v in general_parameters_eda:
# protpred_eda_param[k].append(v)
# l_rw_param = [
# ('[RandomWalk]', ''),
# ('PopSize', '500'),
# ]
# rw_param = DefaultOrderedDict(list)
# for k, v in l_rw_param:
# rw_param[k].append(v)
# l_mcm_param = [
# ('[MonteCarloMetropolis]', ''),
# ('PopSize', '5000'),
# ('Step', '0.02'),
# ('Boltzmann', '0.259'),
# ]
# mcm_param = DefaultOrderedDict(list)
# for k, v in l_mcm_param:
# mcm_param[k].append(v)
# l_ga_param = [
# ('[GeneticAlgorithm]', ''),
# ('PopSize', '3000'),
# ('OffSize', '3000'),
# ('CrossoverRate', '0.3'),
# ('MutationRate', '0.05'),
# ('MutationFactor', '0.1'),
# ('[SelectionConfig]', ''),
# ('SelSize', '5000'),
# ('SelMethod', 'tournament'),
# ('TouSize', '2'),
# ]
# ga_param = DefaultOrderedDict(list)
# for k, v in l_ga_param:
# ga_param[k].append(v)
# l_rboa_param = [
# ('[rBOA]', ''),
# ('PopSize', '5000'),
# ('SelSize', '2500'),
# ('MaxParents', '1'),
# ('MixtureComponents', '2')
# ]
# rboa_param = DefaultOrderedDict(list)
# for k, v in l_rboa_param:
# rboa_param[k].append(v)
# l_de_param = [
# ('[DE]', ''),
# ('PopSize', '3000'),
# ('OffSize', '3000'),
# ('CrossoverRate', '0.4'),
# ('FRate', '0.2'),
# ('[SelectionConfig]', ''),
# ('SelSize', '5000'),
# ('SelMethod', 'tournament'),
# ('TouSize', '2'),
# ]
# de_param = DefaultOrderedDict(list)
# for k, v in l_de_param:
# de_param[k].append(v)
# l_eda_param = [
# ('[EDA]', ''),
# ('PopSize', '500'),
# ('OffSize', '500'),
# ('SamplingMode', 'univariate'),
# ('Noise', '2'),
# ('Objective', 'mono'),
# ('Hierarchical', 'no'),
# ('[SelectionConfig]', ''),
# ('SelSize', '500'),
# ('SelMethod', 'tournament'),
# ('TouSize', '2'),
# ]
# eda_param = DefaultOrderedDict(list)
# for k, v in l_eda_param:
# eda_param[k].append(v)
# l_ceda_param = [
# ('[CEDA]', ''),
# ('MaxEval1', '500000'),
# ('MaxEval2', '500000'),
# ('Overlap', '0'),
# ('SamplingMode', 'univariate'),
# ('[SelectionConfig]', ''),
# ('SelSize', '5000'),
# ('SelMethod', 'tournament'),
# ('TouSize', '2'),
# ]
# ceda_param = DefaultOrderedDict(list)
# for k, v in l_ceda_param:
# ceda_param[k].append(v)
# l_fgm_param = [
# ('[FGM]', ''),
# ('MixtureComponents', '2'),
# ('Dimensionality', '2'),
# ('Threshold', '1.5'),
# ('Lambda', '0.9'),
# ('Partitions', '150'),
# ('FullMatrix', 'no'),
# ('GlobalSigma', 'no'),
# ('UseJointPDF', 'no'),
# ('[Hierarchical]', ''),
# ('ClusterMethod', 'euclidian'),
# ('AgglomerationM', 'complete'),
# ('CutTree', '2'),
# ('ClusteringType', 'dihedral'),
# ]
# fgm_param = DefaultOrderedDict(list)
# for k, v in l_fgm_param:
# fgm_param[k].append(v)
pathExecution = ''
command = ''
program = ''
framework = '2PG' # 2PG(Default) or ProtPred-EDA or MEAMT
pathGromacs = ''
jobStart = ''
jobEnd = ''
def __init__(self):
super(IcmcGalaxy, self).__init__()
# util/__init__
# def getjobStart(self):
# return self.jobStart
# def setjobStart(self, jobStart):
# self.jobStart = jobStart
# def getjobEnd(self):
# return self.jobEnd
# def setjobEnd(self, jobEnd):
# self.jobEnd = jobEnd
# def calcTimeExecution(self, start, end):
# dif = end - start
# minutes = 0
# if (dif.seconds / 60) > 60:
# minutes = (dif.seconds / 60) - ((dif.seconds / 3600) * 60)
# else:
# minutes = dif.seconds / 60
# return [
# dif.seconds / 3600,
# minutes,
# dif.seconds - ((dif.seconds / 60) * 60)]
# utils/path
# def getPathGromacs(self):
# self.pathGromacs = '/home/%s/programs/gmx-4.6.5/no_mpi/bin/' \
# % self.getLoggedUser()
# return self.pathGromacs
# frameworks/params.py
# def getParameters(self):
# return self.general_parameters
# frameworks/framework
# def setFramework(self, framework):
# self.framework = framework
# def getFramework(self):
# return self.framework
# frameworks/params.py
# def setParameter(self, key, value):
# try:
# if(self.framework == '2PG'):
# if key in self.general_parameters:
# self.general_parameters[key] = value
# else:
# raise "There is no key %s in the parameters list. \
# Please, use a valid key.\n" % key
# elif(self.framework == 'ProtPred-EDA'):
# if key in self.protpred_eda_param:
# self.protpred_eda_param[key] = value
# elif(self.getParameterValue("OptimMethod") == 'rw'):
# self.rw_param[key] = value
# elif(self.getParameterValue("OptimMethod") == 'mcm'):
# self.mcm_param[key] = value
# elif(self.getParameterValue("OptimMethod") == 'eda'):
# if key in self.eda_param:
# self.eda_param[key] = value
# elif self.\
# getParameterValue("SamplingMode", "eda") == 'fgm':
# if key in self.fgm_param:
# self.fgm_param[key] = value
# else:
# raise "There is no key %s in the parameters list. \
# Please, use a valid key.\n" % key
# else:
# raise "There is no key %s in the parameters list. \
# Please, use a valid key.\n" % key
# elif(self.getParameterValue("OptimMethod") == 'rboa'):
# self.rboa_param[key] = value
# elif(self.getParameterValue("OptimMethod") == 'ga'):
# self.ga_param[key] = value
# elif(self.getParameterValue("OptimMethod") == 'de'):
# self.de_param[key] = value
# elif(self.getParameterValue("OptimMethod") == 'ceda'):
# if key in self.ceda_param:
# self.ceda_param[key] = value
# elif self.\
# getParameterValue("SamplingMode", "ceda") == 'fgm':
# if key in self.fgm_param:
# self.fgm_param[key] = value
# else:
# raise "There is no key %s in the parameters list [SamplingMode](%s)(%s). \
# Please, use a valid key.\n" % (
# key,
# self.getParameterValue("OptimMethod"),
# self.getParameterValue("SamplingMode"),
# )
# else:
# raise "There is no key %s in the parameters list[OptimMethod](%s)(%s). \
# Please, use a valid key.\n" % (
# key,
# self.getParameterValue("OptimMethod"),
# self.getParameterValue("SamplingMode"),
# )
# else:
# raise "There is no key %s in the parameters list. \
# Please, use a valid key.\n" % key
# elif(self.framework == 'MEAMT'):
# if key in self.meamt_param:
# self.meamt_param[key] = value
# else:
# raise "There is no key %s in the parameters list. \
# Please, use a valid key.\n" % key
# else:
# raise Exception("There is no defined framework.\n")
# except Exception, e:
# self.ShowErrorMessage("Error when setParameter\n%s" % e)
# # raise Exception("Error while setting parameter: \n%s" % e)
# def getParameterValue(self, key, optMethod=None):
# try:
# if(self.framework == '2PG'):
# if key in self.general_parameters:
# return self.general_parameters[key]
# elif(self.framework == 'ProtPred-EDA'):
# if key in self.protpred_eda_param:
# return self.protpred_eda_param[key]
# elif key in self.rw_param:
# return self.rw_param[key]
# elif key in self.mcm_param:
# return self.mcm_param[key]
# elif key in self.eda_param and optMethod == "eda":
# return self.eda_param[key]
# elif key in self.fgm_param:
# return self.fgm_param[key]
# elif key in self.ga_param:
# return self.ga_param[key]
# elif key in self.rboa_param:
# return self.rboa_param[key]
# elif key in self.de_param:
# return self.de_param[key]
# elif key in self.ceda_param and optMethod == "ceda":
# return self.ceda_param[key]
# else:
# raise Exception(
# "There is no key %s in the parameters list"
# "Please, use a valid key.\n" % key)
# elif(self.framework == 'MEAMT'):
# if key in self.meamt_param:
# return self.meamt_param[key]
# else:
# raise Exception("There is no defined framework.\n")
# except Exception, e:
# self.ShowErrorMessage("Error when getParameterValue\n%s" % e)
# # raise Exception("Error while getting parameter value: %s" % e)
# util/__init__
# def getLoggedUser(self):
# try:
# return getpass.getuser()
# except Exception, e:
# self.ShowErrorMessage("Error when setCommand\n%s" % e)
# frameworks/framework
# def getConfigurationFile(self, filename):
# # return '%s%s' % (self.getPathExecution(), filename)
# return '%s' % filename
# def setCommand(self, framework, algorithm):
# try:
# global command
# if(self.framework == '2PG'):
# # self.command = '%ssrc/%s' % (
# self.command = '/usr/local/bin/%s' % (algorithm)
# # elif(self.framework == 'MEAMT'):
# # self.command = '%s%s' % (self.getPathAlgorithms(framework), algorithm)
# elif(self.framework == 'i-paes'):
# self.command = '%s%s' % (self.getPathAlgorithms(framework), algorithm)
# else:
# self.command = '%s%s' % (self.getPathExecute(), algorithm)
# except Exception, e:
# self.ShowErrorMessage("Error when setCommand\n%s" % e)
# def getCommand(self):
# return self.command
# def getProgram(self):
# return self.program
# # fazer com que ele pegue o diretorio deste arquivo e una com o nome do programa
# def setProgram(self, executable):
# global program
# self.program = executable
# utils/path
# def getPathExecution(self): # the directory where the execution will run
# return self.pathExecution
# def getPathExecute(self): # the folder where all the execution folders run
# try:
# # return "/home/alexandre/execute/"
# return "/dados/%s/execute/" % self.getLoggedUser()
# except Exception, e:
# self.ShowErrorMessage("Error when getPathExecute\n%s" % e)
# def getPathAlgorithms(self, framework):
# try:
# return "/home/%s/programs/%s/" % (self.getLoggedUser(), framework)
# except Exception, e:
# self.ShowErrorMessage("Error when getPathAlgorithms\n%s" % e)
# utils/__init__.py
# def ValidateEmail(self, email):
# try:
# email = email.replace('__at__', '@')
# if not(re.match('(.+)@(.+)\.(.+)', email, re.IGNORECASE)):
# raise Exception("Invalid email address. Please, insert a valid email adress.")
# return email
# except Exception, e:
# self.ShowErrorMessage("Error when ValidateEmail\n%s" % e)
# utils/path.py
# def CreateExecutionDirectory(self, email=None):
# try:
# now = datetime.datetime.now()
# tupla = now.timetuple()
# rand = random.randint(0, 1000)
# try: # dia #mes #ano #hora #min #seg
# if email is None:
# nome_diretorio = str(tupla[2]) + str(tupla[1]) + str(tupla[0]) \
# + "_" + str(tupla[3]) + str(tupla[4]) + str(tupla[5]) + "_" + str(rand) + "/"
# else:
# nome_diretorio = email + str(tupla[2]) + str(tupla[1]) + str(tupla[0]) \
# + "_" + str(tupla[3]) + str(tupla[4]) + str(tupla[5]) + "_" + str(rand) + "/"
# os.mkdir(os.path.join(self.getPathExecute(), nome_diretorio))
# os.chmod(os.path.join(self.getPathExecute(), nome_diretorio), stat.S_IRWXU)
# except Exception, e:
# self.ShowErrorMessage("Error when CreateExecutionDirectory\n%s" % e)
# # raise Exception("Error while creating the execution directory!\n%s" % e)
# self.pathExecution = nome_diretorio
# return nome_diretorio
# except Exception, e:
# self.ShowErrorMessage("Error when CreateExecutionDirectory\n%s" % e)
# utils/input.py
# def CreateLocalPopFile(self, path, pop_file):
# try:
# if(self.framework == '2PG'):
# arq_pop = open(path + "pop_0.pdb", "wr")
# models = 0
# for line in file(pop_file, "r"):
# arq_pop.write(line)
# if line.startswith("MODEL"):
# models += 1
# arq_pop.close()
# return models
# else:
# arq_pop = open(path + "pop_meamt.txt", "wr")
# ind = 0
# for line in file(pop_file, "r"):
# arq_pop.write(line)
# if line.startswith("##"):
# ind += 1
# arq_pop.close()
# return ind
# except Exception, e:
# self.ShowErrorMessage("Error when CreateLocalPopFile\n%s" % e)
# # raise Exception("Error while creating the population file!\n%s" % e)
# def CreateLocalFastaFile(self, path, type_input, fasta_file, tool):
# try:
# arq_fasta = open(path + "fasta.txt", "wr")
# caption = ''
# sequence = ''
# if tool in ('2PG_Random_Tool', '2PG_NSGA2_Tool', '2PG_MC_Metropolis', '2PG_Mono_Tool'):
# if type_input == '0':
# arq_fasta.write("none:A|PDBID|CHAIN|SEQUENCE"+'\n')
# arq_fasta.write(fasta_file)
# sequence = fasta_file
# caption = 'none'
# elif type_input == '1':
# for line in file(fasta_file, "r"):
# if len(caption) == 0:
# caption = line[1:5]
# else:
# sequence += line
# arq_fasta.write(line)
# elif tool == '2PG_BuildConformation_Tool':
# if(self.getParameterValue('force_field') == 'amber99sb-ildn'):
# linha = ''
# if type_input == '0':
# header = "none:A|PDBID|CHAIN|SEQUENCE"+'\n'
# linha = fasta_file # neste caso é só a sequência, mas a variável é a mesma
# elif type_input == '1':
# input_fasta = file(fasta_file, "r")
# lines = input_fasta.readlines()
# header = lines[0]
# linha = lines[1]
# if(self.getParameterValue('c_terminal_charge') == 'none' and
# self.getParameterValue('n_terminal_charge') == 'none'):
# arq_fasta.write(header)
# arq_fasta.write(linha)
# elif(self.getParameterValue('c_terminal_charge') == 'ACE' and
# self.getParameterValue('n_terminal_charge') == 'none'):
# arq_fasta.write('X')
# arq_fasta.write(linha)
# else:
# if(self.getParameterValue('n_terminal_charge') == 'NME' and
# self.getParameterValue('c_terminal_charge') == 'none'):
# linha = string.replace(linha, '\n', 'X')
# a = list(linha)
# linha = ''.join(a)
# arq_fasta.write(linha)
# arq_fasta.write('\n')
# else:
# arq_fasta.write('X')
# linha = string.replace(linha, '\n', 'X')
# a = list(linha)
# linha = ''.join(a)
# arq_fasta.write(linha)
# arq_fasta.write('\n')
# else:
# for line in file(fasta_file, "r"):
# arq_fasta.write(line)
# elif(tool == 'ProtPred_EDA'):
# if type_input == '0':
# arq_fasta.write(fasta_file)
# sequence = fasta_file
# caption = 'none'
# elif type_input == '1':
# for line in file(fasta_file, "r"):
# if len(caption) == 0:
# caption = line[1:5]
# else:
# arq_fasta.write(line.replace('\n', ''))
# sequence += line
# elif(tool in ('MEAMT_BuildConformation_Tool', 'MEAMT_Tool')):
# residues = 0
# if type_input == '0':
# residues = len(fasta_file.strip().replace("\n", ""))
# arq_fasta.write(str(residues))
# arq_fasta.write(fasta_file)
# sequence = fasta_file
# caption = 'none'
# elif type_input == '1':
# for line in file(fasta_file, "r"):
# if len(caption) == 0:
# caption = line[1:5]
# else:
# line = line.strip().replace("\n", "")
# sequence += line
# residues += len(line)
# arq_fasta.write(str(residues))
# arq_fasta.write("\n")
# arq_fasta.write(line)
# arq_fasta.close()
# return sequence
# except Exception, e:
# self.ShowErrorMessage("Error when CreateLocalFastaFile\n%s" % e)
# # raise Exception("Error while creating the local fasta file!\n%s" % e)
# def CreateLocalSeqFile(self, path, type_input, seq_file, tool):
# try:
# arq_fasta = open(path + "protein.seq", "wr")
# sequence = ''
# residues = 0
# if type_input == '0': # verify
# residues = len(seq_file.strip().replace("\n", ""))
# arq_fasta.write(seq_file)
# sequence = seq_file
# elif type_input == '1':
# for line in file(seq_file, "r"):
# residues += 1
# sequence += line.split(" ")[0] # three letter code
# arq_fasta.write(line.strip().replace("\n", ""))
# arq_fasta.write("\n") # TODO: do not insert an empty line
# arq_fasta.close()
# return sequence, residues
# except Exception, e:
# self.ShowErrorMessage("Error when CreateLocalSeqFile\n%s" % e)
# def CreateConfigurationFile(self, path):
# try:
# if(self.framework == '2PG'):
# arq = file(path + 'configuration.conf', "wr")
# params = self.general_parameters.items()
# for par in params:
# arq.write("%s = %s\n" % (par[0], par[1]))
# arq.close()
# elif(self.framework == 'ProtPred-EDA'):
# arq = file(path + 'input.ini', "wr")
# params = self.protpred_eda_param.items()
# param_extra = []
# for i, par in enumerate(params):
# if((par[0].find("[")) != -1):
# if(i == 0):
# arq.write("%s\n" % par[0])
# else:
# arq.write("\n%s\n" % par[0])
# elif(not isinstance(par[1], basestring)):
# arq.write("%s = %s\n" % (par[0], par[1][0]))
# else:
# arq.write("%s = %s\n" % (par[0], par[1]))
# if(self.getParameterValue("OptimMethod") == 'rw'):
# params = self.rw_param.items()
# elif(self.getParameterValue("OptimMethod") == 'mcm'):
# params = self.mcm_param.items()
# elif(self.getParameterValue("OptimMethod") == 'eda'):
# params = self.eda_param.items()
# if(self.getParameterValue("SamplingMode", "eda") == 'fgm'):
# param_extra = self.fgm_param.items()
# elif(self.getParameterValue("OptimMethod") == 'rboa'):
# params = self.rboa_param.items()
# elif(self.getParameterValue("OptimMethod") == 'ga'):
# params = self.ga_param.items()
# elif(self.getParameterValue("OptimMethod") == 'de'):
# params = self.de_param.items()
# elif(self.getParameterValue("OptimMethod") == 'ceda'):
# params = self.ceda_param.items()
# if(self.getParameterValue("SamplingMode", "ceda") == 'fgm'):
# param_extra = self.fgm_param.items()
# for i, par in enumerate(params):
# if((par[0].find("[")) != -1):
# if(i == 0):
# arq.write("\n%s\n" % par[0])
# else:
# arq.write("\n%s\n" % par[0])
# elif(not isinstance(par[1], basestring)):
# arq.write("%s = %s\n" % (par[0], par[1][0]))
# else:
# arq.write("%s = %s\n" % (par[0], par[1]))
# if(len(param_extra) > 0):
# for i, par in enumerate(param_extra):
# if((par[0].find("[")) != -1):
# if(i == 0):
# arq.write("\n%s\n" % par[0])
# else:
# arq.write("\n%s\n" % par[0])
# elif(not isinstance(par[1], basestring)):
# arq.write("%s = %s\n" % (par[0], par[1][0]))
# else:
# arq.write("%s = %s\n" % (par[0], par[1]))
# arq.close()
# elif(self.framework == 'MEAMT'):
# arq = file(path + 'parameters.txt', "wr")
# params = self.meamt_param.items()
# for i, par in enumerate(params):
# if((par[0].find("[")) != -1):
# if(i == 0):
# arq.write("%s\n" % par[0])
# else:
# arq.write("\n%s\n" % par[0])
# elif(not isinstance(par[1], basestring)):
# arq.write("%s = %s\n" % (par[0], par[1][0]))
# else:
# arq.write("%s = %s\n" % (par[0], par[1]))
# arq.close()
# except Exception, e:
# self.ShowErrorMessage("Error when CreateConfigurationFile\n%s" % e)
# # raise Exception("Error while creating the configuration file!\n%s" % e)
# utils/mail.py
# def getMessageEmail(self, tool_name):
# try:
# now = datetime.datetime.now()
# tupla = now.timetuple()
# data = str(tupla[2]) + '/' + str(tupla[1]) + '/' + str(tupla[0]) + ' ' + str(tupla[3]) + ':' + str(tupla[4]) + ':' + str(tupla[5])
# tool_name = tool_name.replace('_', ' ')
# messageEmail = '''Hi,
# Your simulation has been conclued at ''' + data + '''.
# You have to go to your History and download it.
# Best Regards.
# %s''' % tool_name
# return messageEmail
# except Exception, e:
# self.ShowErrorMessage("Error while getMessageEmail email!\n%s" % e)
# # raise Exception("Error while getMessageEmail email!\n%s" % e)
# def SendEmail(self, de, para, assunto, mensagem, arquivos, servidor):
# try:
# # Cria o objeto da mensagem
# msg = MIMEMultipart()
# # Define o cabeçalho
# msg['From'] = de
# msg['To'] = para
# msg['Date'] = formatdate(localtime=True)
# msg['Subject'] = assunto
# # Atacha o texto da mensagem
# msg.attach(MIMEText(mensagem))
# # Atacha os arquivos
# for arquivo in arquivos:
# parte = MIMEBase('application', 'octet-stream')
# parte.set_payload(open(arquivo, 'rb').read())
# encoders.encode_base64(parte)
# parte.add_header(
# 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(arquivo)
# )
# msg.attach(parte)
# # Conecta ao servidor SMTP
# smtp = smtplib.SMTP(servidor, 587)
# smtp.ehlo()
# smtp.starttls()
# smtp.ehlo()
# # Faz login no servidor
# smtp.login('adefelicibus@gmail.com', 'mami1752@')
# try:
# # Envia o e-mail
# smtp.sendmail(de, para, msg.as_string())
# finally:
# # Desconecta do servidor
# smtp.close()
# except Exception, e:
# self.ShowErrorMessage("Error when SendEmail:\n%s" % e)
# # raise Exception("Error while sending email!\n%s" % e)
# util/__init__
# def ShowErrorMessage(self, msg):
# error = sys.__stderr__
# error.write(msg)
# error.flush()
# sys.stderr = error
# sys.exit(1)
# # sys.stderr.write(msg)
# # sys.exit()
# def showMessage(self, msg):
# print msg
# def ShowWarningMessage(self, msg):
# info = sys.__stdout__
# info.write(msg)
# info.flush()
# sys.stdout = info
# utils/__init__.py
# def CopyNecessaryFiles(self, new_path):
# try:
# os.chdir(new_path)
# fileList = [os.path.normcase(f)
# for f in os.listdir(self.getPathExecute())]
# fileList = [os.path.join(self.getPathExecute(), f)
# for f in fileList]
# for arquivo in fileList:
# if not os.path.isdir(arquivo):
# if(self.framework == 'MEAMT'):
# shutil.copy(arquivo, new_path)
# else:
# if(os.path.splitext(arquivo.split('/')[-1])[1] != '.txt'):
# shutil.copy(arquivo, new_path)
# else:
# if not(re.search(r'\w+@\w+', arquivo)) and not(re.search(r'\d+_', arquivo)):
# shutil.copytree(arquivo, os.path.join(new_path, arquivo.split('/')[-1]))
# except Exception, e:
# self.ShowErrorMessage("Error when CopyNecessaryFiles:\n%s" % e)
# framework/framework
# def ExecuteProgram(
# self, program, config, path_execution, path_output,
# tool, email, framework='2PG', galaxydir="None", outputID="None"):
# try:
# stdout_file = open("%sstdout.txt" % self.getPathExecution(), "wr")
# retProcess = None
# retProcess = subprocess.Popen([
# 'nohup',
# program,
# self.getCommand(),
# config,
# path_execution,
# galaxydir,
# path_output,
# outputID,
# tool,
# framework,
# email,
# '&'],
# stdout=stdout_file, stderr=subprocess.STDOUT, shell=False)
# if retProcess is not None:
# pass
# except Exception, e:
# self.ShowErrorMessage("Error when ExecuteProgram:\n%s" % e)
# utils/output
# def getResultFiles(self, path, tool, fileName=None):
# try:
# resultFile = ''
# filesToHtml = []
# os.chdir(path)
# # if tool == '2PG_Random_Tool':
# # resultFile = '%s%s' % (path, 'random_algorithm_solutions.pdb')
# if tool == '2PG_SortByFront_Tool':
# resultFile = '%s%s.zip' % (path, tool)
# z = zipfile.ZipFile(resultFile, 'w', zipfile.ZIP_DEFLATED)
# listaArquivosFront = self.listDirectory(path, '*.front')
# for arq in listaArquivosFront:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosXvg = self.listDirectory(path, '*.xvg')
# for arq in listaArquivosXvg:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosPng = self.listDirectory(path, '*.png')
# for arq in listaArquivosPng:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosLog = self.listDirectory(path, '*.log')
# for arq in listaArquivosLog:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# elif tool in (
# 'Dominance_Ranking', '2PG_SortMethodByFront_Tool',
# 'CalculateRMSD', 'CalculateTMScore', 'CalculateGDTTS'):
# resultFile = '%s%s.zip' % (path, tool)
# z = zipfile.ZipFile(resultFile, 'w', zipfile.ZIP_DEFLATED)
# listaArquivosFront = self.listDirectory(path, '*.front')
# for arq in listaArquivosFront:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosXvg = self.listDirectory(path, '*.xvg')
# for arq in listaArquivosXvg:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosPdf = self.listDirectory(path, '*.pdf')
# for arq in listaArquivosPdf:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosPng = self.listDirectory(path, '*.png')
# for arq in listaArquivosPng:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosTxt = self.listDirectory(path, '*.txt')
# for arq in listaArquivosTxt:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosLog = self.listDirectory(path, '*.log')
# for arq in listaArquivosLog:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# elif tool == '2PG_BuildConformation_Tool':
# resultFile = '%s%s' % (path, 'pop_0.pdb')
# elif tool in (
# '2PG_NSGA2_Tool', '2PG_Mono_Tool',
# '2PG_MC_Metropolis', '2PG_Random_Tool'):
# resultFile = '%s%s.zip' % (path, tool)
# z = zipfile.ZipFile(resultFile, 'w', zipfile.ZIP_DEFLATED)
# if(fileName):
# listaArquivosPDB = self.listDirectory(path, '%s*.pdb' % fileName)
# else:
# listaArquivosPDB = self.listDirectory(path, '*.pdb')
# for arq in listaArquivosPDB:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosXvg = self.listDirectory(path, '*.xvg')
# for arq in listaArquivosXvg:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosFit = self.listDirectory(path, '*.fit')
# for arq in listaArquivosFit:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosPng = self.listDirectory(path, '*.png')
# for arq in listaArquivosPng:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# # listaArquivosPdb = self.listDirectory(path, 'PROT_IND_*.pdb')
# # for arq in listaArquivosPdb:
# # z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# # z.write(arq)
# # z.close()
# # filesToHtml.append(os.path.join(path, arq))
# # elif tool == '2PG_MC_Metropolis':
# # os.chdir(path)
# # resultFile = '%s%s' % (path, 'monte_carlo_solutions.pdb')
# # elif(tool == 'ProtPred_EDA'):
# # resultFile = '%s%s' % (path, '/ProtPredEDA_out.zip')
# # z = zipfile.ZipFile(resultFile, 'w', zipfile.ZIP_DEFLATED)
# # self.copyFilesToExecuteFolder(path)
# # listaArquivosPDB = self.listDirectory(path, '*.pdb')
# # for arq in listaArquivosPDB:
# # z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# # z.write(arq)
# # z.close()
# # listadic = self.listDirectory(path)
# # self.zip_folder(listadic[0], resultFile)
# elif(tool == 'ProtPred_EDA'):
# resultFile = '%s%s.zip' % (path, tool)
# z = zipfile.ZipFile(resultFile, 'w', zipfile.ZIP_DEFLATED)
# listaArquivosPDB = self.listDirectory(path, '*.pdb')
# for arq in listaArquivosPDB:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosPng = self.listDirectory(path, '*.png')
# for arq in listaArquivosPng:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# elif tool == 'Download_From_Quark':
# resultFile = '%s%s' % (path, '/ResultQuark.zip')
# z = zipfile.ZipFile(resultFile, 'w', zipfile.ZIP_DEFLATED)
# listaArquivosPDB = self.listDirectory(path, '*.pdb')
# for arq in listaArquivosPDB:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# listaArquivosTxt = self.listDirectory(path, '*.txt')
# for arq in listaArquivosTxt:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# elif(tool == 'MEAMT_BuildConformation_Tool'):
# resultFile = '%s%s' % (path, 'pop_meamt.txt')
# elif(tool == 'MEAMT_Tool'): # criar o html tbm, depois
# # resultFile = '%s%s' % (path, 'protein.pdb')
# resultFile = '%s%s.zip' % (path, tool)
# z = zipfile.ZipFile(resultFile, 'w', zipfile.ZIP_DEFLATED)
# listaArquivosPDB = self.listDirectory(path, '*.pdb')
# for arq in listaArquivosPDB:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosPng = self.listDirectory(path, '*.png')
# for arq in listaArquivosPng:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# listaArquivosTxt = self.listDirectory(path, 'subpop*.txt')
# for arq in listaArquivosTxt:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# filesToHtml.append(os.path.join(path, arq))
# return resultFile, filesToHtml
# except Exception, e:
# self.ShowErrorMessage("Error when getResultFiles:\n%s" % e)
# # raise Exception("Error while getting result files: \n%s" % e)
# utils/input
# def copyFilesToExecuteFolder(self, path, prefix_filename=None):
# try:
# job_folder = os.path.join(path, 'out')
# contents = os.walk(job_folder)
# for root, folders, files in contents:
# for folder in folders:
# pass
# for file_name in files:
# name, ext = os.path.splitext(file_name)
# if(ext == '.pdb'):
# src = os.path.join(root, file_name)
# if(prefix_filename):
# new_filename = prefix_filename + '-' + file_name
# dst = os.path.join(path, new_filename)
# else:
# dst = os.path.join(path, file_name)
# shutil.copy(src, dst)
# except Exception, e:
# self.ShowErrorMessage("Error when copyFilesToExecuteFolder:\n%s" % e)
# utils/__init__
# def zip_folder(self, folder_path, output_path):
# """Zip the contents of an entire folder (with that folder included
# in the archive). Empty subfolders will be included in the archive
# as well.
# """
# parent_folder = os.path.dirname(folder_path)
# # Retrieve the paths of the folder contents.
# contents = os.walk(folder_path)
# try:
# zip_file = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)
# for root, folders, files in contents:
# # Include all subfolders, including empty ones.
# for folder_name in folders:
# absolute_path = os.path.join(root, folder_name)
# relative_path = absolute_path.replace(parent_folder + '\\', '')
# zip_file.write(absolute_path, relative_path)
# for file_name in files:
# absolute_path = os.path.join(root, file_name)
# relative_path = absolute_path.replace(parent_folder + '\\', '')
# zip_file.write(absolute_path, relative_path)
# zip_file.close()
# except Exception, e:
# self.ShowErrorMessage("Error when zipFolder:\n%s" % e)
# # raise Exception("Error while zipping folder: \n%s" % e)
# def listDirectory(self, directory, ereg=None):
# from natsort import natsorted
# try:
# # if self.framework == '2PG':
# fileList = [os.path.normcase(f)
# for f in os.listdir(directory)]
# fileList = [os.path.normcase(f)
# for f in fileList
# if fnmatch.fnmatch(f, ereg)]
# # else:
# # fileList = [os.path.normcase(f)
# # for f in os.listdir(directory)]
# # fileList = [os.path.normcase(f)
# # for f in fileList
# # if os.path.isdir(f) and (re.search(r'out', f))]
# return natsorted(fileList)
# except Exception, e:
# self.ShowErrorMessage("Error when listDirectory:\n%s" % e)
# # raise Exception("Error while listing the directory.\n%s" % e)
# utils/output
# def sendOutputResults(self, path_output, file_output, file_result):
# try:
# dest = path_output + "/" + file_output
# copia = "cp " + file_result + " " + dest
# os.system(copia)
# # shutil.copy(arquivo, new_path)
# except Exception, e:
# self.ShowErrorMessage("Error when sendOutputResults:\n%s" % e)
# # raise Exception("Error while sending output files: \n%s" % e)
# def sendOutputFilesHtml(self, path, files): # copia os arquivos listados em files para o path
# try:
# for f in files:
# shutil.copy(f, path)
# except Exception, e:
# self.ShowErrorMessage("Error when sendOutputFilesHtml:\n%s" % e)
# # raise Exception("Error: %s" % e)
# utils/input.py
# def format_fitness(self, fitness, tool=None):
# try:
# if(tool != 'Dominance_Ranking'):
# fe = string.split(fitness.rstrip(), ',')
# no_obj = len(fe)
# if fe[0] == 'None':
# raise Exception("Please, use checkboxes to specify the objectives.\n")
# if int(no_obj) < 2:
# raise Exception("Please, you must select more than 1 objective.\n")
# fit = ''
# for obj in fe:
# fit += '%s, ' % obj
# fit = fit.strip(', ')
# return no_obj, fit
# else:
# comb = [] # fitness combination
# i = 0
# fe = fitness.split('#')
# for fit in range(len(fe)):
# if len(fe[fit]) > 0:
# fitn = fe[fit].strip().replace(str(i), '')
# comb.append(fitn)
# i = i + 1
# return comb
# except Exception, e:
# self.ShowErrorMessage("Error when FormatFitness:\n%s" % e)
# # raise Exception("Error: %s" % e)
# utils/pdb.py
# # metodo para separar os modelos dentro de um PDB
# def parse_PDB(self, path, pdb_file, maxNumber=None, newName=None):
# try:
# pdb = file(pdb_file, 'r')
# path_f, name_f = os.path.split(pdb_file)
# name_f = name_f.split('.')[0]
# name_f = name_f.replace('_', '-')
# hearder = []
# new_pdbs = []
# for i, line in enumerate(open(pdb_file)):
# if len(new_pdbs) == maxNumber:
# break
# if i < 3: # mudar, um arquivo pdb pode ter mais de 3 linhas de header
# hearder.append(line)
# if line.startswith("MODEL"):
# l = line.split(" ")
# if newName is None:
# new_pdb = os.path.join(path, '%s-M%s.pdb' % (name_f, str(l[8].strip())))
# else:
# new_pdb = os.path.join(path, '%s-M%s.pdb' % (newName, str(l[8].strip())))
# new_pdb_f = file(new_pdb, 'wr')
# new_pdbs.append('%s-M%s.pdb' % (name_f, str(l[8].strip())))
# if int(str(l[8].strip())) > 1: # se o model for diferente de 1, coloca o header
# for head in hearder:
# new_pdb_f.write(head)
# while not line.startswith("ENDMDL"):
# line = pdb.readline()
# new_pdb_f.write(line)
# new_pdb_f.close()
# return new_pdbs
# except Exception, e:
# self.ShowErrorMessage("Error when parsePDB:\n%s" % e)
# # raise Exception("Error: %s" % e)
# def mergePDB(self, path, pdbs):
# try:
# if not pdbs:
# self.ShowErrorMessage("There is no PDB file to merge.")
# new_pdb = []
# header = []
# for idx, pdb_file in enumerate(pdbs):
# pdb = open(os.path.join(path, pdb_file), 'r')
# for line in pdb:
# if idx == 0: # primeiro arquivo, copia o cabeçalho
# if not line.startswith("ATOM") and \
# not line.startswith("MODEL") and \
# not line.startswith("TER") and not line.startswith("ENDMDL"):
# header.append(line)
# elif not line.startswith("ATOM"):
# continue
# else:
# new_pdb.append(line)
# else:
# if not line.startswith("ATOM"):
# continue
# else:
# new_pdb.append(line)
# new_pdb.append("TER\n")
# new_pdb.append("ENDMDL\n")
# if (idx + 2) <= len(pdbs):
# new_pdb.append("MODEL %s\n" % (idx + 2))
# pdbf = os.path.join(path, 'MergedPDB.pdb')
# new_pdb_f = file(pdbf, 'wr')
# new_pdb_f.write(''.join(header))
# new_pdb_f.write(''.join('MODEL 1\n'))
# new_pdb_f.write(''.join(new_pdb))
# new_pdb_f.write('\n')
# new_pdb_f.close()
# return pdbf
# except Exception, e:
# self.ShowErrorMessage("Error when mergePDB:\n%s" % e)
# # raise Exception("Error: %s" % e)
# utils/output
# def sendMultipleOutputs(self, path, files, path_output, outputID):
# try:
# for pdb in files:
# # pdb_name = pdb.split(".")[0].split("_")[2]
# name, ext = os.path.splitext(pdb)
# ext = ext.replace('.', '')
# pdb_name = os.path.basename(pdb)
# new_name = "%s_%s_%s_%s_%s" % ('primary', outputID, pdb_name, 'visible', ext)
# f = os.path.join(path, pdb)
# dest = path_output + '/' + new_name
# copia = "cp " + f + " " + dest
# os.system(copia)
# except Exception, e:
# self.ShowErrorMessage("Error when sendMultipleOutputs:\n%s" % e)
# # raise Exception("Error sendMultipleOutputs: %s" % e)
# def openURL(self, url, path_output, file_name):
# """
# Download the file from `url` and save it locally under `file_name`
# """
# try:
# response = urllib2.urlopen(url)
# file_result = os.path.join(path_output, file_name)
# out_file = open(file_result, 'wb')
# out_file.write(response.read())
# out_file.close()
# except Exception, e:
# self.ShowErrorMessage("Error when openURL:\n%s" % e)
# def extractZipFile(self, zipFile, path):
# try:
# with zipfile.ZipFile(zipFile) as zip_file:
# for member in zip_file.namelist():
# filename = os.path.basename(member)
# # skip directories
# if not filename:
# continue
# # copy file (taken from zipfile's extract)
# source = zip_file.open(member)
# target = file(os.path.join(path, filename), "wb")
# with source, target:
# shutil.copyfileobj(source, target)
# except Exception, e:
# self.ShowErrorMessage("Error when extractZipFile:\n%s" % e)
# # raise Exception("Error on extractZipFile: %s" % e)
# def extractGzFile(self, gzfile, path):
# try:
# shutil.copy(gzfile, path)
# subprocess.call(
# ["atool", '-q', '-X', path, os.path.join(path, os.path.basename(gzfile))])
# # TODO: Verificar se o arquivo tem folder e tratar
# except Exception, e:
# self.ShowErrorMessage("Error when extractGzFile:\n%s" % e)
# # raise Exception("Error on extractGzFile: %s" % e)
# utils/input.py
# def copyPDBsFromInput(
# self,
# path_execute,
# path_to,
# inputnames,
# inputPDBs):
# try:
# nomes_arquivos = []
# for n in inputnames.split(','):
# if len(n) > 0:
# name, ext = os.path.splitext(n)
# name = name.replace(' ', '-').replace('(', '').replace(')', '')
# if ext.find('.pdb') < 0:
# raise Exception('%s is not a PDB file' % name)
# else:
# if not ext.endswith('.pdb'):
# extname = ext.replace(
# '.pdb', '').strip().replace('(', '-').replace(')', '')
# new_name = name + extname + '.pdb'
# nomes_arquivos.append(new_name)
# arquivos = []
# arqs = inputPDBs.partition(',')
# arquivos.append(arqs[0])
# while(len(arqs[2]) > 0):
# arqs = arqs[2].partition(',')
# arquivos.append(arqs[0])
# for i, n in enumerate(nomes_arquivos):
# link_name = os.path.join(path_to, os.path.basename(n))
# if not os.path.exists(link_name):
# os.symlink(arquivos[i], link_name)
# os.system("cp %s %s" % (link_name, path_execute))
# except Exception, e:
# self.ShowErrorMessage("Error when copyPDBsFromInput:\n%s" % e)
# urila/path
# def clearPathExecute(self, path):
# try:
# if os.path.isdir(path):
# shutil.rmtree(path)
# return True
# else:
# self.ShowErrorMessage("It is not a path:\n%s" % path)
# return False
# except Exception, e:
# self.ShowErrorMessage("Error when clearPathExecute:\n%s" % e)
# return False
# utils/__init__
# def getFileSize(self, fpath, outpath):
# """
# format a nice file size string
# """
# try:
# size = ''
# fp = os.path.join(outpath, fpath)
# if os.path.isfile(fp):
# size = '0 B'
# n = float(os.path.getsize(fp))
# if n > 2**20:
# size = '%1.1f MB' % (n/2**20)
# elif n > 2**10:
# size = '%1.1f KB' % (n/2**10)
# elif n > 0:
# size = '%d B' % (int(n))
# return size
# except Exception, e:
# self.ClassColection.ShowErrorMessage(
# "Error on getFileSize\n%s" % e)
#
# def compressFiles(self, files, path, toolname):
# # TODO: validar se files is a list
# try:
# os.chdir(path)
# resultFile = '%s%s.zip' % (path, toolname)
# z = zipfile.ZipFile(resultFile, 'w', zipfile.ZIP_DEFLATED)
# for arq in files:
# z = zipfile.ZipFile(resultFile, 'a', zipfile.ZIP_DEFLATED)
# z.write(arq)
# z.close()
# return True
# except Exception, e:
# self.ShowErrorMessage("Error when compressFiles:\n%s" % e)
|
{"/lib/koala/config.py": ["/lib/koala/version.py"]}
|
42,532,519
|
adefelicibus/koala-server
|
refs/heads/master
|
/fabfile.py
|
# -*- coding: utf-8 -*-
import os
from fabric.api import *
from fabric.contrib.files import upload_template, append, sed, exists, comment
import getpass
CURRENT_PATH = os.path.dirname(os.path.abspath(__file__))
LOGGED_USER = getpass.getuser()
# Configurações para o Cloud USP - Ribeirão
# IP Externo 200.144.255.35
# VM (22) (80)
# docking01 2221 8084
# docking02 2227 8085
# docking03 2228 8086
# docking04 2229 8087
# docking05 2230 8088
# docking06 2231 8089
# docking07 2232 8090
# docking08 2233 8091
# docking09 2234 8092
# docking10 2235 8093
# docking11 2236 8094
# docking12 2224 8095
# USER THAT WILL EXECUTE THE KOALA SERVER
user = 'alexandre'
# Settings to Postgres Database
bd = 'koaladb'
user_db = 'koala'
passwd_db = 'koala'
# IP SERVER
ip_server = "200.144.255.35"
# LOCAL
folder_local = '/home/%s/koala-test/' % user
galaxy_path = '/home/%s/koala-test/galaxy/' % user
data_path = '/home/%s/koala-test/dados/' % user
# GALAXY
galaxy_user = 'galaxyproject'
galaxy_project = 'galaxy'
galaxy_repository = 'git@github.com:%s/%s.git' % (galaxy_user, galaxy_project)
# PULSAR
pulsar_user = 'galaxyproject'
pulsar_project = 'pulsar'
pulsar_repository = 'git@github.com:%s/%s.git -b master' % (pulsar_user, pulsar_project)
# KOALA
koala_user = 'adefelicibus'
koala_project = 'koala-server'
koala_repository = 'git@github.com:%s/%s.git' % (koala_user, koala_project)
# koala server
username = 'koala'
port = 2221
port_http = 8084
koala_server = '%s@%s -p %s' % (username, ip_server, port)
env_path = '/home/%s/env/bin/activate' % username
# # pulsar server 1, docking03
# username = 'koala'
# port_http = 8086
# pulsar_server_1 = '%s@%s' % (username, ip_server)
# # pulsar server 2, docking04
# username = 'koala'
# port_http = 8087
# pulsar_server_2 = '%s@%s' % (username, ip_server)
# # pulsar server 3, docking05
# username = 'koala'
# port_http = 8088
# pulsar_server_3 = '%s@%s' % (username, ip_server)
# # pulsar server 4, docking06
# username = 'koala'
# port_http = 8089
# pulsar_server_4 = '%s@%s' % (username, ip_server)
# pulsar server 5, docking07
# username = 'koala'
# port_http = 8090
# pulsar_server_5 = '%s@%s' % (username, ip_server)
# # pulsar server 6, docking08
# username = 'koala'
# port_http = 8091
# pulsar_server_6 = '%s@%s' % (username, ip_server)
# # pulsar server 7, docking09
username = 'koala'
port_http = 8092
pulsar_server_7 = '%s@%s' % (username, ip_server)
# # pulsar server 8, docking10
# username = 'koala'
# port_http = 8093
# pulsar_server_8 = '%s@%s' % (username, ip_server)
# # pulsar server 9, docking11
# username = 'koala'
# port_http = 8094
# pulsar_server_9 = '%s@%s' % (username, ip_server)
# # pulsar server 10, docking12
# username = 'koala'
# port_http = 8095
# pulsar_server_10 = '%s@%s' % (username, ip_server)
# # pulsar server 11, docking2
# username = 'koala'
# port_http = 8085
# pulsar_server_11 = '%s@%s' % (username, ip_server)
# hosts
# env.hosts = ["myserver.net"]
# env.user = "koala"
env.key_filename = "/home/%s/.ssh/id_rsa" % LOGGED_USER
# env.password = ""
env.port = 2234
env.hosts = [pulsar_server_7]
env.forward_agent = True
# -------------------------------
# SERVER
# -------------------------------
# ANTES DE QUALQUER COISA, CRIAR O USUARIO $user, COLOCAR COMO ROOT,
# LOGAR, CRIAR O SSH-KEYGEN, COPIAR
# SSH KEY DO COMPUTADOR LOCAL PARA O AUTHORIZED_KEYS NO SERVIDOR
# ssh-copy-id -i ~/.ssh/id_rsa.pub remote-host
def testserver():
with cd('~/'):
run('ls')
def reboot():
"""Reinicia o servidor"""
sudo('reboot')
def locale_server():
sudo('locale-gen --no-purge --lang pt_BR')
# update no servidor
def update_server():
"""Atualizando pacotes no servidor"""
log('Atualizando pacotes')
sudo('apt-get -y update')
# upgrade no servidor
def upgrade_server():
"""Updating programs"""
log('Updating programs')
sudo('apt-get -y upgrade')
def build_server():
"""Install all necessary packages"""
log('Installing all necessary packages')
sudo('apt-get -y install git')
sudo('apt-get -y install python-dev')
sudo('apt-get -y install python-pip')
sudo('apt-get -y install zip')
sudo('apt-get -y install python-virtualenv')
sudo('apt-get -y install pymol')
sudo('apt-get -y install postgresql postgresql-contrib')
sudo('pip install virtualenvwrapper')
sudo('apt-get -y install openmpi-bin openmpi-doc libopenmpi-dev')
sudo('apt-get -y install automake')
sudo('apt-get -y install nginx supervisor')
sudo('apt-get -y install libcurl4-gnutls-dev')
sudo('apt-get -y install libffi-dev')
sudo('apt-get -y install python-numpy')
# reboot()
def createDirectories_server(path=None):
if(not exists('~/programs', use_sudo=True)):
sudo('mkdir ~/programs')
if(not exists('~/envs', use_sudo=True)):
sudo('mkdir ~/envs')
if(not exists('/dados/%s/execute' % user, use_sudo=True)):
sudo('mkdir -p /dados/%s/execute' % user)
sudo('chown %s:%s ~/envs' % (user, user))
sudo('chown %s:%s ~/programs' % (user, user))
sudo('chown -R %s:%s /dados/%s' % (user, user, user))
def installzlib_server():
with cd('~/programs'):
sudo('wget http://zlib.net/zlib-1.2.8.tar.gz')
sudo('tar xzf zlib-1.2.8.tar.gz')
with cd('zlib-1.2.8'):
sudo('./configure')
sudo('make')
sudo('make install')
with cd('~/programs'):
sudo('rm zlib-1.2.8.tar.gz')
def installFFTW_server():
with cd('~/programs'):
sudo('wget http://www.fftw.org/fftw-3.3.4.tar.gz')
sudo('tar xzf fftw-3.3.4.tar.gz')
with cd('fftw-3.3.4'):
sudo('./configure --enable-float')
sudo('make')
sudo('make install')
with cd('~/programs'):
sudo('rm fftw-3.3.4.tar.gz')
def installGROMACS_server():
with cd('~/programs'):
sudo('wget ftp://ftp.gromacs.org/pub/gromacs/gromacs-4.6.5.tar.gz')
sudo('tar xzf gromacs-4.6.5.tar.gz')
with cd('gromacs-4.6.5'):
sudo('mkdir build')
sudo('cd build/')
sudo(
'cmake /home/koala/programs/gromacs-4.6.5/ -DSHARED_LIBS_DEFAULT=OFF '
'-DBUILD_SHARED_LIBS=OFF -DGMX_PREFER_STATIC_LIBS=YES '
'-DGMX_BUILD_OWN_FFTW=OFF -DFFTW_LIBRARY=/usr/local/lib/libfftw3f.a '
'-DFFTW_INCLUDE_DIR=/usr/local/include/ '
'-DGMX_GSL=OFF -DGMX_DEFAULT_SUFFIX=ON -DGMX_GPU=OFF '
'-DGMX_MPI=OFF -DGMX_DOUBLE=OFF '
'-DGMX_INSTALL_PREFIX=/home/%s/programs/gmx-4.6.5/no_mpi/ '
'-DCMAKE_INSTALL_PREFIX=/home/%s/programs/gmx-4.6.5/no_mpi/' % (user, user))
sudo('make -j 8')
sudo('make install')
with cd('~/programs'):
sudo('rm -r gromacs-4.6.5')
sudo('rm gromacs-4.6.5.tar.gz')
def installVINA_server():
with cd('~/programs'):
sudo('mkdir autodock-vina')
with cd('autodock-vina'):
sudo('wget http://vina.scripps.edu/download/autodock_vina_1_1_2_linux_x86.tgz')
sudo('tar zxvf autodock_vina_1_1_2_linux_x86.tgz')
with cd('autodock_vina_1_1_2_linux_x86'):
sudo('mv * ../')
sudo('rm -rf autodock_vina_1_1_2_linux_x86.tgz')
sudo('rm -rf autodock_vina_1_1_2_linux')
append(
'~/.bashrc',
['export VINA=$HOME/programs/autodock-vina/bin/vina'],
use_sudo=True,
)
sudo('source ~/.bashrc')
def installMGL_server():
with cd('~/programs'):
sudo('mkdir mgltools')
with cd('mgltools'):
sudo('wget http://mgltools.scripps.edu/downloads/downloads/tars/releases/ \
REL1.5.6/mgltools_x86_64Linux2_1.5.6.tar.gz')
sudo('tar zxvf mgltools_x86_64Linux2_1.5.6.tar.gz')
with cd('mgltools_x86_64Linux2_1.5.6'):
sudo('mv * ../')
sudo('rm -rf mgltools_x86_64Linux2_1.5.6.tar.gz')
sudo('rm -rf mgltools_x86_64Linux2_1.5.6')
sudo('./install.sh -d ~/programs/mgltools')
append(
'~/.bashrc',
['export PATH=~/programs/mgltools/bin:$PATH',
'export SCRIPT_LIGAND4=$HOME/programs/mgltools/MGLToolsPckgs/ \
AutoDockTools/Utilities24/prepare_ligand4.py',
'export PYTHONSH=$HOME/programs/mgltools/bin/pythonsh',
'export SCRIPT_RECEPTOR4=$HOME/programs/mgltools/MGLToolsPckgs/ \
AutoDockTools/Utilities24/prepare_receptor4.py',
'alias pmv=\'~/programs/mgltools/bin/pmv\'',
'alias adt=\'~/programs/mgltools/bin/adt\'',
'alias vision=\'~/programs/mgltools/bin/vision\'',
'alias pythonsh=\'~/programs/mgltools/bin/pythonsh\''],
use_sudo=True,
)
sudo('source ~/.bashrc')
# http://docs.fabfile.org/en/latest/api/contrib/files.html
def setVirtualenv_server():
append(
'~/.bashrc',
['export WORKON_HOME=~/envs',
'source /usr/local/bin/virtualenvwrapper.sh'],
use_sudo=True,
)
append(
'~/.profile',
['export WORKON_HOME=~/envs',
'source /usr/local/bin/virtualenvwrapper.sh'],
use_sudo=True,
)
sudo('source ~/.bashrc')
sudo('source ~/.profile')
def setPythonPath():
append(
'~/.bashrc',
['export PYTHONPATH=/usr/lib/python2.7/dist-packages:$PYTHONPATH',
'export PYTHONPATH=/usr/lib/python2.7/dist-packages/pymol:$PYTHONPATH',
'export PYTHONPATH=/usr/local/lib/python2.7/dist-packages:$PYTHONPATH',
'export PYTHONPATH=/usr/local/bin/pymol/modules:$PYTHONPATH',
'export MPI_DIR=/lib/openmpi',
'export PATH=/lib/openmpi/bin:$PATH',
'export LD_LIBRARY_PATH=/lib/openmpi/lib:$LD_LIBRARY_PATH'],
use_sudo=True,
)
sudo('source ~/.bashrc')
def installPyHighcharts_server():
with cd('~/programs'):
run('git clone git@github.com:adefelicibus/PyHighcharts.git')
with cd('/usr/lib/python2.7/dist-packages'):
sudo('ln -s /home/%s/programs/PyHighcharts/ PyHighcharts' % user)
def install2PGCartesian():
path = '2pg_cartesian'
with cd("~/programs"):
run('git clone git@github.com:rodrigofaccioli/2pg_cartesian.git %s' % path)
with cd('~/programs/%s' % path):
run('mkdir build')
with cd('build'):
run('cmake ..')
run('make')
sudo('make install')
# def install2PGBuildConformation():
# cd /usr/local/bin
# sudo ln -s /home/koala/programs/2pg_build_conformation/src/protpred-Gromacs_pop_initial .
# def installMEAMT():
# cp ~/programs/meamt/aemt-mo-up2
# cp ~/programs/meamt/aemt-pop-up2
# pass
# clone Koala
def cloneKoala_server():
""" Criar novo projeto local """
log('Criando novo projeto')
run('git clone %s' % koala_repository)
with cd('%s' % koala_project):
run('mkvirtualenv %s' % koala_project)
run('pip install -r requirements.txt')
def buildEnvKoala_server():
sudo('workon %s' % koala_project)
sudo('pip install -U distribute')
sudo('pip install pycrypto')
sudo('pip install natsort')
sudo('pip install beautifulsoup4')
sudo('pip install certifi')
sudo('pip install pyopenssl ndg-httpsclient pyasn1')
sudo('pip install pycurl')
sudo('pip install fabric')
# clone Pulsar
def clonePulsar_server():
""" Criar novo projeto local """
log('Criando novo projeto')
run('git clone %s' % pulsar_repository)
with cd('%s' % pulsar_project):
run('mkvirtualenv %s' % pulsar_project)
sudo('pip install -r requirements.txt')
def buildEnvPulsar():
run('workon %s' % pulsar_project)
sudo('pip install -U distribute')
sudo('pip install pycrypto')
sudo('pip install natsort')
sudo('pip install beautifulsoup4')
sudo('pip install certifi')
sudo('pip install pyopenssl ndg-httpsclient pyasn1')
sudo('pip install pycurl')
def setKoalaLibLink_server():
sudo(
'ln -s /home/koala/koala-server/lib/koala/ \
/home/koala/envs/%s/lib/python2.7/site-packages/koala' % pulsar_project)
def setConfigNginx():
write_file('%s/config/nginx_server.conf' % CURRENT_PATH, '/etc/nginx/nginx.conf', 'config')
def setSitePulsarNginx():
write_file(
'%s/config/site-koala' % CURRENT_PATH, '/etc/nginx/sites-available/site-koala', 'config')
sed(
'/etc/nginx/sites-available/site-koala',
before='8000',
after='%s' % port_http,
use_sudo=True)
sudo('ln -s /etc/nginx/sites-available/site-koala /etc/nginx/sites-enabled/site-koala')
nginx_restart()
def setPulsarConfig():
with cd('/home/%s/%s/' % (user, pulsar_project)):
run('cp server.ini.sample server.ini')
sed(
'/home/koala/pulsar/server.ini',
before='8913',
# before='8000',
after='%s' % port_http,
use_sudo=True)
comment(
'/home/koala/pulsar/server.ini',
regex='host = localhost',
use_sudo=True)
def setPulsarApp():
write_file('%s/config/app.yml' % CURRENT_PATH, '/home/koala/pulsar/', 'config')
def startPulsar():
with cd('~/pulsar/'):
run('paster serve server.ini --daemon')
def copyExecuteFiles():
with cd('/dados/koala/'):
run('cp -rR ~/%s/execute/ .' % koala_project)
def setLibOpenMPI():
sudo('ln -s sudo ln -s /usr/lib/libmpi_cxx.so.0.0.1 /usr/lib/libmpi_cxx.so.1')
sudo('ln -s /usr/lib/openmpi/lib/libmpi_cxx.so.0.0.1 /usr/lib/openmpi/lib/libmpi_cxx.so.1')
sudo('ln -s /usr/lib/libmpi.so.0 /usr/lib/libmpi.so.1')
sudo('ln -s /usr/lib/openmpi/lib/libmpi.so /usr/lib/openmpi/lib/libmpi.so.1')
def updateKoala():
# atualizar o koala em todos os server
pass
def installScripts():
pass
def newServerPulsar():
"""Configurar e instalar todos pacotes necessários para servidor"""
log('Configurar e instalar todos pacotes necessários para servidor')
locale_server()
update_server()
upgrade_server()
build_server()
createDirectories_server()
installzlib_server()
installFFTW_server()
installGROMACS_server()
installVINA_server()
installMGL_server()
setVirtualenv_server()
setPythonPath()
installPyHighcharts_server()
install2PGCartesian()
cloneKoala_server()
# buildEnvKoala_server()
clonePulsar_server()
buildEnvPulsar()
setKoalaLibLink_server()
setConfigNginx()
setSitePulsarNginx()
setPulsarConfig()
setPulsarApp()
startPulsar()
copyExecuteFiles()
log('Reiniciando a máquina')
reboot()
# -------------------------------
# GLOBAL METHODS
# -------------------------------
def nginx_restart():
"""Restart nginx no servidor"""
log('restart nginx')
sudo('/etc/init.d/nginx restart')
def write_file(filename, destination, path_template):
upload_template(
filename=filename,
destination=destination,
# template_dir=os.path.join(CURRENT_PATH, 'inc'),
template_dir=os.path.join(CURRENT_PATH, path_template),
context=env,
# use_jinja=True,
use_sudo=True,
backup=True
)
def upload_public_key():
"""Faz o upload da chave ssh para o servidor"""
log('Adicionando chave publica no servidor')
ssh_file = '~/.ssh/id_rsa.pub'
target_path = '~/.ssh/uploaded_key.pub'
put(ssh_file, target_path)
run('echo `cat ~/.ssh/uploaded_key.pub` >> \
~/.ssh/authorized_keys && rm -f ~/.ssh/uploaded_key.pub')
def login():
local("ssh %s" % pulsar_server_1)
def log(message):
print """
==============================================================
%s
==============================================================
""" % message
# -------------------------------
# LOCAL
# -------------------------------
def localLocale():
local('sudo locale-gen --no-purge --lang pt_BR')
def createLocalUser(user_senha=None):
"""Criar um usuário no servidor"""
if not user_senha:
user_senha = raw_input('Digite a senha do usuário: ')
log('Criando usuário {0}'.format(user))
local(
'sudo useradd -m -p '
'pass=$(perl -e \'print crypt($ARGV[0], "password")\' \'{0}\') {1}'.format(
user_senha, user))
print '\nSenha usuário: {0}'.format(user_senha)
local('sudo gpasswd -a %s sudo' % user)
print '\n============================================================='
# Update local
def updateLocal():
"""Atualizando pacotes no servidor"""
log('Atualizando pacotes')
local('sudo apt-get -y update')
# Upgrade local
def upgradeLocal():
"""Updating programs"""
log('Updating programs')
local('sudo apt-get -y upgrade')
# install system dependencies
def buildLocal():
"""Install all necessary packages"""
log('Installing all necessary packages')
local('sudo apt-get -y install git')
local('sudo apt-get -y install python-dev')
local('sudo apt-get -y install python-pip')
local('sudo apt-get -y install zip')
local('sudo apt-get -y install python-virtualenv')
local('sudo apt-get -y install pymol')
local('sudo apt-get -y install postgresql postgresql-contrib')
local('sudo pip install virtualenvwrapper')
local('sudo apt-get -y install openmpi-bin openmpi-doc libopenmpi-dev')
local('sudo apt-get -y install automake')
local('sudo apt-get -y install nginx supervisor')
local('sudo apt-get -y install libcurl4-gnutls-dev')
local('sudo apt-get -y install libffi-dev')
local('sudo apt-get -y install python-numpy')
local('sudo apt-get -y install gsl-bin libgsl0-dev')
def createDirectoriesLocal(path=None):
if(not os.path.exists('%sprograms' % folder_local)):
local('sudo mkdir -p %sprograms' % folder_local)
if(not os.path.exists('%senvs' % folder_local)):
local('sudo mkdir -p %senvs' % folder_local)
if(not os.path.exists('%sexecute' % data_path)):
local('sudo mkdir -p %sexecute' % data_path)
local('sudo chown %s:%s %senvs' % (user, user, folder_local))
local('sudo chown %s:%s %sprograms' % (user, user, folder_local))
local('sudo chown -R %s:%s %s' % (user, user, data_path))
def installZlibLocal():
with lcd('%sprograms' % folder_local):
local('wget http://zlib.net/zlib-1.2.8.tar.gz')
local('tar xzf zlib-1.2.8.tar.gz')
with lcd('zlib-1.2.8'):
local('./configure')
local('make')
local('sudo make install')
with lcd('%sprograms' % folder_local):
local('rm zlib-1.2.8.tar.gz')
def installFFTWlocal():
with lcd('%sprograms' % folder_local):
local('wget http://www.fftw.org/fftw-3.3.4.tar.gz')
local('tar xzf fftw-3.3.4.tar.gz')
with lcd('fftw-3.3.4'):
local('./configure --enable-float')
local('make')
local('sudo make install')
with lcd('%sprograms' % folder_local):
local('rm fftw-3.3.4.tar.gz')
def installGROMACSlocal():
with lcd('%sprograms' % folder_local):
local('wget ftp://ftp.gromacs.org/pub/gromacs/gromacs-4.6.5.tar.gz')
local('tar xzf gromacs-4.6.5.tar.gz')
with lcd('gromacs-4.6.5'):
local('mkdir build')
with lcd('build'):
local(
'cmake .. -DSHARED_LIBS_DEFAULT=OFF '
'-DBUILD_SHARED_LIBS=OFF -DGMX_PREFER_STATIC_LIBS=YES '
'-DGMX_BUILD_OWN_FFTW=OFF -DFFTW_LIBRARY=/usr/local/lib/libfftw3f.a '
'-DFFTW_INCLUDE_DIR=/usr/local/include/ '
'-DGMX_GSL=OFF -DGMX_DEFAULT_SUFFIX=ON -DGMX_GPU=OFF '
'-DGMX_MPI=OFF -DGMX_DOUBLE=OFF '
'-DGMX_INSTALL_PREFIX=%sprograms/gmx-4.6.5/no_mpi/ '
'-DCMAKE_INSTALL_PREFIX=%sprograms/gmx-4.6.5/no_mpi/' % (
folder_local, folder_local))
local('make -j 8')
local('sudo make install')
with lcd('%sprograms' % folder_local):
local('rm -r gromacs-4.6.5')
local('rm gromacs-4.6.5.tar.gz')
def installVINA_local():
with lcd('%sprograms' % folder_local):
local('mkdir autodock-vina')
with lcd('autodock-vina'):
local('wget http://vina.scripps.edu/download/autodock_vina_1_1_2_linux_x86.tgz')
local('tar zxvf autodock_vina_1_1_2_linux_x86.tgz')
with lcd('autodock_vina_1_1_2_linux_x86'):
local('mv * ../')
local('rm -rf autodock_vina_1_1_2_linux_x86.tgz')
local('rm -rf autodock_vina_1_1_2_linux')
local(
'sudo echo "export VINA=%sprograms/autodock-vina/bin/vina" >> ~/.bashrc' %
folder_local)
local("/bin/bash -l -c 'source ~/.bashrc'")
def installMGL_local():
with lcd('%sprograms' % folder_local):
local('mkdir mgltools')
with lcd('mgltools'):
local('wget http://mgltools.scripps.edu/downloads/downloads/tars/releases/ \
REL1.5.6/mgltools_x86_64Linux2_1.5.6.tar.gz')
local('tar zxvf mgltools_x86_64Linux2_1.5.6.tar.gz')
with lcd('mgltools_x86_64Linux2_1.5.6'):
local('mv * ../')
local('rm -rf mgltools_x86_64Linux2_1.5.6.tar.gz')
local('rm -rf mgltools_x86_64Linux2_1.5.6')
local('./install.sh -d %sprograms/mgltools' % folder_local)
local('sudo echo "export PATH=%sprograms/mgltools/bin:$PATH\n'
'export SCRIPT_LIGAND4=%sprograms/mgltools/MGLToolsPckgs/ \
AutoDockTools/Utilities24/prepare_ligand4.py\n'
'export PYTHONSH=%sprograms/mgltools/bin/pythonsh\n'
'export SCRIPT_RECEPTOR4=%sprograms/mgltools/MGLToolsPckgs/ \
AutoDockTools/Utilities24/prepare_receptor4.py\n'
'alias pmv=\'%sprograms/mgltools/bin/pmv\'\n'
'alias adt=\'%sprograms/mgltools/bin/adt\'\n'
'alias vision=\'%sprograms/mgltools/bin/vision\'\n'
'alias pythonsh=\'%sprograms/mgltools/bin/pythonsh\'" >> ~/.bashrc' %
(
folder_local, folder_local, folder_local, folder_local,
folder_local, folder_local, folder_local, folder_local))
local("/bin/bash -l -c 'source ~/.bashrc'")
def setVirtualenvlocal():
local('echo "export WORKON_HOME=%senvs" >> ~/.bashrc' % folder_local)
local('echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bashrc')
local('echo "export WORKON_HOME=%senvs" >> ~/.profile' % folder_local)
local('echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.profile')
local("/bin/bash -l -c 'source ~/.bashrc'")
local("/bin/bash -l -c 'source ~/.profile'")
def setPythonPathLocal():
local(
'sudo echo "export PYTHONPATH=/usr/lib/python2.7/dist-packages:$PYTHONPATH\n'
'export PYTHONPATH=/usr/lib/python2.7/dist-packages/pymol:$PYTHONPATH\n'
'export PYTHONPATH=/usr/local/lib/python2.7/dist-packages:$PYTHONPATH\n'
'export PYTHONPATH=/usr/local/bin/pymol/modules:$PYTHONPATH\n'
'export MPI_DIR=/lib/openmpi\n'
'export PATH=/lib/openmpi/bin:$PATH\n'
'export LD_LIBRARY_PATH=/lib/openmpi/lib:$LD_LIBRARY_PATH" >> ~/.bashrc')
local("/bin/bash -l -c 'source ~/.bashrc'")
def installPyHighchartsLocal():
with lcd('%sprograms' % folder_local):
local('git clone git@github.com:adefelicibus/PyHighcharts.git')
with lcd('/usr/lib/python2.7/dist-packages'):
local('sudo ln -s %sprograms/PyHighcharts/ PyHighcharts' % folder_local)
def install2PGCartesianLocal():
path = '2pg_cartesian'
with lcd("%sprograms" % folder_local):
local('git clone git@github.com:rodrigofaccioli/2pg_cartesian.git %s' % path)
with lcd(path):
local('mkdir build')
with lcd('build'):
local('cmake ..')
local('make')
local('sudo make install')
def install2PGBuildConformationLocal():
path = '2pg_build_conformation'
with lcd("%sprograms" % folder_local):
local('git clone git@github.com:rodrigofaccioli/2pg_build_conformation.git %s' % path)
with lcd('%s/src' % path):
local('make')
with lcd("/usr/local/bin"):
local('sudo ln -s %sprograms/%s/src/Gromacs_pop_initial .' % (folder_local, path))
def installMEAMT():
# cp ~/programs/meamt/aemt-mo-up2
# cp ~/programs/meamt/aemt-pop-up2
pass
def installDependenciesLocal():
pass
def cloneGalaxyLocal():
with lcd('%sprograms' % folder_local):
local('git clone %s' % galaxy_repository)
with lcd('%s' % galaxy_project):
local("sudo /bin/bash -l -c 'mkvirtualenv %s'" % galaxy_project)
local("sudo chown -R %s:%s %senvs/%s" % (user, user, folder_local, galaxy_project))
local('sudo pip install -r requirements.txt')
def buildEnvGalaxyLocal():
local("sudo /bin/bash -l -c 'workon %s'" % galaxy_project)
local('sudo pip install -U distribute')
local('sudo pip install pycrypto')
local('sudo pip install natsort')
local('sudo pip install beautifulsoup4')
local('sudo pip install certifi')
local('sudo pip install pyopenssl ndg-httpsclient pyasn1')
local('sudo pip install pycurl')
local('sudo pip install fabric')
local("sudo /bin/bash -l -c 'deactivate'")
def setKoalaLibLinksLocal():
local(
'sudo ln -s %s/lib/koala/ %senvs/%s/lib/python2.7/site-packages/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/config/datatypes_conf.xml %sprograms/%s/config/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/config/galaxy.ini %sprograms/%s/config/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/config/integrated_tool_panel.xml %sprograms/%s/config/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/config/job_conf.xml %sprograms/%s/config/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/config/tool_conf.xml %sprograms/%s/config/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/datatypes/confFiles.py %sprograms/%s/lib/galaxy/datatypes/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/datatypes/gromacs_datatype.py %sprograms/%s/lib/galaxy/datatypes/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/datatypes/molFiles.py %sprograms/%s/lib/galaxy/datatypes/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/tools/analysis/ %sprograms/%s/tools/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/tools/gromacs-tools/ %sprograms/%s/tools/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/tools/meamt/ %sprograms/%s/tools/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/tools/pdb-tools/ %sprograms/%s/tools/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/tools/protpred-2pg/ %sprograms/%s/tools/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/tools/protpred-eda/ %sprograms/%s/tools/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/tools/autodock-vina/ %sprograms/%s/tools/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/static/Bio-200.png %sprograms/%s/static/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/static/LOGO-ICMC-RGB-300.png %sprograms/%s/static/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/static/koala.css %sprograms/%s/static/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/static/logo-koala.png %sprograms/%s/static/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/static/usp-logo-300px.png %sprograms/%s/static/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/static/welcome.html %sprograms/%s/static/' % (
CURRENT_PATH, folder_local, galaxy_project))
def copyExecuteFilesLocal():
local('cp -rR %s/execute/ %s' % (CURRENT_PATH, data_path))
def setLibOpenMPILocal():
local('sudo ln -s /usr/lib/libmpi_cxx.so.0.0.1 /usr/lib/libmpi_cxx.so.1')
local(
'sudo ln -s /usr/lib/openmpi/lib/libmpi_cxx.so.0.0.1 /usr/lib/openmpi/lib/libmpi_cxx.so.1')
local('sudo ln -s /usr/lib/libmpi.so.0 /usr/lib/libmpi.so.1')
local('sudo ln -s /usr/lib/openmpi/lib/libmpi.so /usr/lib/openmpi/lib/libmpi.so.1')
def installScriptsLocal():
local(
'sudo ln -s %s/scripts/check_structures_gromacs.py %sprograms/%s/scripts/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/scripts/min.sh %sprograms/%s/scripts/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/scripts/prepare_structures.py %sprograms/%s/scripts/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/scripts/rename_atoms.py %sprograms/%s/scripts/' % (
CURRENT_PATH, folder_local, galaxy_project))
local(
'sudo ln -s %s/scripts/residue_renumber_all_pdbs.py %sprograms/%s/scripts/' % (
CURRENT_PATH, folder_local, galaxy_project))
def createDBKoalaLocal():
local(
"echo 'CREATE USER %s SUPERUSER INHERIT CREATEDB CREATEROLE;' |"
" sudo -u postgres psql" % user_db)
local(
'echo "ALTER USER %s PASSWORD \'koalaa\';" |'
' sudo -u postgres psql' % user_db)
local(
"echo 'CREATE DATABASE %s --OWNER %s;' |"
" sudo -u postgres psql" % (bd, user_db))
def runKoalaLocal():
log('Running Koala server local')
local('sh %sprograms/%s/run.sh --reload' % (folder_local, galaxy_project))
def newKoalaLocal():
"""Create a new Koala Server local"""
log('Creating a new Koala Server local')
localLocale()
createLocalUser()
updateLocal()
upgradeLocal()
buildLocal()
createDirectoriesLocal()
installZlibLocal()
installFFTWlocal()
installGROMACSlocal()
installVINA_local()
installMGL_local()
setVirtualenvlocal()
setPythonPathLocal()
installPyHighchartsLocal()
install2PGCartesianLocal()
cloneGalaxyLocal()
buildEnvGalaxyLocal()
setKoalaLibLinksLocal()
copyExecuteFilesLocal()
setLibOpenMPILocal()
installScriptsLocal()
createDBKoalaLocal()
runKoalaLocal()
# lixo
# # ------------------------------------------------------------
# def server():
# """inicia o servidor do Galaxy local"""
# log('Iniciando servidor do Galaxy')
# local('sh galaxy-dist/run.sh --reload')
# def update_tool_local(tool_name):
# """Atualiza tool no diretório do Galaxy"""
# log('Atualizando tool no diretorio do Galaxy')
# if not os.path.exists(tool_path):
# os.mkdir(tool_path)
# warn("Criando o diretório raiz das tools")
# if not os.path.exists(os.path.join(os.getcwd(), ''.join([tool_name, '.xml']))):
# abort("Tool não encontrada.")
# else:
# local('cp %s.py %s.xml %s' % (tool_name, tool_name, tool_path))
# def update_tool_server(tool_name, server=''):
# """Atualiza tool no diretório do Galaxy no servidor"""
# log('Atualizando tool no diretorio do Galaxy no servidor')
# if not os.path.exists(os.path.join(os.getcwd(), ''.join([tool_name, '.xml']))):
# abort("Tool não encontrada.")
# else:
# local('scp %s.py %s.xml %s:%s' % (tool_name, tool_name, cloud_server, project_path))
# def update_all_tools_local():
# pass
# def reinitialize_server(server=''):
# '''Reinitile the remote server'''
# log('Reinitilizing the remote server')
# with settings(warn_only=True):
# if run('screen -R -S "Galaxy" -p 0 -X exec sh %s/run.sh --reload' % galaxy_path).failed:
# log('There is no screen availabe. \nYou must create a new screen.\nAfter that, type CTRL + A + D to deatached it')
# if confirm("Do you want to create a new screen now? "):
# create_remote_screen()
# run('screen -R -S "Galaxy" -p 0 -X exec sh %s/run.sh --reload' % galaxy_path)
# else:
# abort("There is no screen available");
# def create_remote_screen():
# '''Create a new screen'''
# log("Creating a new screen.")
# run('screen -R -S "Galaxy"')
# def upload_public_key():
# """faz o upload da chave ssh para o servidor"""
# log('Adicionando chave publica no servidor')
# ssh_file = '~/.ssh/id_rsa.pub'
# target_path = '~/.ssh/uploaded_key.pub'
# put(ssh_file, target_path)
# run('echo `cat ~/.ssh/uploaded_key.pub` >> ~/.ssh/authorized_keys && rm -f ~/.ssh/uploaded_key.pub')
# def remote_pull():
# """git pull remoto"""
# log('Atualizando aplicação no servidor')
# login()
# with cd(project_path):
# run('git pull origin master')
|
{"/lib/koala/config.py": ["/lib/koala/version.py"]}
|
42,579,772
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/LMTrace/models.py
|
import torch
from torch import nn
from torch.nn import CrossEntropyLoss
from transformers import AutoModel, BertPreTrainedModel
import logging
from transformers.models.electra.modeling_electra import ElectraClassificationHead
logger = logging.getLogger(__name__)
MODEL_ARCH_SINGLE = "single"
MODEL_ARCH_SIAMESE = "siamese"
class AvgPooler(nn.Module):
def __init__(self, config):
super().__init__()
self.hidden_size = config.hidden_size
self.pooler = torch.nn.AdaptiveAvgPool2d((1, config.hidden_size))
def forward(self, hidden_states):
return self.pooler(hidden_states).view(-1, self.hidden_size)
class RelationClassifyHeader(nn.Module):
"""
use averaging pooling across tokens to replace first_token_pooling.
"""
def __init__(self, config):
super().__init__()
self.hidden_size = config.hidden_size
self.s_pooler = AvgPooler(config)
self.t_pooler = AvgPooler(config)
self.dense = nn.Linear(config.hidden_size * 3, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.output_layer = nn.Linear(config.hidden_size, 2)
def forward(self, s_hidden, t_hidden):
pool_s_hidden = self.s_pooler(s_hidden)
pool_t_hidden = self.t_pooler(t_hidden)
diff_hidden = torch.abs(pool_s_hidden - pool_t_hidden)
concated_hidden = torch.cat((pool_s_hidden, pool_t_hidden), 1)
concated_hidden = torch.cat((concated_hidden, diff_hidden), 1)
x = self.dropout(concated_hidden)
x = self.dense(x)
x = torch.tanh(x)
x = self.dropout(x)
x = self.output_layer(x)
return x
class LMTraceSingle(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.bert = AutoModel.from_config(config)
self.cls = ElectraClassificationHead(config)
self.init_weights()
def forward(self, input_ids, attention_mask, token_type_ids, labels=None, **kwargs):
hidden = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
).last_hidden_state
logits = self.cls(hidden)
output_dict = dict()
if labels is not None:
loss_fct = CrossEntropyLoss() # loss fct need logits without softmax
loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
output_dict["loss"] = loss
output_dict["logits"] = torch.softmax(logits, 1)
return output_dict
class LMTraceSiamese(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.lm = AutoModel.from_config(config)
self.classifier = RelationClassifyHeader(config)
self.init_weights()
def forward(
self,
s_input_ids=None,
s_attention_mask=None,
t_input_ids=None,
t_attention_mask=None,
labels=None,
**kwargs
):
s_hidden = self.lm(
s_input_ids, attention_mask=s_attention_mask
).last_hidden_state
t_hidden = self.lm(
t_input_ids, attention_mask=t_attention_mask
).last_hidden_state
logits = self.cls(s_hidden=s_hidden, t_hidden=t_hidden)
output_dict = {}
if labels is not None:
loss_fct = CrossEntropyLoss()
rel_loss = loss_fct(logits.view(-1, 2), labels.view(-1))
output_dict["loss"] = rel_loss
output_dict["logits"] = torch.softmax(logits, 1)
return output_dict # (rel_loss), rel_score
def get_sim_score(self, s_hidden, t_hidden):
logits = self.classifier(t_hidden=s_hidden, s_hidden=t_hidden)
sim_scores = torch.softmax(logits, 1).data.tolist()
return [x[1] for x in sim_scores]
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,579,773
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/server/default_config.py
|
class DefaultConfig:
DB_SERVER = "localhost"
DB_NAME = "trace_model"
DB_USER = "trace_model"
DB_PASSWD = "123456"
OUTPUT_DIR = "./train_output"
LOG_DIR = "./log"
# TODO add config for production server
class ProductionConfig(DefaultConfig):
pass
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,579,774
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/baseline/IR_model.py
|
import numpy, sys, os
sys.path.append("../..")
from gensim import corpora, models, matutils
from gensim.models import TfidfModel
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import re, time
import argparse
from dataclasses import field, dataclass
from transformers.hf_argparser import HfArgumentParser
from LMTrace.metrics import TraceMetrics
from tqdm import tqdm
import pandas as pd
from gensim.models.ldamodel import LdaModel
from gensim.models.lsimodel import LsiModel
from LMTrace.data_structure import CSVReader, TOKEN, SOID, TOID, SID, TID
from torch.utils.data import DataLoader
import logging
stop_words = stopwords.words("english")
logger = logging.getLogger(__name__)
class VSM:
def __init__(self):
self.tfidf_model: TfidfModel = None
def build_model(self, docs_tokens):
print("Building VSM model...")
dictionary = corpora.Dictionary(docs_tokens)
corpus = [dictionary.doc2bow(x) for x in docs_tokens]
self.tfidf_model = models.TfidfModel(corpus, id2word=dictionary)
print("Finish building VSM model")
def _get_doc_similarity(self, doc1_tk, doc2_tk):
doc1_vec = self.tfidf_model[self.tfidf_model.id2word.doc2bow(doc1_tk)]
doc2_vec = self.tfidf_model[self.tfidf_model.id2word.doc2bow(doc2_tk)]
return matutils.cossim(doc1_vec, doc2_vec)
def get_link_scores(self, source, target):
s_tokens = source[TOKEN].split()
t_tokens = target[TOKEN].split()
score = self._get_doc_similarity(s_tokens, t_tokens)
return score
class LDA:
def __init__(self):
self.ldamodel = None
def build_model(self, docs_tokens, num_topics=200, passes=500):
dictionary = corpora.Dictionary(docs_tokens)
corpus = [dictionary.doc2bow(x) for x in docs_tokens]
self.ldamodel = LdaModel(
corpus,
num_topics=num_topics,
id2word=dictionary,
passes=passes,
alpha="auto",
random_state=numpy.random.RandomState(1),
)
def get_topic_distrb(self, doc):
bow_doc = self.ldamodel.id2word.doc2bow(doc)
return self.ldamodel.get_document_topics(bow_doc)
def get_link_scores(self, source, target):
"""
:param doc1_tk: Preprocessed documents as tokens
:param doc2_tk: Preprocessed documents as tokens
:return:
"""
doc1_tk = source[TOKEN].split()
doc2_tk = target[TOKEN].split()
dis1 = self.get_topic_distrb(doc1_tk)
dis2 = self.get_topic_distrb(doc2_tk)
return matutils.cossim(dis1, dis2)
class LSI:
def __init__(self):
self.lsi = None
def build_model(self, docs_tokens, num_topics=200):
dictionary = corpora.Dictionary(docs_tokens)
corpus = [dictionary.doc2bow(x) for x in docs_tokens]
self.lsi = LsiModel(corpus, num_topics=num_topics, id2word=dictionary)
def get_topic_distrb(self, doc):
bow_doc = self.lsi.id2word.doc2bow(doc)
return self.lsi[bow_doc]
def get_link_scores(self, source, target):
doc1_tk = source[TOKEN].split()
doc2_tk = target[TOKEN].split()
dis1 = self.get_topic_distrb(doc1_tk)
dis2 = self.get_topic_distrb(doc2_tk)
return matutils.cossim(dis1, dis2)
def preprocess(text):
clean_text = re.sub("\W+", " ", text).lower()
tokens = word_tokenize(clean_text)
tokens = [tk for tk in tokens if tk not in stop_words]
res = []
for tk in tokens:
res.extend(tk.split("_"))
return res
@dataclass
class DataTrainingArguments:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
"""
model_name: str = field(
default=None,
metadata={"help": "VSM, LDA, LSI"},
)
output_dir: str = field(
default=None, metadata={"help": "directory to store outputs"}
)
train_dir: str = field(
default=None, metadata={"help": "directory for trianing dataset"}
)
test_dir: str = field(
default=None, metadata={"help": "direcotry for testing dataset"}
)
source_file: str = field(
default="source_art.csv", metadata={"help": "source artifact file name"}
)
target_file: str = field(
default="target_art.csv", metadata={"help": "target artifact file name"}
)
link_file: str = field(default="link.csv", metadata={"help": "link file name"})
def gen_retrival_dataset(examples):
dataset = []
for sid in examples.s_index:
for tid in examples.t_index:
label = 1 if tid in examples.s2t[sid] else 0
dataset.append((sid, tid, label))
return dataset
def run(arg_dict=None):
exe_time = 0
parser = HfArgumentParser(DataTrainingArguments)
if arg_dict is not None:
args = parser.parse_dict(arg_dict)
elif len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
args = parser.parse_args_into_dataclasses()
args = args[0]
args.output_dir = os.path.join(args.output_dir, args.model_name)
if not os.path.isdir(args.output_dir):
os.makedirs(args.output_dir)
train_examples = CSVReader(
data_dir=args.train_dir,
dataset_name="train",
sart=args.source_file,
tart=args.target_file,
lk=args.link_file,
).get_examples()
test_examples = CSVReader(
data_dir=args.test_dir,
dataset_name="test",
sart=args.source_file,
tart=args.target_file,
lk=args.link_file,
).get_examples()
doc_tokens = [x[TOKEN].split() for x in train_examples.t_index.values()]
logger.info(f"indexing data on {len(doc_tokens)} artifacts...")
logger.debug(doc_tokens[:20])
logger.info("building model {}".format(args.model_name))
if args.model_name == "VSM":
model = VSM()
model.build_model(doc_tokens)
elif args.model_name == "LDA":
model = LDA()
model.build_model(doc_tokens, num_topics=200, passes=500)
elif args.model_name == "LSI":
model = LSI()
model.build_model(doc_tokens, num_topics=200)
else:
raise Exception("Model not found...")
# work
retrival_dataloader = DataLoader(
gen_retrival_dataset(test_examples), batch_size=1000
)
start_time = time.time()
res = []
for batch in tqdm(retrival_dataloader, desc="retrival evaluation"):
for s_id, t_id, label in zip(
batch[0].tolist(), batch[1].tolist(), batch[2].tolist()
):
pred = model.get_link_scores(
test_examples.s_index[s_id], test_examples.t_index[t_id]
)
s_oid = test_examples.s_index[s_id][SOID]
t_oid = test_examples.t_index[t_id][TOID]
res.append((s_oid, t_oid, pred, label))
df = pd.DataFrame()
df["s_id"] = [x[0] for x in res]
df["t_id"] = [x[1] for x in res]
df["pred"] = [round(x[2],4) for x in res]
df["label"] = [x[3] for x in res]
max_score = max(df["pred"])
df["confid"] = [round(x[2] / max_score,4) for x in res]
exe_time = time.time() - start_time
raw_res_file = os.path.join(args.output_dir, "raw_res.csv")
logger.info("writing raw results")
df.to_csv(raw_res_file)
logger.info("Evaluating results")
m = TraceMetrics(df, output_dir=args.output_dir)
summary = m.write_summary(exe_time)
logger.info(summary)
if __name__ == "__main__":
run()
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,579,775
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/LMTrace/train.py
|
import logging
import os
import re
import sys
import pandas as pd
from dataclasses import field, dataclass
from typing import Optional
from transformers import (
HfArgumentParser,
TrainingArguments,
AutoConfig,
AutoTokenizer,
default_data_collator,
DataCollatorWithPadding,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process, set_seed
from LMTrace.data_structure import CSVReader, SID, TID, SOID, TOID, PRED, LABEL
from LMTrace.models import (
LMTraceSingle,
LMTraceSiamese,
MODEL_ARCH_SINGLE,
MODEL_ARCH_SIAMESE,
)
from LMTrace.trainer import SingleTLMTrainer, compute_metrics
from LMTrace.metrics import TraceMetrics
from tqdm import tqdm
logger = logging.getLogger(__name__)
@dataclass
class DataTrainingArguments(TrainingArguments):
"""
Arguments pertaining to what data we are going to input our model for training and eval.
"""
model_name_or_path: str = field(
default=None,
metadata={
"help": "Path to pretrained language model (LM) or model identifier from huggingface.co/models. e.g. google/electra-small-discriminator"
},
)
train_dir: Optional[str] = field(
default=None, metadata={"help": "Directory for training dataset"}
)
valid_dir: Optional[str] = field(
default=None, metadata={"help": "Directory for validation dataset"}
)
test_dir: Optional[str] = field(
default=None, metadata={"help": "Directory for test dataset"}
)
source_file: Optional[str] = field(
default="source_art.csv", metadata={"help": "source artifact file name"}
)
target_file: Optional[str] = field(
default="target_art.csv", metadata={"help": "target artifact file name"}
)
link_file: Optional[str] = field(
default="link.csv", metadata={"help": "link file name"}
)
valid_query_num: Optional[str] = field(
default=-1,
metadata={
"help": "max number of trace queries as validation dataset. If a value smaller than 1 is given it will include all queries"
},
)
pad_to_max_length: Optional[bool] = field(
default=True,
metadata={
"help": "pad the sequence with white space if not enough token exist"
},
)
resample_rate: Optional[int] = field(
default=1,
metadata={"help": "Resampling rate of positive examples in training dataset."},
)
example_sampling_strategy: Optional[int] = field(
default="static_random",
metadata={
"help": "The strategy of creating training dataset. Once positive examples(links) are provided, we create and load negative examples with different strategy."
+ "static_random: default method which create datasets before training and reuse the dataset in each epoch"
+ "dynamic_random: create dataset with new negative examples Randomly at the beginning of each epoch"
+ "offline_neg_sampling: create dataset with hard negative examples at the beginning of each epoch (TODO)"
+ "online_neg_sampling: create hard negative examples at batch level (TODO)"
},
)
max_seq_length: Optional[int] = field(
default=512, metadata={"help": "max length of an artifact sequence "}
)
model_arch: str = field(
default=MODEL_ARCH_SINGLE,
metadata={
"help": "Model architecture in format of <language model type>_<Single/Siamese>. e.g. electra_single, electra_siamese, bert_single, bert_siamese"
},
)
def main(
arg_dict=None,
train_reader=None,
valid_reader=None,
test_reader=None,
link_writer=None,
):
parser = HfArgumentParser(DataTrainingArguments)
if arg_dict is not None:
args = parser.parse_dict(arg_dict)
elif len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
args = parser.parse_args_into_dataclasses()
training_args = model_args = data_args = args[0]
# Detecting last checkpoint.
last_checkpoint = None
if (
os.path.isdir(training_args.output_dir)
and training_args.do_train
and not training_args.overwrite_output_dir
):
last_checkpoint = get_last_checkpoint(training_args.output_dir)
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
raise ValueError(
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
"Use --overwrite_output_dir to overcome."
)
elif last_checkpoint is not None:
logger.info(
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
)
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger.setLevel(
logging.INFO if is_main_process(training_args.local_rank) else logging.WARN
)
set_seed(training_args.seed)
config = AutoConfig.from_pretrained(model_args.model_name_or_path)
tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path)
config.num_labels = 2
pad_on_right = tokenizer.padding_side == "right"
if data_args.max_seq_length > tokenizer.model_max_length:
logger.warn(
f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"
f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
)
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
data_collator = (
default_data_collator
if data_args.pad_to_max_length
else DataCollatorWithPadding(
tokenizer, pad_to_multiple_of=8 if training_args.fp16 else None
)
)
if model_args.model_arch.endswith(MODEL_ARCH_SINGLE):
model = LMTraceSingle.from_pretrained(
model_args.model_name_or_path, config=config
)
trainer = SingleTLMTrainer(
model=model,
tokenizer=tokenizer,
args=training_args,
data_collator=data_collator,
compute_metrics=compute_metrics,
)
elif model_args.model_arch.endswith(MODEL_ARCH_SIAMESE):
model = LMTraceSiamese.from_pretrained(
model_args.model_name_or_path, config=config
)
else:
raise Exception(
f"model with {model_args.model_arch} architecture is not supported "
)
# Training
if training_args.do_train:
if train_reader is None:
train_reader = CSVReader(
data_dir=data_args.train_dir,
dataset_name="train",
sart=data_args.source_file,
tart=data_args.target_file,
lk=data_args.link_file,
)
train_examples = train_reader.get_examples()
if valid_reader is None:
valid_reader = CSVReader(
data_dir=data_args.valid_dir,
dataset_name="valid",
sart=data_args.source_file,
tart=data_args.target_file,
lk=data_args.link_file,
)
valid_examples = valid_reader.get_examples()
# train dataset may need dynamic generation thus we provide raw examples
trainer.train_dataset = train_examples
trainer.eval_dataset = valid_examples.gen_trace_dataset(
tokenizer,
MODEL_ARCH_SINGLE, # TODO replace with params
query_num=data_args.valid_query_num,
max_seq_length=max_seq_length,
for_validation=True,
)
if last_checkpoint is not None:
checkpoint = last_checkpoint
elif os.path.isdir(model_args.model_name_or_path):
checkpoint = model_args.model_name_or_path
else:
checkpoint = None
train_result = trainer.train(resume_from_checkpoint=checkpoint)
trainer.save_model() # Saves the tokenizer too for easy upload
output_train_file = os.path.join(training_args.output_dir, "train_results.txt")
if trainer.is_world_process_zero():
with open(output_train_file, "w") as writer:
logger.info("***** Train results *****")
for key, value in sorted(train_result.metrics.items()):
logger.info(f" {key} = {value}")
writer.write(f"{key} = {value}\n")
# Need to save the state, since Trainer.save_model saves only the tokenizer with the model
trainer.state.save_to_json(
os.path.join(training_args.output_dir, "trainer_state.json")
)
# Evaluation
# Evaluate need metrics to produce
if training_args.do_eval or training_args.do_predict:
if test_reader is None:
test_reader = CSVReader(
data_dir=data_args.test_dir,
dataset_name="valid",
sart=data_args.source_file,
tart=data_args.target_file,
lk=data_args.link_file,
)
test_examples = test_reader.get_examples()
test_dataset = test_examples.gen_trace_dataset(
tokenizer,
MODEL_ARCH_SINGLE,
with_label=training_args.do_eval,
max_seq_length=max_seq_length,
)
logger.info("*** Evaluate ***")
results = trainer.predict(test_dataset)
preds = results.predictions[:, 1] # get the score for label 1
output_raw_res = os.path.join(training_args.output_dir, "eval_raw.txt")
if trainer.is_world_process_zero():
columns = [SID, TID, PRED]
if training_args.do_eval:
columns.append(LABEL)
df = pd.DataFrame(columns=columns)
for e, pred in tqdm(zip(test_dataset, preds), desc="Write raw results"):
row = {
SID: test_examples.s_index[e[SID]][SOID],
TID: test_examples.t_index[e[TID]][TOID],
PRED: float(round(pred, 4)),
}
if training_args.do_eval:
row[LABEL] = int(e[LABEL])
df = df.append(row, ignore_index=True)
if link_writer is None:
df.to_csv(output_raw_res, index=False)
else:
link_writer.write(df)
if training_args.do_eval:
logger.info("***** Eval results *****")
m = TraceMetrics(
df,
output_dir=training_args.output_dir,
source_col=SID,
target_col=TID,
pred_col=PRED,
label_col=LABEL,
)
exe_time = results.metrics["eval_runtime"]
extra_info = dict()
extra_info[
"model_info"
] = f"Loading best model from {trainer.state.best_model_checkpoint} (score: {trainer.state.best_metric})."
summary = m.write_summary(exe_time=exe_time, extra_info=extra_info)
logger.info(summary)
if __name__ == "__main__":
main()
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,579,776
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/experiments/exp1_baseline/train_eval.py
|
import sys, os
from datetime import datetime
import argparse
from pathlib import Path
root = os.path.join(Path(__file__).parent.absolute(), "../..")
sys.path.append(root)
from LMTrace.train import main
dt_string = datetime.now().strftime("%d_%m_%Y_%H_%M_%S")
data_dir = os.path.join(root, "data")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="IR baseline")
parser.add_argument("--dataset", help="dataset directory")
parser.add_argument("--epoch", default=120, help="training epoch")
parser.add_argument(
"--model_name_or_path",
default="bert-base-uncased",
help="path to the model dir",
)
parser.add_argument(
"--out_dir_root",
default= "./"
)
args = parser.parse_args()
epoch = int(args.epoch)
run_name = args.dataset.replace(os.sep, "_") + "_exp1"
model_path = args.model_name_or_path
exp_args = {
"train_dir": os.path.join(data_dir, f"{args.dataset}/train"),
"valid_dir": os.path.join(data_dir, f"{args.dataset}/valid"),
"test_dir": os.path.join(data_dir, f"{args.dataset}/test"),
"model_name_or_path": model_path,
"model_arch": "electra_single",
"output_dir": os.path.join(args.out_dir_root, f"./{epoch}ep/model"),
"do_train": True,
"do_eval": True,
"overwrite_output_dir": True,
"per_device_train_batch_size": 8,
"num_train_epochs": epoch,
"logging_steps": 500,
"save_total_limit": 3,
"evaluation_strategy": "epoch",
"run_name": run_name,
"resample_rate": 1,
"gradient_accumulation_steps": 8,
"logging_first_step": True,
"metric_for_best_model": "f1",
"load_best_model_at_end": True,
"logging_dir": f"../runs/{run_name}_{dt_string}",
"example_sampling_strategy": "dynamic_random",
"valid_query_num": 20,
"learning_rate": 3e-5,
}
main(exp_args)
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,579,777
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/LMTrace/trainer.py
|
import collections
import logging
import time
from typing import Optional, List, Union, Dict, Any
from torch import nn
from torch.utils.data import (
DataLoader,
Dataset,
DistributedSampler,
RandomSampler,
SequentialSampler,
)
from transformers import (
Trainer,
EvalPrediction,
is_torch_tpu_available,
WEIGHTS_NAME,
is_apex_available,
is_datasets_available,
is_torch_tpu_available,
set_seed,
)
import os
import torch
from transformers.file_utils import (
is_apex_available,
is_sagemaker_distributed_available,
)
from transformers.trainer_pt_utils import nested_detach
from torch.cuda import amp
from packaging import version
from transformers.trainer_pt_utils import SequentialDistributedSampler, get_tpu_sampler
import warnings
from transformers.modeling_utils import PreTrainedModel
import math
from transformers.integrations import hp_params, init_deepspeed
from transformers.trainer_callback import TrainerState
import gc
from logging import StreamHandler
import sys
from transformers.trainer_utils import TrainOutput, get_last_checkpoint, speed_metrics
from torch.cuda.amp.autocast_mode import autocast
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
if is_torch_tpu_available():
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
import torch_xla.distributed.parallel_loader as pl
if is_sagemaker_distributed_available():
import smdistributed.dataparallel.torch.distributed as dist
from smdistributed.dataparallel.torch.parallel.distributed import (
DistributedDataParallel as DDP,
)
else:
import torch.distributed as dist
logger = logging.getLogger(__name__)
def compute_metrics(pred: EvalPrediction):
labels = pred.label_ids
preds = pred.predictions.argmax(-1)
precision, recall, f1, _ = precision_recall_fscore_support(
labels, preds, average="binary"
)
acc = accuracy_score(labels, preds)
return {"accuracy": acc, "f1": f1, "precision": precision, "recall": recall}
class TLMTrainer(Trainer):
def __init__(self, *args, **kwargs):
"""
Trainer customized for TML training
"""
super().__init__(*args, **kwargs)
# monitor the trainer at runtime
self.runtime_monitor = {"train_pred": []} # predict during training
def get_train_dataloader(self) -> DataLoader:
"""
Returns the training :class:`~torch.utils.data.DataLoader`.
"""
if self.train_dataset is None:
raise ValueError("Trainer: training requires a train_dataset.")
# transform the training examples into trainnig dataset
train_dataset = self.train_dataset.gen_training_dataset(
tokenizer=self.tokenizer,
model_arch=self.args.model_arch,
resample_rate=self.args.resample_rate,
max_seq_length=self.args.max_seq_length,
)
if is_torch_tpu_available():
train_sampler = get_tpu_sampler(train_dataset)
else:
train_sampler = (
RandomSampler(train_dataset)
if self.args.local_rank == -1
else DistributedSampler(train_dataset)
)
data_loader = DataLoader(
train_dataset,
batch_size=self.args.train_batch_size,
sampler=train_sampler,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
)
return data_loader
def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch, tr_acc=None):
if self.control.should_log:
logs: Dict[str, float] = {}
tr_loss_scalar = tr_loss.item()
# reset tr_loss to zero
tr_loss -= tr_loss
steps = self.state.global_step - self._globalstep_last_logged
logs["loss"] = round(
tr_loss_scalar / steps,
4,
)
if tr_acc is not None:
tr_acc_scalar = tr_acc.item()
tr_acc -= tr_acc
logs["accuracy"] = round(
tr_acc_scalar / steps / self.args.gradient_accumulation_steps,
4,
)
# backward compatibility for pytorch schedulers
logs["learning_rate"] = (
self.lr_scheduler.get_last_lr()[0]
if version.parse(torch.__version__) >= version.parse("1.4")
else self.lr_scheduler.get_lr()[0]
)
self._total_loss_scalar += tr_loss_scalar
self._total_acc_scalar += tr_acc_scalar
self._globalstep_last_logged = self.state.global_step
self.log(logs)
metrics = None
if self.control.should_evaluate:
metrics = self.evaluate()
self._report_to_hp_search(trial, epoch, metrics)
if self.control.should_save:
self._save_checkpoint(model, trial, metrics=metrics)
self.control = self.callback_handler.on_save(
self.args, self.state, self.control
)
def train(
self,
resume_from_checkpoint: Optional[Union[str, bool]] = None,
trial: Union["optuna.Trial", Dict[str, Any]] = None,
**kwargs,
):
if "model_path" in kwargs:
resume_from_checkpoint = kwargs.pop("model_path")
warnings.warn(
"`model_path` is deprecated and will be removed in a future version. Use `resume_from_checkpoint` "
"instead.",
FutureWarning,
)
if len(kwargs) > 0:
raise TypeError(
f"train() received got unexpected keyword arguments: {', '.join(list(kwargs.keys()))}."
)
# This might change the seed so needs to run first.
self._hp_search_setup(trial)
# Model re-init
model_reloaded = False
if self.model_init is not None:
# Seed must be set before instantiating the model when using model_init.
set_seed(self.args.seed)
self.model = self.call_model_init(trial)
model_reloaded = True
# Reinitializes optimizer and scheduler
self.optimizer, self.lr_scheduler = None, None
# Load potential model checkpoint
if resume_from_checkpoint is not None and os.path.isfile(
os.path.join(resume_from_checkpoint, WEIGHTS_NAME)
):
logger.info(f"Loading model from {resume_from_checkpoint}).")
if isinstance(self.model, PreTrainedModel):
self.model = self.model.from_pretrained(resume_from_checkpoint)
model_reloaded = True
else:
state_dict = torch.load(
os.path.join(resume_from_checkpoint, WEIGHTS_NAME)
)
self.model.load_state_dict(state_dict)
# If model was re-initialized, put it on the right device and update self.model_wrapped
if model_reloaded:
if not self.is_model_parallel:
self.model = self.model.to(self.args.device)
self.model_wrapped = self.model
# Keeping track whether we can can len() on the dataset or not
train_dataset_is_sized = isinstance(self.train_dataset, collections.abc.Sized)
# Data loader and number of training steps
train_dataloader = self.get_train_dataloader()
# Setting up training control variables:
# number of training epochs: num_train_epochs
# number of training steps per epoch: num_update_steps_per_epoch
# total number of training steps to execute: max_steps
if train_dataset_is_sized:
num_update_steps_per_epoch = (
len(train_dataloader) // self.args.gradient_accumulation_steps
)
num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1)
if self.args.max_steps > 0:
max_steps = self.args.max_steps
num_train_epochs = (
self.args.max_steps // num_update_steps_per_epoch
+ int(self.args.max_steps % num_update_steps_per_epoch > 0)
)
else:
max_steps = math.ceil(
self.args.num_train_epochs * num_update_steps_per_epoch
)
num_train_epochs = math.ceil(self.args.num_train_epochs)
else:
# see __init__. max_steps is set when the dataset has no __len__
max_steps = self.args.max_steps
num_train_epochs = 1
num_update_steps_per_epoch = max_steps
if self.args.deepspeed:
model, optimizer, lr_scheduler = init_deepspeed(
self, num_training_steps=max_steps
)
self.model = model.module
self.model_wrapped = model # will get further wrapped in DDP
self.deepspeed = model # DeepSpeedEngine object
self.optimizer = optimizer
self.lr_scheduler = lr_scheduler
else:
self.create_optimizer_and_scheduler(num_training_steps=max_steps)
self.state = TrainerState()
self.state.is_hyper_param_search = trial is not None
# Check if saved optimizer or scheduler states exist
self._load_optimizer_and_scheduler(resume_from_checkpoint)
model = self.model_wrapped
# Mixed precision training with apex (torch < 1.6)
if self.use_apex:
model, self.optimizer = amp.initialize(
model, self.optimizer, opt_level=self.args.fp16_opt_level
)
# Multi-gpu training (should be after apex fp16 initialization)
if self.args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Distributed training (should be after apex fp16 initialization)
if self.sharded_ddp is not None:
model = ShardedDDP(model, self.optimizer)
elif is_sagemaker_distributed_available():
model = DDP(
model, device_ids=[dist.get_local_rank()], broadcast_buffers=False
)
elif self.deepspeed:
pass # already initialized its own DDP earlier
elif self.args.local_rank != -1:
if self.args.ddp_find_unused_parameters is not None:
find_unused_parameters = self.args.ddp_find_unused_parameters
elif isinstance(model, PreTrainedModel):
# find_unused_parameters breaks checkpointing as per
# https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021
find_unused_parameters = not getattr(
model.config, "gradient_checkpointing", False
)
else:
find_unused_parameters = True
model = torch.nn.parallel.DistributedDataParallel(
model,
device_ids=[self.args.local_rank],
output_device=self.args.local_rank,
find_unused_parameters=find_unused_parameters,
)
# for the rest of this function `model` is the outside model, whether it was wrapped or not
if model is not self.model:
self.model_wrapped = model
# important: at this point:
# self.model is the Transformers Model
# self.model_wrapped is DDP(Transformers Model), DDP(Deepspeed(Transformers Model)), etc.
# Train!
if is_torch_tpu_available():
world_size = xm.xrt_world_size()
elif self.args.local_rank != -1:
world_size = dist.get_world_size()
else:
world_size = 1
total_train_batch_size = (
self.args.train_batch_size
* self.args.gradient_accumulation_steps
* world_size
)
num_examples = (
self.num_examples(train_dataloader)
if train_dataset_is_sized
else total_train_batch_size * self.args.max_steps
)
logger.info("***** Running training *****")
logger.info(f" Num examples = {num_examples}")
logger.info(f" Num Epochs = {num_train_epochs}")
logger.info(
f" Instantaneous batch size per device = {self.args.per_device_train_batch_size}"
)
logger.info(
f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}"
)
logger.info(
f" Gradient Accumulation steps = {self.args.gradient_accumulation_steps}"
)
logger.info(f" Total optimization steps = {max_steps}")
self.state.epoch = 0
start_time = time.time()
epochs_trained = 0
steps_trained_in_current_epoch = 0
# Check if continuing training from a checkpoint
if resume_from_checkpoint is not None and os.path.isfile(
os.path.join(resume_from_checkpoint, "trainer_state.json")
):
self.state = TrainerState.load_from_json(
os.path.join(resume_from_checkpoint, "trainer_state.json")
)
epochs_trained = self.state.global_step // num_update_steps_per_epoch
if not self.args.ignore_data_skip:
steps_trained_in_current_epoch = self.state.global_step % (
num_update_steps_per_epoch
)
steps_trained_in_current_epoch *= self.args.gradient_accumulation_steps
else:
steps_trained_in_current_epoch = 0
logger.info(
" Continuing training from checkpoint, will skip to saved global_step"
)
logger.info(f" Continuing training from epoch {epochs_trained}")
logger.info(
f" Continuing training from global step {self.state.global_step}"
)
if not self.args.ignore_data_skip:
logger.info(
f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} "
"batches in the first epoch."
)
# Update the references
self.callback_handler.model = self.model
self.callback_handler.optimizer = self.optimizer
self.callback_handler.lr_scheduler = self.lr_scheduler
self.callback_handler.train_dataloader = train_dataloader
self.state.trial_name = (
self.hp_name(trial) if self.hp_name is not None else None
)
self.state.trial_params = hp_params(trial) if trial is not None else None
# This should be the same if the state has been saved but in case the training arguments changed, it's safer
# to set this after the load.
self.state.max_steps = max_steps
self.state.num_train_epochs = num_train_epochs
self.state.is_local_process_zero = self.is_local_process_zero()
self.state.is_world_process_zero = self.is_world_process_zero()
# tr_loss is a tensor to avoid synchronization of TPUs through .item()
tr_loss = torch.tensor(0.0).to(self.args.device)
tr_acc = torch.tensor(0.0).to(self.args.device)
# _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses
self._total_loss_scalar = 0.0
self._total_acc_scalar = 0.0
self._globalstep_last_logged = self.state.global_step
self._total_flos = self.state.total_flos
model.zero_grad()
self.control = self.callback_handler.on_train_begin(
self.args, self.state, self.control
)
# Skip the first epochs_trained epochs to get the random state of the dataloader at the right point.
if not self.args.ignore_data_skip:
for epoch in range(epochs_trained):
# We just need to begin an iteration to create the randomization of the sampler.
for _ in train_dataloader:
break
for epoch in range(epochs_trained, num_train_epochs):
if isinstance(train_dataloader, DataLoader) and isinstance(
train_dataloader.sampler, DistributedSampler
):
train_dataloader.sampler.set_epoch(epoch)
if is_torch_tpu_available():
parallel_loader = pl.ParallelLoader(
train_dataloader, [self.args.device]
).per_device_loader(self.args.device)
epoch_iterator = parallel_loader
else:
epoch_iterator = train_dataloader
# Reset the past mems state at the beginning of each epoch if necessary.
if self.args.past_index >= 0:
self._past = None
steps_in_epoch = (
len(epoch_iterator)
if train_dataset_is_sized
else self.args.max_steps * self.args.gradient_accumulation_steps
)
self.control = self.callback_handler.on_epoch_begin(
self.args, self.state, self.control
)
for step, inputs in enumerate(epoch_iterator):
# Skip past any already trained steps if resuming training
if steps_trained_in_current_epoch > 0:
steps_trained_in_current_epoch -= 1
continue
if (step + 1) % self.args.gradient_accumulation_steps == 0:
self.control = self.callback_handler.on_step_begin(
self.args, self.state, self.control
)
if (
(step + 1) % self.args.gradient_accumulation_steps != 0
) and self.args.local_rank != -1:
# Avoid unnecessary DDP synchronization since there will be no backward pass on this example.
with model.no_sync():
loss, accuracy = self.training_step(model, inputs)
else:
loss, accuracy = self.training_step(model, inputs)
tr_loss += loss
tr_acc += accuracy
self._total_flos += self.floating_point_ops(inputs)
if (step + 1) % self.args.gradient_accumulation_steps == 0 or (
# last step in epoch but step is always smaller than gradient_accumulation_steps
steps_in_epoch <= self.args.gradient_accumulation_steps
and (step + 1) == steps_in_epoch
):
# Gradient clipping
if (
self.args.max_grad_norm is not None
and self.args.max_grad_norm > 0
and not self.deepspeed
):
# deepspeed does its own clipping
if self.use_amp:
# AMP: gradients need unscaling
self.scaler.unscale_(self.optimizer)
if hasattr(self.optimizer, "clip_grad_norm"):
# Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping
self.optimizer.clip_grad_norm(self.args.max_grad_norm)
else:
# Revert to normal clipping otherwise, handling Apex or full precision
torch.nn.utils.clip_grad_norm_(
amp.master_params(self.optimizer)
if self.use_apex
else model.parameters(),
self.args.max_grad_norm,
)
# Optimizer step
if self.deepspeed:
self.deepspeed.step()
elif is_torch_tpu_available():
xm.optimizer_step(self.optimizer)
elif self.use_amp:
self.scaler.step(self.optimizer)
self.scaler.update()
else:
self.optimizer.step()
# write runtime monitor to file
if self.args.debug:
runtime_file = os.path.join(self.args.output_dir, "runtime.txt")
with open(runtime_file, "w") as fout:
fout.write("".join(self.runtime_monitor["train_pred"]))
self.runtime_monitor["train_pred"] = []
self.lr_scheduler.step()
model.zero_grad()
self.state.global_step += 1
self.state.epoch = epoch + (step + 1) / steps_in_epoch
self.control = self.callback_handler.on_step_end(
self.args, self.state, self.control
)
self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, tr_acc)
if self.control.should_epoch_stop or self.control.should_training_stop:
break
self.control = self.callback_handler.on_epoch_end(
self.args, self.state, self.control
)
self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, tr_acc)
if self.args.tpu_metrics_debug or self.args.debug:
if is_torch_tpu_available():
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
else:
logger.warning(
"You enabled PyTorch/XLA debug metrics but you don't have a TPU "
"configured. Check your training configuration if this is unexpected."
)
if self.control.should_training_stop:
break
# update the dataloader at epoch level
if self.args.example_sampling_strategy in [
"dynamic_random",
"offline_neg_sampling",
]:
train_dataloader = self.get_train_dataloader()
if self.args.past_index and hasattr(self, "_past"):
# Clean the state at the end of training
delattr(self, "_past")
logger.info(
"\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n"
)
if (
self.args.load_best_model_at_end
and self.state.best_model_checkpoint is not None
):
logger.info(
f"Loading best model from {self.state.best_model_checkpoint} (score: {self.state.best_metric})."
)
if isinstance(self.model, PreTrainedModel):
self.model = self.model.from_pretrained(
self.state.best_model_checkpoint
)
if not self.is_model_parallel:
self.model = self.model.to(self.args.device)
else:
state_dict = torch.load(
os.path.join(self.state.best_model_checkpoint, WEIGHTS_NAME)
)
self.model.load_state_dict(state_dict)
if self.deepspeed:
self.deepspeed.load_checkpoint(
self.state.best_model_checkpoint,
load_optimizer_states=False,
load_lr_scheduler_states=False,
)
metrics = speed_metrics("train", start_time, self.state.max_steps)
if self._total_flos is not None:
self.store_flos()
metrics["total_flos"] = self.state.total_flos
self.log(metrics)
self.control = self.callback_handler.on_train_end(
self.args, self.state, self.control
)
# add remaining tr_loss
self._total_loss_scalar += tr_loss.item()
self._total_acc_scalar += tr_acc.item()
return TrainOutput(
self.state.global_step,
self._total_loss_scalar / self.state.global_step,
metrics,
)
def training_step(
self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]
) -> torch.Tensor:
"""
Perform a training step on a batch of inputs.
Subclass and override to inject custom behavior.
Args:
model (:obj:`nn.Module`):
The model to train.
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
argument :obj:`labels`. Check your model's documentation for all accepted arguments.
Return:
:obj:`torch.Tensor`: The tensor with training loss on this batch.
"""
model.train()
inputs = self._prepare_inputs(inputs)
if self.use_amp:
with autocast():
loss = self.compute_loss(model, inputs)
else:
loss, outputs = self.compute_loss(model, inputs, return_outputs=True)
# get logits to montior the accuracy at during training
if hasattr(self.model, "config"):
ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", [])
else:
ignore_keys = []
if isinstance(outputs, dict):
logits = tuple(
v for k, v in outputs.items() if k not in ignore_keys + ["loss"]
)
else:
logits = outputs[1:]
logits = nested_detach(logits)
if len(logits) == 1:
logits = logits[0]
labels = inputs["labels"]
preds = logits.argmax(-1)
correct_cnt = preds.eq(labels).long().sum().item()
accuracy = correct_cnt / preds.shape[0]
if self.args.debug:
self.runtime_monitor["train_pred"].append(
f"{preds.tolist()},{labels.tolist()},{correct_cnt}\n"
)
if self.args.n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu parallel training
if self.args.gradient_accumulation_steps > 1:
loss = loss / self.args.gradient_accumulation_steps
if self.use_amp:
self.scaler.scale(loss).backward()
elif self.use_apex:
with amp.scale_loss(loss, self.optimizer) as scaled_loss:
scaled_loss.backward()
elif self.deepspeed:
self.deepspeed.backward(loss)
else:
loss.backward()
return loss.detach(), accuracy
class SingleTLMTrainer(TLMTrainer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class SiameseTLMTrainer(TLMTrainer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,579,778
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/server/init_db.py
|
import os
import mysql.connector
import argparse
from pathlib import Path
import sys
sys.path.append("..")
from LMTrace.data_structure import CSVReader, DronologyReader
def add_rows(cursor, table, columns, rows):
holder = ",".join(["%s"] * len(columns))
for r in rows:
cursor.execute(f"INSERT INTO {table}({','.join(columns)}) VALUES ({holder})", r)
def create_artifact_table(cursor, name, rows=[]):
query = """
CREATE TABLE {} (
id VARCHAR(255) PRIMARY KEY,
summary TEXT,
content TEXT)
""".format(
name
)
cursor.execute(query)
columns = ["id", "summary", "content"]
add_rows(cursor, name, columns, rows)
def create_link_table(cursor, name, rows=[]):
query = """
CREATE TABLE {} (
source_id VARCHAR(255),
target_id VARCHAR(255),
PRIMARY KEY(source_id,target_id)
)""".format(
name
)
cursor.execute(query)
columns = ["source_id", "target_id"]
add_rows(cursor, name, columns, rows)
def create_tim(cursor):
tim_art = """
CREATE TABLE tim_artifact (
artifact VARCHAR(255) PRIMARY KEY,
tablename VARCHAR(255)
)"""
tim_link = """
CREATE TABLE tim_trace_matrix (
trace_matrix VARCHAR(255) PRIMARY KEY,
source_artifact VARCHAR(255),
target_artifact VARCHAR(255),
is_generated TINYINT(4),
tablename VARCHAR(255))
"""
cursor.execute(tim_art)
cursor.execute(tim_link)
def create_trace_matrix(cursor, table_name):
q = """CREATE TABLE {} (
id INT AUTO_INCREMENT PRIMARY KEY,
source VARCHAR(255) NOT NULL,
target VARCHAR(255) NOT NULL,
score FLOAT NOT NULL,
approval INT NOT NULL DEFAULT 2,
UNIQUE KEY source_target (source,target)
)
""".format(
table_name
)
cursor.execute(q)
def init_SAFA_db(host, user, passwd, db_name, erase):
db_user = os.environ.get("TRACELINK_DB_USER") if not user else user
db_pass = os.environ.get("TRACELINK_DB_PASS") if not passwd else passwd
mydb = mysql.connector.connect(host=host, user=db_user, password=db_pass)
cursor = mydb.cursor()
if erase:
cursor.execute(f"DROP DATABASE IF EXISTS {db_name} ")
cursor.execute(f"CREATE DATABASE IF NOT EXISTS {db_name} ")
cursor.execute(f"USE {db_name}")
create_tim(cursor)
# inject the dronology RE-DD dataset
dr = DronologyReader(dir_path="../data/Dronology", stype="RE", ttype="DD")
dr.get_examples()
sarts = [(k, "", v) for k, v in dr.sarts.items()]
tarts = [(k, "", v) for k, v in dr.tarts.items()]
links = dr.links
create_artifact_table(cursor, "Requirement", sarts)
create_artifact_table(cursor, "Design", tarts)
create_link_table(cursor, "Requirement2Design", links)
# create views for train,valid,test
for part in ["train", "valid", "test"]:
reader = CSVReader(f"../data/Dronology/RE-DD/{part}")
reader.get_examples()
sarts = [(k, "", v) for k, v in reader.sarts.items()]
tarts = [(k, "", v) for k, v in reader.tarts.items()]
print(f"{len(sarts)},{len(tarts)},{len(reader.links)}")
create_artifact_table(cursor, f"Requirement_{part}", sarts)
create_artifact_table(cursor, f"Design_{part}", tarts)
create_link_table(cursor, f"Requirement2Design_{part}", reader.links)
mydb.commit()
mydb.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="create database schema")
parser.add_argument("--user", help="user name for mysql database")
parser.add_argument("--passwd", help="password for mysql database")
parser.add_argument("--host", default="localhost", help="host name for database")
parser.add_argument("--db_name", default="trace_model", help="database name")
parser.add_argument(
"--erase", action="store_true", help="whether erase the database before start"
)
args = parser.parse_args()
init_SAFA_db(args.host, args.user, args.passwd, args.db_name, args.erase)
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,579,779
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/test/server_test.py
|
import mysql.connector
import unittest
class TestServer(unittest.TestCase):
def test_Reader(self):
pass
if __name__ == "__main__":
unittest.main()
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,579,780
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/server/app.py
|
import sys, os
sys.path.append("../")
from LMTrace.models import LMTraceSingle, LMTraceSingle
from transformers import ElectraTokenizer, AutoTokenizer, AutoModel, AutoConfig
import torch
from flask import Flask, request, g
# Train and generate links through REST API and store in Mysql database For SAFA project
app = Flask(__name__)
from server.default_config import DefaultConfig
import mysql.connector
from LMTrace.train import main
from LMTrace.data_structure import SAFALinkWriter, SAFATableReader
from server.init_db import create_trace_matrix
import uuid
from werkzeug.exceptions import BadRequest
import logging
logger = logging.getLogger(__name__)
app.config.from_object(DefaultConfig())
info = {
"db_url": None,
}
app.config["DB_USER"] = os.environ.get("DB_USER", app.config["DB_USER"])
app.config["DB_PASSWD"] = os.environ.get("DB_PASS", app.config["DB_PASSWD"])
app.config["DB_SERVER"] = os.environ.get("DB_SERVER", app.config["DB_SERVER"])
app.config["DB_NAME"] = os.environ.get("DB_NAME", app.config["DB_NAME"])
db = mysql.connector.connect(
host=app.config["DB_SERVER"],
user=app.config["DB_USER"],
password=app.config["DB_PASSWD"],
)
info["db_url"] = app.config["DB_SERVER"]
@app.route("/")
def state():
# return the status of trace_model API as dash board
return info
@app.route("/list_model", methods=["GET"])
def list_model():
available_models = {"test_model": "./model/checkpoint-110"}
return available_models
@app.route("/train", methods=["POST", "PUT"])
def train_model():
# INPUT: a json configuration file. link, source and target artifact table, model output path
# OUTPUT: a model as directory at given path
config = request.get_json()
cursor = db.cursor()
cursor.execute(f"USE {app.config['DB_NAME']}")
readers = []
for part in ["train", "valid", "test"]:
readers.append(
SAFATableReader(
cursor,
config.pop(f"{part}_sart"),
config.pop(f"{part}_tart"),
config.pop(f"{part}_link"),
)
)
# parameter controlled by server
config["output_dir"] = os.path.join(
app.config["OUTPUT_DIR"], config.get("outptu_dir", "default")
)
config["logging_dir"] = app.config["LOG_DIR"]
config["do_train"] = True
config["learning_rate"] = float(config["learning_rate"])
main(config, readers[0], readers[1], readers[2])
return "model"
@app.route("/generate", methods=["POST"])
def gen_trace_matrix():
# INPUT: source and target artifact, output table name
# OUTPUT: a trace matrix table with given name
config = request.get_json()
sart_table, tart_table = (
config["source_artifact_table"],
config["target_artifact_tabel"],
)
trace_matrix_table = config["trace_matrix_table"]
cursor = db.cursor()
cursor.execute(f"USE {app.config['DB_NAME']}")
overwrite = config.pop("overwrite", False)
if overwrite:
cursor.execute(f"DROP TABLE IF EXISTS {trace_matrix_table}")
else:
cursor.execute("SHOW TABLES")
all_table = set([x[0] for x in cursor])
if trace_matrix_table in all_table:
raise BadRequest(
f"Table {trace_matrix_table} already exist, provide a new name or overwrite it with parameter --overwrite"
)
create_trace_matrix(cursor, trace_matrix_table)
lk_writer = SAFALinkWriter(cursor, trace_matrix_table)
data_reader = SAFATableReader(cursor, sart_table, tart_table)
# Disable train to avoid reading train/valid dataset
# Disable eval to avoid runing matrics as we do not provide labels at generation
config["do_train"] = False
config["do_eval"] = False
config["do_predict"] = True
config["model_arch"] = "electra_single"
config["output_dir"] = os.path.join(
app.config["OUTPUT_DIR"], config.get("outptu_dir", "default")
)
config["logging_dir"] = app.config["LOG_DIR"]
main(config, test_reader=data_reader, link_writer=lk_writer)
db.commit()
return trace_matrix_table
@app.teardown_appcontext
def close_db():
if hasattr(g, "db"):
db.close()
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,579,781
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/LMTrace/data_structure.py
|
import os
import random
import re
from collections import defaultdict
from typing import List, Dict
import torch
import pandas as pd
from tqdm import tqdm
import xml.etree.ElementTree as ET
from LMTrace.models import MODEL_ARCH_SINGLE, MODEL_ARCH_SIAMESE
import json, logging
from pathlib import Path
logger = logging.getLogger(__name__)
TOKEN = "token"
OID = "oid"
SOID = "s_oid"
TOID = "t_oid"
ID = "id"
SID = "sid"
TID = "tid"
PRED = "pred"
LABEL = "label"
TEXT = "text"
STEXT = "s_text"
TTEXT = "t_text"
EMBD = "embd"
INPUT_ID = "input_ids"
TK_TYPE = "token_type_ids"
ATTEN_MASK = "attention_mask"
DEFAULT_SOURCE_FILE = "source_art.csv"
DEFAULT_TARGET_FILE = "target_art.csv"
DEFAULT_LINK_FILE = "link.csv"
class TraceExamples:
"""
Manage the examples read from raw dataset
examples:
valid_examples = CodeSearchNetReader(data_dir).get_examples(type="valid", num_limit=valid_num, summary_only=True)
valid_examples = Examples(valid_examples)
valid_examples.update_features(model)
valid_examples.update_embd(model)
"""
def __init__(self, s_arts, t_arts, links):
"""
Index the raw examples with numeric ids (sid and tid) and The origin id is named as s_oid,t_oid.
:param raw_examples: A list of dictionary with keys: s_oid, s_text, t_oid, t_text
"""
self.s_index, self.t_index = dict(), dict() # artifact index (id->text)
self.rs_index, self.rt_index = (
dict(),
dict(),
) # reversed artifact index (oid->id)
self.s2t, self.t2s = defaultdict(set), defaultdict(set) # true links
self.sid_cnt, self.tid_cnt, self.lk_cnt = 0, 0, 0
for i, s_oid in enumerate(s_arts):
if s_arts[s_oid] != s_arts[s_oid] or len(s_arts[s_oid]) == 0:
logger.warn(f"skip sart {s_oid} with content {s_arts[s_oid]}")
continue
self.s_index[i] = {SOID: s_oid, TOKEN: s_arts[s_oid]}
self.rs_index[s_oid] = i
for i, t_oid in enumerate(t_arts):
if t_arts[t_oid] != t_arts[t_oid] or len(t_arts[t_oid]) == 0:
logger.warn(f"skip tart {t_oid} with content {t_arts[t_oid]}")
continue
self.t_index[i] = {TOID: t_oid, TOKEN: t_arts[t_oid]}
self.rt_index[t_oid] = i
for lk in links:
s_oid, t_oid = lk
if s_oid not in self.rs_index or t_oid not in self.rt_index:
logger.debug(
f"{lk} is dropped, s_oid:{self.rs_index.get(s_oid,None)}, t_oid:{self.rt_index.get(t_oid,None)}"
)
continue
sid, tid = self.rs_index[s_oid], self.rt_index[t_oid]
if tid not in self.s2t[sid]:
self.lk_cnt += 1
self.s2t[sid].add(tid)
self.t2s[tid].add(sid)
def __len__(self):
return self.lk_cnt
@staticmethod
def exclude_and_sample(sample_pool, exclude, num):
for id in exclude:
sample_pool.remove(id)
selected = random.choices(list(sample_pool), k=num)
return selected
def build_feature_entry(
self, sid, tid, label, tokenizer, model_arch, max_seq_length=256
):
s_tks = self.s_index[sid][TOKEN]
t_tks = self.t_index[tid][TOKEN]
pair_feature = tokenizer(
text=s_tks,
text_pair=t_tks,
return_attention_mask=True,
return_token_type_ids=True,
add_special_tokens=True,
padding="max_length",
max_length=max_seq_length,
truncation="longest_first",
)
entry = {SID: sid, TID: tid, "label": label}
if model_arch.endswith(MODEL_ARCH_SINGLE):
entry["input_ids"] = pair_feature[INPUT_ID]
entry["attention_mask"] = pair_feature[ATTEN_MASK]
entry["token_type_ids"] = pair_feature[TK_TYPE]
elif model_arch.endswith(MODEL_ARCH_SIAMESE):
entry["s_input_ids"] = self.s_index[sid][INPUT_ID]
entry["s_attention_mask"] = self.s_index[sid][ATTEN_MASK]
entry["t_input_ids"] = self.t_index[tid][INPUT_ID]
entry["t_attention_mask"] = self.t_index[tid][ATTEN_MASK]
else:
raise Exception(f"model arch {model_arch} not recoginized")
return entry
def gen_trace_dataset(
self,
tokenizer,
model_arch,
max_seq_length,
query_num=-1,
with_label=True,
for_validation=False,
):
"""
Generate trace challenge based on true links.
:param tokenizer:
:param model_arch:
:param for_validation:Evaluting large validation will significantly slow down training.
Limit the tracing size by reducing target artifacts which do not have links.
It will make the metrics higher at validation than evaluation.
:return:
"""
dataset = []
t_index = (
{x: self.t_index[x] for x in self.t2s.keys()}
if for_validation
else self.t_index
)
s_index = self.s_index
if query_num >= 0:
n = min(query_num, len(self.s_index))
s_index = {
x: self.s_index[x] for x in random.sample(self.s_index.keys(), n)
}
for sid in s_index:
if query_num > 0 and len(dataset) > query_num:
break
for tid in t_index:
if with_label:
label = 1 if tid in self.s2t[sid] else 0
else:
label = None
dataset.append(
self.build_feature_entry(
sid,
tid,
label,
tokenizer,
model_arch,
max_seq_length=max_seq_length,
)
)
return dataset
def gen_training_dataset(
self, tokenizer, model_arch, max_seq_length=256, resample_rate=1
):
"""
Generate training examples with random negative examples.
The dataset is a balanced dataset with equal size of positive and negative examples.
Create features for both single and siamese models.
:return:
"""
for index in [self.s_index, self.t_index]:
for id in index:
feature = tokenizer(
text=index[id][TOKEN],
return_attention_mask=True,
return_token_type_ids=False,
truncation="longest_first",
max_length=max_seq_length,
padding="max_length",
)
index[id][INPUT_ID] = feature[INPUT_ID]
index[id][ATTEN_MASK] = feature[ATTEN_MASK]
dataset = []
for sid in tqdm(self.s2t, desc="creating train dataset"):
pos_tids = self.s2t[sid]
for pos_tid in pos_tids:
for i in range(resample_rate):
dataset.append(
self.build_feature_entry(sid, pos_tid, 1, tokenizer, model_arch)
)
neg_tids = TraceExamples.exclude_and_sample(
set(self.t_index.keys()), pos_tids, num=len(pos_tids) * resample_rate
)
for n_tid in neg_tids:
dataset.append(
self.build_feature_entry(sid, n_tid, 0, tokenizer, model_arch)
)
return dataset
def update_embd(self, model):
"""
update the artifact embeddings for Siamese-LM model
:param model: Siamese model
:return:
"""
with torch.no_grad():
model.eval()
for index in [self.s_index, self.t_index]:
for id in tqdm(index, desc="update embedding"):
feature = index[id]
input_tensor = (
torch.tensor(feature[INPUT_ID]).view(1, -1).to(model.device)
)
mask_tensor = (
torch.tensor(feature[ATTEN_MASK]).view(1, -1).to(model.device)
)
embd = model.get_LM(input_tensor, mask_tensor)[0]
embd_cpu = embd.to("cpu")
index[id][EMBD] = embd_cpu
def write_arts(self, art_dict, file_path):
df = pd.DataFrame(columns=[ID, TEXT])
df[ID] = art_dict.keys()
df[TEXT] = art_dict.values()
df.to_csv(file_path)
def split_dataset(
self, out_dir, weigths={"train": 8, "valid": 1, "test": 1}, by="sart"
):
"""
Split dataset into train, validation, test and write them into CSV format.
Each source artifact are treated as a single query and the weights are applied on the source artifacts.
:param trace_examples:
:param out_dir:
:return:
"""
queries = list(self.s2t.keys())
random.shuffle(queries)
q_iter = iter(queries)
total_w = sum(weigths.values())
stat = {}
for idx, slice_name in enumerate(weigths):
slice_dir = os.path.join(out_dir, slice_name)
if not os.path.isdir(slice_dir):
os.makedirs(slice_dir)
if by == "link":
n = int(self.lk_cnt * (weigths[slice_name] / total_w))
elif by == "sart":
n = int(len(self.s2t) * (weigths[slice_name] / total_w))
cnt = 0
sarts = dict()
tarts = {
self.t_index[x][TOID]: self.t_index[x][TOKEN]
for x in self.t_index.keys()
}
lk_s_col, lk_t_col = [], []
# allow last slice take all remaining links
while cnt < n or idx == len(weigths) - 1:
sid = next(q_iter, None)
if sid is None:
logger.debug(f"{len(lk_s_col)},{slice_name}")
break
logger.debug(f"{cnt}/{n},{slice_name}")
for tid in self.s2t[sid]:
sart, tart = self.s_index[sid], self.t_index[tid]
sarts[sart[SOID]] = sart[TOKEN]
# tarts[tart[TOID]] = tart[TOKEN]
lk_s_col.append(sart[SOID])
lk_t_col.append(tart[TOID])
cnt += 1 if by == "link" else 0
cnt += 1 if by == "sart" else 0
stat[slice_name] = {
"slice": slice_name,
"link": len(lk_s_col),
"sart:": len(sarts),
"tart": len(tarts),
}
self.write_arts(sarts, os.path.join(slice_dir, DEFAULT_SOURCE_FILE))
self.write_arts(tarts, os.path.join(slice_dir, DEFAULT_TARGET_FILE))
lk_df = pd.DataFrame(columns=[SID, TID])
lk_df[SID] = lk_s_col
lk_df[TID] = lk_t_col
lk_df.to_csv(os.path.join(slice_dir, DEFAULT_LINK_FILE))
with open(os.path.join(out_dir, "split_summary.txt"), "w") as fout:
for slice in stat:
fout.write(str(stat[slice]) + "\n")
class DataReader:
def __init__(
self,
dir_path,
):
self.dir_path = dir_path
def get_examples(self) -> TraceExamples:
raise NotImplementedError
@staticmethod
def align_art_link(sarts, tarts, links):
lk_sids = set([x[0] for x in links])
lk_tids = set([x[1] for x in links])
s_rm = [x for x in sarts if x not in lk_sids]
t_rm = [x for x in tarts if x not in lk_tids]
[sarts.pop(x) for x in s_rm]
[tarts.pop(x) for x in t_rm]
return sarts, tarts, links
class CSVReader(DataReader):
"""
dataset reader for csv file. A datatset contains three files:
1. source_art.csv: contain 'id' and 'text' column
2. target_art.csv: contain 'id' and 'text' column
3. link.csv: contain 'sid' and 'tid' column
"""
def __init__(
self,
data_dir,
dataset_name="CSVReader",
sart=DEFAULT_SOURCE_FILE,
tart=DEFAULT_TARGET_FILE,
lk=DEFAULT_LINK_FILE,
):
super().__init__(data_dir)
self.data_dir = data_dir
self.sart = os.path.join(data_dir, sart)
self.tart = os.path.join(data_dir, tart)
self.lk = os.path.join(data_dir, lk)
self.sarts, self.tarts, self.links = None, None, None
def get_examples(self):
sart_df = pd.read_csv(self.sart)
tart_df = pd.read_csv(self.tart)
lk_df = pd.read_csv(self.lk)
parse_art = lambda data_df: {
row[ID]: row[TEXT]
for index, row in data_df.iterrows()
if row[TEXT] == row[TEXT]
}
s_index, t_index = parse_art(sart_df), parse_art(tart_df)
links = [(row[SID], row[TID]) for index, row in lk_df.iterrows()]
self.sarts, self.tarts, self.links = s_index, t_index, links
return TraceExamples(s_index, t_index, links)
class PACISReader(DataReader):
def __init__(self, dir_path):
super().__init__(dir_path)
self.source = os.path.join(dir_path, "SSDFinal.xml")
self.target = os.path.join(dir_path, "SRS.xml")
self.link = os.path.join(dir_path, "TraceMatrixSSD2SRS.txt")
def get_examples(self) -> TraceExamples:
sarts = self.read_artifact(self.source, "source")
tarts = self.read_artifact(self.target, "target")
lk_df = pd.read_csv(self.link)
links = [(row[0], row[1]) for index, row in lk_df.iterrows()]
sarts, tarts, links = DataReader.align_art_link(sarts, tarts, links)
return TraceExamples(sarts, tarts, links)
def read_artifact(self, path, type):
arts = dict()
root = ET.parse(path).getroot()
for art in root.findall("artifact"):
id = art.find("art_id").text
title = art.find("art_title").text
content = art.find("art_content").text
title = title if title else ""
content = content if content else ""
text = re.sub("#[^#]*#", "", content if type == "source" else title).strip(
"\n\t\r "
)
text = re.sub("[\n\t\s]+", " ", text)
if len(text.split()) > 10:
arts[id] = text
return arts
class CCHITReader(DataReader):
"""
Convert CCHIT in XML into csv files
"""
def __init__(
self, dir_path, sart="source.xml", tart="target.xml", link_files="answer2.xml"
):
super().__init__(dir_path)
self.sart = os.path.join(dir_path, "source.xml")
self.tart = os.path.join(dir_path, "target.xml")
self.link = os.path.join(dir_path, "answer2.xml")
def get_examples(self) -> TraceExamples:
sarts = self._read_art(self.sart, "source")
tarts = self._read_art(self.tart, "target")
links = self._read_link()
sarts, tarts, links = DataReader.align_art_link(sarts, tarts, links)
return TraceExamples(sarts, tarts, links)
def _read_art(self, path, type):
arts = dict()
art_file = self.sart if type == "source" else self.tart
with open(art_file) as fin:
root = ET.parse(fin).getroot()
for art in root.iter("artifact"):
id = art.find("art_id").text
content = art.find("art_title").text
arts[id] = content
return arts
def _read_link(self):
links = set()
with open(self.link) as fin:
root = ET.parse(fin).getroot()
for lk in root.iter("link"):
sid = lk.find("source_artifact_id").text
tid = lk.find("target_artifact_id").text
links.add((sid, tid))
return links
class DronologyReader(DataReader):
def __init__(self, dir_path, stype, ttype):
"""
:stype: type prefix/code for source artifact
:ttype: type prefix/code for target artifact
"""
super().__init__(dir_path)
self.file_path = os.path.join(dir_path, "dronologydataset01.json")
self.stype = stype
self.ttype = ttype
self.sarts, self.tarts, self.links = None, None, None
def get_examples(self) -> TraceExamples:
with open(self.file_path, encoding="utf8") as dr_json_file:
data = json.load(dr_json_file)
entries = data["entries"]
links = set()
sarts, tarts = dict(), dict()
get_prefix = lambda id_str: id_str.split("-")[0]
for entry in entries:
art_id = entry["issueid"]
prefix = get_prefix(art_id)
attributes = entry["attributes"]
art_type = attributes["issuetype"]
art_summary = attributes["summary"].strip("\n\t\r ")
art_describ = attributes["description"].strip("\n\t\r ")
content = f"{art_summary} \n {art_describ}"
if prefix == self.stype or self.stype == "*":
sarts[art_id] = content
for child in entry["children"].values():
for rel_art in child:
if get_prefix(rel_art) == self.ttype or self.ttype == "*":
links.add((art_id, rel_art))
elif prefix == self.ttype or self.ttype == "*":
tarts[art_id] = content
else:
continue
sarts, tarts, links = DataReader.align_art_link(sarts, tarts, links)
self.sarts, self.tarts, self.links = sarts, tarts, links
logger.debug(f"s:{len(sarts)}, t:{len(tarts)}, lk:{len(links)}")
return TraceExamples(sarts, tarts, links)
class CM1Reader(CCHITReader):
def __init__(self, dir_path):
super().__init__(dir_path)
self.sart = os.path.join(dir_path, "CM1-sourceArtifacts.xml")
self.tart = os.path.join(dir_path, "CM1-targetArtifacts.xml")
self.link = os.path.join(dir_path, "CM1-answerSet.xml")
def _read_art(self, path, type):
arts = dict()
art_file = self.sart if type == "source" else self.tart
with open(art_file) as fin:
root = ET.parse(fin).getroot()
for art in root.iter("artifact"):
id = art.find("id").text
content = art.find("content").text
arts[id] = content
return arts
class WARCReader(DataReader):
def __init__(self, dir_path):
super().__init__(dir_path)
self.sdir = os.path.join(dir_path, "FRS")
self.tdir = os.path.join(dir_path, "SRS")
self.link = os.path.join(dir_path, "FRStoSRS.txt")
def get_examples(self) -> TraceExamples:
links = set()
sarts, tarts = self._read_arts()
for line in Path(self.link).read_text().splitlines():
if line.startswith("%"):
continue
parts = [x for x in line.split("\t") if len(x) > 0]
if len(parts) == 2:
sid, tids = parts[0], parts[1]
for tid in tids.split():
links.add((sid, tid))
return TraceExamples(sarts, tarts, links)
def _read_arts(self):
def read_art(dir, fname):
content = Path(os.path.join(dir, fname)).read_text()
return fname, content[content.find("-") :] # clean the id from text
sarts, tarts = dict(), dict()
for sart in os.listdir(self.sdir):
id, content = read_art(self.sdir, sart)
sarts[id] = content
for tart in os.listdir(self.tdir):
id, content = read_art(self.tdir, tart)
tarts[id] = content
return sarts, tarts
class SAFATableReader(DataReader):
def __init__(self, mysql_cursor, source_table, target_table, link_table=None):
"""
Dataset reader from mysql database with SAFA project schema.
Args:
mysql_cursor : mysql cursor
source_table : table name for source artifact
target_table : table name for target artifact
link_table (optional): Table name for links. When read dataset for prediction purpose, leave this place as None . Defaults to None.
"""
super().__init__("")
self.cursor = mysql_cursor
self.stab, self.ttab, self.lk_tab = source_table, target_table, link_table
def get_examples(self) -> TraceExamples:
sarts = self._read_art(self.stab)
tarts = self._read_art(self.ttab)
links = set()
if self.lk_tab is not None:
self.cursor.execute(f"SELECT source_id, target_id FROM {self.lk_tab}")
results = self.cursor.fetchall()
for sid, tid in results:
links.add((sid, tid))
return TraceExamples(sarts, tarts, links)
def _read_art(self, table_url):
arts = dict()
self.cursor.execute(f"SELECT id, content FROM {table_url}")
results = self.cursor.fetchall()
for id, content in results:
arts[id] = content
return arts
class SAFALinkWriter:
def __init__(self, mysql_cursor, table_name):
self.cursor = mysql_cursor
self.table = table_name
def write(self, df: "DataFrame"):
sql = f"INSERT INTO {self.table} (source, target, score) VALUES (%s, %s, %s)"
vals = []
for idx, row in df.iterrows():
vals.append((row[SID], row[TID], row[PRED]))
self.cursor.executemany(sql, vals)
if __name__ == "__main__":
rds = [
CM1Reader("../data/CM1-NASA"),
PACISReader("../data/PACIS"),
CCHITReader("../data/CCHIT"),
]
for rd in rds:
print(len(rd))
break
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,579,782
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/experiments/exp1_baseline/IR.py
|
import sys, os
from pathlib import Path
root = os.path.join(Path(__file__).parent.absolute(), "../..")
sys.path.append(root)
from baseline.IR_model import run
import argparse
import logging
from logging import DEBUG, INFO, WARN
logging.basicConfig(level=INFO, stream=sys.stdout)
logging.getLogger("gensim").setLevel(WARN)
data_dir = os.path.join(root, "data")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="IR baseline")
parser.add_argument("--dataset", help="name of the dataset")
args = parser.parse_args()
dataset = args.dataset
for model in ["VSM", "LDA", "LSI"]:
exp_args = {
"model_name": model,
"output_dir": "./IRs",
"train_dir": os.path.join(data_dir, f"{dataset}/train"),
"valid_dir": os.path.join(data_dir, f"{dataset}/valid"),
"test_dir": os.path.join(data_dir, f"{dataset}/test"),
}
run(exp_args)
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,579,783
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/LMPretrain/pretrain_electra.py
|
import argparse
from pathlib import Path
import subprocess
import logging
from transformers.models.auto.tokenization_auto import AutoTokenizer
from transformers.models.electra.tokenization_electra import ElectraTokenizer
from tokenizers.implementations.byte_level_bpe import ByteLevelBPETokenizer
import json
electra_git = "https://github.com/google-research/electra.git"
logger = logging.getLogger(__name__)
def get_vocab(args):
tokenizer = AutoTokenizer.from_pretrained("google/electra-base-discriminator")
# Initialize an empty tokenizer
new_tokenizer = ByteLevelBPETokenizer(add_prefix_space=True)
# And then train
new_tokenizer.train(
files,
vocab_size=10000,
min_frequency=2,
show_progress=True,
special_tokens=["<s>", "<pad>", "</s>"],
)
tokenizer.add_tokens(new_tokenizer.get_vocab().keys())
tokenizer.save_pretrained(args.data_dir)
# Automation of https://chriskhanhtran.github.io/posts/electra-spanish/
def main():
parser = argparse.ArgumentParser("description")
parser.add_argument(
"--electra_dir",
default="./",
help="installation location for of electra code. Clone code base if dir do not exist",
)
parser.add_argument("--data_dir", help="directory for corpus")
parser.add_argument(
"--from_scratch",
help="whether train LM from scratch or continue pretraiing from existing model",
)
parser.add_argument(
"--process_num", help="process num for preprocessing the corpus"
)
args = parser.parse_args()
edir = Path(args.electra_dir)
if not edir.is_dir():
subprocess.run(f"git clone {electra_git} {edir}".split(), shell=True)
else:
logger.info("electra code already exist, skip cloning")
get_vocab()
subprocess.run(
f"python {args.electra_dir}/build_pretraining_dataset.py --corpus-dir {args.data_dir} --vocab_file {args.data_dir}/vocab.tx --output-dir {args.data_dir}/pretrained_tfrecords --max-seq-length {512} --blanks-separate-docs False --no-lower-case --num-process {args.process_numm}".split()
)
hparams = {
"do_train": "true",
"do_eval": "false",
"model_size": "small",
"do_lower_case": "false",
"vocab_size": 119547,
"num_train_steps": 100,
"save_checkpoints_steps": 100,
"train_batch_size": 32,
}
with open("hparams.json", "w") as f:
json.dump(hparams, f)
subprocess.run(
"python run_pretraining.py --data-dir {args.data_dir} --model-name electra_small --hparams {hparams.json}"
)
convert_checkpoint()
if __name__ == "__main__":
main()
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,579,784
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/LMTrace/metrics.py
|
import os
import pandas as pd
from pandas import DataFrame
from sklearn.metrics import precision_recall_curve, PrecisionRecallDisplay
import matplotlib.pyplot as plt
class TraceMetrics:
def __init__(
self,
data_frame: DataFrame,
source_col="s_id",
target_col="t_id",
pred_col="pred",
label_col="label",
output_dir=None,
):
"""
Evaluate the performance given datafrome with column "s_id", "t_id" "pred" and "label"
:param data_frame:
"""
self.source_col = source_col
self.taret_col = target_col
self.pred_col = pred_col
self.label_col = label_col
self.data_frame = data_frame
self.output_dir = output_dir
self.s_ids, self.t_ids = (
data_frame[source_col],
data_frame[target_col],
)
self.pred, self.label = data_frame[pred_col], data_frame[label_col].astype(
"int32"
)
self.group_sort = None
def f1_score(self, precision, recall):
return (
2 * (precision * recall) / (precision + recall)
if precision + recall > 0
else 0
)
def f2_score(self, precision, recall):
return (
5 * precision * recall / (4 * precision + recall)
if precision + recall > 0
else 0
)
def f_details(self, threshold, precision, recall):
"Return ture positive (tp), fp, tn,fn "
f_name = "f1_details"
tp, fp, tn, fn = 0, 0, 0, 0
for p, l in zip(self.pred, self.label):
if p > threshold:
p = 1
else:
p = 0
if l == p and p == 1:
tp += 1
elif l == p and p == 0:
tn += 1
elif l != p and p == 1:
fp += 1
elif l != p and p == 0:
fn += 1
return {
"tp": tp,
"fp": fp,
"tn": tn,
"fn": fn,
"precision": precision,
"recall": recall,
}
def draw_pr_curve(self, precision, recall, fig_name):
print(precision)
print(recall)
viz = PrecisionRecallDisplay(precision=precision, recall=recall)
viz.plot()
if os.path.isdir(self.output_dir):
fig_path = os.path.join(self.output_dir, fig_name)
plt.savefig(fig_path)
plt.close()
def best_fscores(self, fig_name=None):
print(self.label)
print(self.pred)
precision, recall, thresholds = precision_recall_curve(self.label, self.pred)
max_f1 = 0
f1_p, f1_r = 0, 0
max_f2 = 0
f2_p, f2_r = 0, 0
max_f1_thre, max_f2_thre = 0, 0
for p, r, tr in zip(precision, recall, thresholds):
f1 = self.f1_score(p, r)
f2 = self.f2_score(p, r)
if f1 >= max_f1:
max_f1 = f1
f1_p, f1_r = p, r
max_f1_thre = tr
if f2 >= max_f2:
max_f2 = f2
f2_p, f2_r = p, r
max_f2_thre = tr
if fig_name is not None:
pr_curve = self.draw_pr_curve(precision, recall, fig_name=fig_name)
f1_detail = self.f_details(max_f1_thre, f1_p, f1_r)
f2_detail = self.f_details(max_f2_thre, f2_p, f2_r)
f1_detail["f1"] = max_f1
f2_detail["f2"] = max_f2
return f1_detail, f2_detail
def precision_at_K(self, k=1):
if self.group_sort is None:
self.group_sort = (
self.data_frame.groupby([self.source_col])
.apply(lambda x: x.sort_values([self.pred_col], ascending=False))
.reset_index(drop=True)
)
group_tops = self.group_sort.groupby(self.source_col)
cnt = 0
hits = 0
for s_id, group in group_tops:
for index, row in group.head(k).iterrows():
hits += 1 if row[self.label_col] == 1 else 0
cnt += 1
return round(hits / cnt if cnt > 0 else 0, 3)
def MAP_at_K(self, k=-1):
if self.group_sort is None:
self.group_sort = (
self.data_frame.groupby([self.source_col])
.apply(lambda x: x.sort_values([self.pred_col], ascending=False))
.reset_index(drop=True)
)
group_tops = self.group_sort.groupby(self.source_col)
ap_sum = 0
for s_id, group in group_tops:
group_hits = 0
ap = 0
if k > 0:
rows = group.head(k).iterrows()
else:
rows = group.iterrows()
for i, (index, row) in enumerate(rows):
if row[self.label_col] == 1:
group_hits += 1
ap += group_hits / (i + 1)
ap = ap / group_hits if group_hits > 0 else 0
ap_sum += ap
map = ap_sum / len(group_tops) if len(group_tops) > 0 else 0
return round(map, 3)
def MRR(self):
if self.group_sort is None:
self.group_sort = (
self.data_frame.groupby([self.source_col])
.apply(lambda x: x.sort_values([self.pred_col], ascending=False))
.reset_index(drop=True)
)
group_tops = self.group_sort.groupby(self.source_col)
mrr_sum = 0
for s_id, group in group_tops:
rank = 0
for i, (index, row) in enumerate(group.iterrows()):
rank += 1
if row[self.pred_col] == 1:
mrr_sum += 1.0 / rank
break
return mrr_sum / len(group_tops)
def get_all_metrices(self):
pk3 = self.precision_at_K(3)
pk2 = self.precision_at_K(2)
pk1 = self.precision_at_K(1)
f1_detail, f2_detail = self.best_fscores()
map = self.MAP_at_K()
mrr = self.MRR()
return {
"pk3": pk3,
"pk2": pk2,
"pk1": pk1,
"f1": f1_detail,
"f2": f2_detail,
"map": map,
"mrr": mrr,
}
def write_summary(
self, exe_time, summary_file_name="eval_summary.txt", extra_info={}
):
summary_path = os.path.join(self.output_dir, summary_file_name)
res = self.get_all_metrices()
pk3, pk2, pk1 = res["pk3"], res["pk2"], res["pk1"]
best_f1, best_f2 = res["f1"], res["f2"]
map, mrr = res["map"], res["mrr"]
summary = "\npk3={}, pk2={},pk1={} \n best_f1 = {}\n bets_f2={} \n MAP={}, MRR={},\n exe_time={} \n".format(
pk3, pk2, pk1, best_f1, best_f2, map, mrr, exe_time
)
with open(summary_path, "w") as fout:
fout.write(summary)
for k, v in extra_info.items():
fout.write(f"{k}:{v}")
return summary
if __name__ == "__main__":
test = [
(1, 1, 0.8, 1),
(1, 2, 0.3, 0),
(2, 1, 0.9, 1),
(2, 1, 0, 0),
(3, 1, 0.5, 0),
]
df = pd.DataFrame(test, columns=["s_id", "t_id", "pred", "label"])
m = TraceMetrics(df)
m.precision_recall_curve("test.png")
print(m.precision_at_K(2))
print(m.MAP_at_K(2))
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,579,785
|
anthi7/SE_TraceBERT
|
refs/heads/main
|
/experiments/exp1_baseline/eval_only.py
|
import sys,os
import argparse
from datetime import datetime
from pathlib import Path
root = os.path.join(Path(__file__).parent.absolute(), "../..")
sys.path.append(root)
from LMTrace.train import main
data_dir = os.path.join(root, "data")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="IR baseline")
parser.add_argument("--dataset", help="dataset directory")
parser.add_argument("--model_path", help="dataset directory")
args = parser.parse_args()
exp_args = {
"train_dir": os.path.join(data_dir, f"{args.dataset}/train"),
"valid_dir": os.path.join(data_dir, f"{args.dataset}/valid"),
"test_dir": os.path.join(data_dir, f"{args.dataset}/test"),
"model_name_or_path": args.model_path,
"model_arch": "electra_single",
"output_dir": os.path.join(args.model_path, ".."),
"do_train": False,
"do_eval": True,
}
main(exp_args)
|
{"/LMTrace/train.py": ["/LMTrace/data_structure.py", "/LMTrace/models.py", "/LMTrace/trainer.py", "/LMTrace/metrics.py"], "/LMTrace/data_structure.py": ["/LMTrace/models.py", "/LMTrace/utils.py"], "/LMTrace/train_backup.py": ["/LMTrace/models.py"], "/experiments/test_run.py": ["/LMTrace/train.py"], "/baseline/IR_model.py": ["/LMTrace/metrics.py", "/LMTrace/data_structure.py"], "/experiments/exp1_baseline/train_eval.py": ["/LMTrace/train.py"], "/server/init_db.py": ["/LMTrace/data_structure.py"], "/server/app.py": ["/LMTrace/models.py", "/server/default_config.py", "/LMTrace/train.py", "/LMTrace/data_structure.py", "/server/init_db.py"], "/experiments/exp1_baseline/IR.py": ["/baseline/IR_model.py"], "/experiments/exp1_baseline/eval_only.py": ["/LMTrace/train.py"]}
|
42,604,022
|
bazickoff/webApp
|
refs/heads/master
|
/__init__.py
|
from flask import Flask, render_template, request, flash, redirect, session
import os
import signal
import time
import pickle
from multiprocessing import Process
import yuzdelik
import r10_futures
import last_trades
import reports_week
import reports_day
app = Flask(__name__)
app.secret_key = "super secret key"
users = {}
bots = {}
with open('/var/www/webApp/users_data.pckl', 'rb') as users_data: # /var/www/webApp/
users = pickle.load(users_data)
# def bot_control(user):
# pid = users[user].get("pid")
# if pid:
# try:
# os.kill(pid, 0)
# return True
# except:
# return False
# return False
@app.after_request
def add_header(r):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Cache-Control'] = 'public, max-age=0'
return r
@app.route("/")
def index():
return render_template("index.html")
@app.route("/kullanici", methods=["POST", "GET"])
def kullanici():
global users
curr_user = request.args.get("user")
login = ""
if not curr_user:
curr_user = request.form.get("register")
login = request.form.get("login")
api = request.form.get("api")
secret = request.form.get("secret")
if curr_user and api and secret:
users[curr_user] = {"api": api, "secret": secret}
with open('/var/www/webApp/users_data.pckl', 'wb') as users_data:
pickle.dump(users, users_data)
elif not users.get(login):
flash("Kullanıcı Bulunamadı")
return redirect("/")
if not curr_user:
curr_user = login
is_alive = True if bots.get(curr_user) and bots.get(curr_user).is_alive() else False
return render_template("kullanici.html", user = curr_user, bot_control=is_alive)
@app.route("/bot", methods=["POST", "GET"])
def bot():
global users, bots
user = request.args.get("user")
if request.form.get("return"):
return redirect(f"/kullanici?user={user}")
if request.form.get("stop"):
while bots.get(user).is_alive():
os.system(f"kill -9 {bots.get(user).pid}")
with open('/var/www/webApp/users_data.pckl', 'rb') as users_data:
users = pickle.load(users_data)
api = users[user]["api"]
secret = users[user]["secret"]
symbol = request.form.get("coin")
step = request.form.get("step")
yuzde = request.form.get("yuzde")
unit = request.form.get("unit")
grids = request.form.get("grids")
if len(request.form) >= 4: # formdan gelen veriler symbol, step, yuzde vb leri içerirse 4ten büyük olur
function = yuzdelik.bot if yuzde else r10_futures.bot
bot = Process(target=function, args=(
symbol, step, unit, grids, api, secret))
bot.start()
bots[user] = bot
with open('/var/www/webApp/users_data.pckl', 'wb') as users_data:
users[user] = {"api": api, "secret": secret, "symbol": symbol, "step": float(step),
"unit": float(unit), "grids": int(grids)}
pickle.dump(users, users_data)
c_bot = users[user]
is_alive = True if bots.get(user) and bots.get(user).is_alive() else False
return render_template("bot.html",
trades=last_trades.trades(
c_bot["symbol"], c_bot["api"], c_bot["secret"]),
report=reports_day.reports(
c_bot["symbol"], c_bot["api"], c_bot["secret"]),
user=user, is_alive=is_alive)
@app.route("/raporlar/<user>", methods=["POST", "GET"])
def raporlar(user):
c_bot = users[user]
try:
sym = c_bot["symbol"]
except:
flash("Daha Önce Bot Akif Etmediniz !")
return redirect(f"/kullanici?user={user}")
day = reports_day.reports(c_bot["symbol"], c_bot["api"], c_bot["secret"])
week = reports_week.reports(c_bot["symbol"], c_bot["api"], c_bot["secret"])
trades = last_trades.trades(c_bot["symbol"], c_bot["api"], c_bot["secret"])
return render_template("rapor.html", user=user, day=day, week=week, trades=trades)
|
{"/webApp/__init__.py": ["/yuzdelik.py", "/last_trades.py", "/reports_week.py"], "/__init__.py": ["/yuzdelik.py", "/last_trades.py", "/reports_week.py"]}
|
42,631,401
|
Misbahhassan08/crowdbotics
|
refs/heads/main
|
/RPI.py
|
"""
PUMP1 : GPIO 17
PUMP2 : GPIO 27
PUMP3 : GPIO 22
PUMP4 : GPIO 5
Sensor1 : GPIO 6
Sensor2 : GPIO 13
Sensor3 : GPIO 19
Sensor4 : GPIO 21
Button1 : GPIO 18
Button2 : GPIO 23
Button3 : GPIO 24
Button4 : GPIO 25
"""
import json
import time
from datetime import datetime
import pigpio
import threading
import sys
import sqlite3
from PyQt5.QtCore import QThread, pyqtSignal
from EncoderClass import decoder
class RPI(QThread):
SensorFlow1 = pyqtSignal(int, float, name='m_signals1')
SensorFlow2 = pyqtSignal(int, float, name='m_signals2')
SensorFlow3 = pyqtSignal(int, float, name='m_signals3')
SensorFlow4 = pyqtSignal(int, float, name='m_signals4')
def __init__(self):
QThread.__init__(self)
# pumps Gpio's
self.pump1 = 17
self.pump2 = 27
self.pump3 = 22
self.pump4 = 5
# Sensors Gpio's
self.sensor1 = 6
self.sensor2 = 13
self.sensor3 = 19
self.sensor4 = 21
# Button Gpio
self.btn1 = 18
self.btn2 = 23
self.btn3 = 24
self.btn4 = 25
self.count1 = 0
self.count2 = 0
self.count3 = 0
self.count4 = 0
self.tick1 = 0.0
self.tick2 = 0.0
self.tick3 = 0.0
self.tick4 = 0.0
self.pi = pigpio.pi()
self.pi.set_mode(self.pump1, pigpio.OUTPUT)
self.pi.set_mode(self.pump2, pigpio.OUTPUT)
self.pi.set_mode(self.pump3, pigpio.OUTPUT)
self.pi.set_mode(self.pump4, pigpio.OUTPUT)
self.pi.write(self.pump1, 0)
self.pi.write(self.pump2, 0)
self.pi.write(self.pump3, 0)
self.pi.write(self.pump4, 0)
#----------------------------------------------------------------------
self.s1 = decoder(self.pi,self.sensor1, self.callback1)
self.s2 = decoder(self.pi,self.sensor2, self.callback2)
self.s3 = decoder(self.pi,self.sensor3, self.callback3)
self.s4 = decoder(self.pi,self.sensor4, self.callback4)
self.b1 = decoder(self.pi,self.btn1, self.btnCallaback1)
self.b2 = decoder(self.pi,self.btn2, self.btnCallaback2)
self.b3 = decoder(self.pi,self.btn3, self.btnCallaback3)
self.b4 = decoder(self.pi,self.btn4, self.btnCallaback4)
time.sleep(0.01)
print('INIT RPI DONE')
def reset1(self):
self.s1.count = 0.0
def reset2(self):
self.s2.count = 0.0
def reset3(self):
self.s3.count = 0.0
def reset4(self):
self.s4.count = 0.0
def btnCallaback1(self, pulse, tick):
pass
def btnCallaback2(self, pulse, tick):
pass
def btnCallaback3(self, pulse, tick):
pass
def btnCallaback4(self, pulse, tick):
pass
def callback1(self, pulse, tick):
self.count1 = pulse
self.tick1 = tick
self.SensorFlow1.emit(int(self.count1),float(self.tick1))
pass
def callback2(self, pulse, tick):
self.count2 = pulse
self.tick2= tick
self.SensorFlow2.emit(int(self.count2),float(self.tick2))
pass
def callback3(self, pulse, tick):
self.count3 = pulse
self.tick3 = tick
self.SensorFlow3.emit(int(self.count3),float(self.tick3))
pass
def callback4(self, pulse, tick):
self.count4 = pulse
self.tick4 = tick
self.SensorFlow4.emit(int(self.count4),float(self.tick4))
pass
def pump_1_on(self):
self.pi.write(self.pump1,1)
def pump_2_on(self):
self.pi.write(self.pump2,1)
def pump_3_on(self):
self.pi.write(self.pump3,1)
def pump_4_on(self):
self.pi.write(self.pump4,1)
def pump_1_off(self):
self.pi.write(self.pump1,0)
def pump_2_off(self):
self.pi.write(self.pump2,0)
def pump_3_off(self):
self.pi.write(self.pump3,0)
def pump_4_off(self):
self.pi.write(self.pump4,0)
|
{"/test2.py": ["/RPI.py"], "/RPI.py": ["/EncoderClass.py"], "/GUI.py": ["/screen1.py", "/screen2.py", "/RPI.py"]}
|
42,631,402
|
Misbahhassan08/crowdbotics
|
refs/heads/main
|
/EncoderClass.py
|
import pigpio
import time
class decoder:
"""Class to decode mechanical rotary encoder pulses."""
def __init__(self, pi, gpioA, callback):
self.pi = pi
self.callback = callback
self.gpioA = gpioA
self.levA = 0
self.count = 0
self.pi.set_mode(gpioA, pigpio.INPUT)
self.pi.set_pull_up_down(gpioA, pigpio.PUD_UP)
self.cbA = self.pi.callback(gpioA, pigpio.FALLING_EDGE, self._pulse)
def _pulse(self, gpio, level, tick):
self.count += 1
t1 = self.pi.get_current_tick()
self.callback(self.count, t1)
def cancel(self):
self.cbA.cancel()
|
{"/test2.py": ["/RPI.py"], "/RPI.py": ["/EncoderClass.py"], "/GUI.py": ["/screen1.py", "/screen2.py", "/RPI.py"]}
|
42,631,403
|
Misbahhassan08/crowdbotics
|
refs/heads/main
|
/GUI.py
|
import json
import time
from datetime import datetime, time
import sys
import threading
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import QThread, pyqtSignal
import sqlite3
import pigpio
from screen1 import Ui_MainWindow1
from screen2 import Ui_MainWindow2
from RPI import RPI
class GUI1(QtWidgets.QWidget,Ui_MainWindow1 ):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.setupUi(self)
print('INIT: GUI1')
pass
class GUI2(QtWidgets.QWidget,Ui_MainWindow2 ):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.setupUi(self)
print('INIT: GUI2')
#self.pushButton_2.clicked.connect(lambda: self._motor4())
pass
class GUI(QtWidgets.QWidget,threading.Thread,):
def __init__(self):
threading.Thread.__init__(self)
QtWidgets.QWidget.__init__(self)
self.pi = pigpio.pi()
self.thread_loop = True
self.mode = "Pulse" # Time
self.rpi = RPI()
self._screen1 = GUI1()
self._screen2 = GUI2()
self._screen2.frame_keyboard.setGeometry(QtCore.QRect(100,500,500,500))
# rpi signals
self.rpi.SensorFlow1.connect(self.flowrate1)
self.rpi.SensorFlow2.connect(self.flowrate2)
self.rpi.SensorFlow3.connect(self.flowrate3)
self.rpi.SensorFlow4.connect(self.flowrate4)
#btn_start, btn_calibrate, cb_pump1, cb_pump1,. lbl_pump1
# --------------------------- screen 1 --------------------------------------------------------------------------
self._screen1.btn_s1_start.clicked.connect(lambda: self.btn_screen1_start())
self._screen1.btn_s1_calibrate.clicked.connect(lambda: self.switch_to_screen2())
self._screen1.cb_pump1.toggled.connect(lambda: self.buttonState(self._screen1.cb_pump1))
self._screen1.cb_pump2.toggled.connect(lambda: self.buttonState(self._screen1.cb_pump2))
self._screen1.cb_pump3.toggled.connect(lambda: self.buttonState(self._screen1.cb_pump3))
self._screen1.cb_pump4.toggled.connect(lambda: self.buttonState(self._screen1.cb_pump3))
# ------------------------------ screen2 ---------------------------------------------------------------------------
self._screen2.btnPump1.clicked.connect(lambda: self.screen2_pump1())
self._screen2.btnPump2.clicked.connect(lambda: self.screen2_pump2())
self._screen2.btnPump3.clicked.connect(lambda: self.screen2_pump3())
self._screen2.btnPump4.clicked.connect(lambda: self.screen2_pump4())
self._screen2.btnSave.clicked.connect(lambda: self.btn_save())
self._screen2.btnBack.clicked.connect(lambda: self.btn_open_screen1())
self._screen2.txtbtn1.mouseReleaseEvent = self.presstxt_btn1
self._screen2.txtbtn2.mouseReleaseEvent = self.presstxt_btn2
self._screen2.txtbtn3.mouseReleaseEvent = self.presstxt_btn3
self._screen2.rbTime.toggled.connect(lambda:self.btnstate(self._screen2.rbTime))
self._screen2.rbPulse.toggled.connect(lambda:self.btnstate(self._screen2.rbPulse))
self._screen2.btn1.clicked.connect(lambda: self.btn1Clicked())
self._screen2.btn2.clicked.connect(lambda: self.btn2Clicked())
self._screen2.btn3.clicked.connect(lambda: self.btn3Clicked())
self.reset = 0
self.s1BtnStart = False
self.screen1 = True
self.screen2 = False
self.kb = 0 # keyboard position value 0 = hide, 1= btn1 active, 2= btn2 actve 3= btn3 active
self.motor1 = False
self.motor2 = False
self.motor3 = False
self.motor4 = False
self.t1 = 0.0
self.t2 = 0.0
self.t3 = 0.0
self.t4 = 0.0
self.tt1 = 0.0
self.tt2 = 0.0
self.tt3 = 0.0
self.tt4 = 0.0
self.tresult1 = 0.0
self.tresult2 = 0.0
self.tresult3 = 0.0
self.tresult4 = 0.0
self.flow_rate1 = 0.0
self.flow_rate2 = 0.0
self.flow_rate3 = 0.0
self.flow_rate4 = 0.0
self._screen2.btnA.clicked.connect(lambda: self.apress())
self._screen2.btnB.clicked.connect(lambda: self.bpress())
self._screen2.btnC.clicked.connect(lambda: self.cpress())
self._screen2.btnD.clicked.connect(lambda: self.dpress())
self._screen2.btnE.clicked.connect(lambda: self.epress())
self._screen2.btnF.clicked.connect(lambda: self.fpress())
self._screen2.btnG.clicked.connect(lambda: self.gpress())
self._screen2.btnH.clicked.connect(lambda: self.hpress())
self._screen2.btnI.clicked.connect(lambda: self.ipress())
self._screen2.btnJ.clicked.connect(lambda: self.jpress())
self._screen2.btnK.clicked.connect(lambda: self.kpress())
self._screen2.btnL.clicked.connect(lambda: self.lpress())
self._screen2.btnM.clicked.connect(lambda: self.mpress())
self._screen2.btnN.clicked.connect(lambda: self.npress())
self._screen2.btnO.clicked.connect(lambda: self.opress())
self._screen2.btnP.clicked.connect(lambda: self.ppress())
self._screen2.btnQ.clicked.connect(lambda: self.qpress())
self._screen2.btnR.clicked.connect(lambda: self.rpress())
self._screen2.btnS.clicked.connect(lambda: self.spress())
self._screen2.btnT.clicked.connect(lambda: self.tpress())
self._screen2.btnU.clicked.connect(lambda: self.upress())
self._screen2.btnV.clicked.connect(lambda: self.vpress())
self._screen2.btnW.clicked.connect(lambda: self.wpress())
self._screen2.btnX.clicked.connect(lambda: self.xpress())
self._screen2.btnY.clicked.connect(lambda: self.ypress())
self._screen2.btnZ.clicked.connect(lambda: self.zpress())
self._screen2.btnEnter_2.clicked.connect(lambda: self.enter_press())
self._screen2.btnDelete_2.clicked.connect(lambda: self.delete_press())
self._screen2.btnSpace.clicked.connect(lambda: self.space_press())
self.i =0 # show screen 1
#self.i =1 # check screen 1 is open
#self.i =2 #show screen 2
#self.i =3 # check screen 2 is open
#self.i =4 #show screen 3
#self.i =5 # check screen 3 is open
self._screen1.show()
self._screen2.show()
self.i = 1
self._screen2.hide()
self.deamon = True
self.start()
print("TEST")
pass
#************************ Signals *******************************************
def btn_save(self):
self.reset = 1
self.rpi.reset1()
self.rpi.reset2()
self.rpi.reset3()
self.rpi.reset4()
self.tt1 = 0.0
self.tt2 = 0.0
self.tt3 = 0.0
self.tt4 = 0.0
self.tresult1 = 0.0
self.tresult2 = 0.0
self.tresult3 = 0.0
self.tresult4 = 0.0
print("save button calling")
pass
def flowrate1(self, p,t):
self.t1 = t
self.flow_rate1 = p
pass
def flowrate2(self, p,t):
self.t2 = t
self.flow_rate2 = p
pass
def flowrate3(self, p,t):
self.t3 = t
self.flow_rate3 = p
pass
def flowrate4(self, p,t):
self.t4 = t
self.flow_rate4 = p
pass
def buttonState(self, b):
try:
if True:
if b.text() == "Pump1":
if b.isChecked():
self.motor1 = True
else:
self.motor1 = False
self.screen1_message = "Pump1 UnSelect"
elif b.text() == "Pump2":
if b.isChecked():
self.motor2 = True
else:
self.motor2 = False
self.screen1_message = "Pump2 UnSelect"
elif b.text() == "Pump3":
if b.isChecked():
self.motor3 = True
else:
self.motor3 = False
self.screen1_message = "Pump3 UnSelect"
elif b.text() == "Pump4":
if b.isChecked():
self.motor4 = True
else:
self.motor4 = False
self.screen1_message = "Pump4 UnSelect"
pass
pass
except Exception as error:
self.screen1_error="Error {}".format(error)
pass
def stop(self):
self.thread_loop = False
self.join()
#------------------------------------------ Screen 1 Functions --------------------------------------------------------------------------
def btn_screen1_start(self): # pressing start button
if self.s1BtnStart:
self.s1BtnStart = False
else:
self.s1BtnStart = True
pass
def switch_to_screen2(self):
self.screen2 = True
self.screen1 = False
self.i = 2
self.motor1 = False
self.motor2 = False
self.motor3 = False
self.motor4 = False
self.reset = 0
pass
#------------------------------------- Screen 2 Functions --------------------------------------------------------------------------------
def screen2_pump1(self):
if self.motor1:
self.motor1 = False
else:
self.motor1 = True
if self.tresult1 == 0.0 :
self.tt1 = self.pi.get_current_tick()
self.reset = 0
else:
self.tt1 = self.tresult1
pass
def screen2_pump2(self):
if self.motor2:
self.motor2 = False
else:
self.motor2 = True
if self.tresult2 == 0.0 :
self.tt2 = self.pi.get_current_tick()
self.reset = 0
else:
self.tt2 = self.tresult2
pass
def screen2_pump3(self):
if self.motor3:
self.motor3 = False
else:
self.motor3 = True
if self.tresult3== 0.0 :
self.tt3 = self.pi.get_current_tick()
reset = 0
else:
self.tt3 = self.tresult3
pass
def screen2_pump4(self):
if self.motor4:
self.motor4 = False
else:
self.motor4 = True
if self.tresult4 == 0.0 :
self.tt4 = self.pi.get_current_tick()
reset = 0
else:
self.tt4 = self.tresult4
pass
def btn1Clicked(self):
val = self._screen2.txtbtn1.text()
if len(val)>0:
self._screen2.btn1.setText(''+val)
def btn2Clicked(self):
val = self._screen2.txtbtn2.text()
if len(val)>0:
self._screen2.btn2.setText(''+val)
def btn3Clicked(self):
val = self._screen2.txtbtn3.text()
if len(val)>0:
self._screen2.btn3.setText(''+val)
def btnstate(self,b):
if b.text() == "Time":
if b.isChecked() == True:
print(b.text() + "is selected ")
self.mode = "Time"
else:
print(b.text() + "is deSelectd")
if b.text() == "Pulse":
if b.isChecked() == True:
print(b.text() + "is selected ")
self.mode = "Pulse"
else:
print(b.text() + "is deSelectd")
pass
def presstxt_btn1(self, event):
print('clicking')
self._screen2.frame_keyboard.setGeometry(QtCore.QRect(10,60,711,251))
self.kb = 1
pass
def presstxt_btn2(self, event):
print('clicking')
self._screen2.frame_keyboard.setGeometry(QtCore.QRect(10,60,711,251))
self.kb = 2
pass
def presstxt_btn3(self, event):
print('clicking')
self._screen2.frame_keyboard.setGeometry(QtCore.QRect(10,60,711,251))
self.kb = 3
pass
def btn_open_screen1(self):
self.screen2 = False
self.screen1 = True
self.i = 0
self.motor1 = False
self.motor2 = False
self.motor3 = False
self.motor4 = False
pass
def apress(self):
print('pressing a')
self.txtUpdate('A')
def bpress(self):
print('pressing b')
self.txtUpdate('B')
def cpress(self):
print('pressing c')
self.txtUpdate('C')
def dpress(self):
print('pressing d')
self.txtUpdate('D')
def epress(self):
print('pressing e')
self.txtUpdate('E')
def fpress(self):
print('pressing f')
self.txtUpdate('F')
def gpress(self):
print('pressing g')
self.txtUpdate('G')
def hpress(self):
print('pressing h')
self.txtUpdate('H')
def ipress(self):
print('pressing i')
self.txtUpdate('I')
def jpress(self):
print('pressing j')
self.txtUpdate('J')
def kpress(self):
print('pressing k')
self.txtUpdate('K')
def lpress(self):
print('pressing l')
self.txtUpdate('L')
def mpress(self):
print('pressing m')
self.txtUpdate('M')
def npress(self):
print('pressing n')
self.txtUpdate('N')
def opress(self):
print('pressing o')
self.txtUpdate('O')
def ppress(self):
print('pressing p')
self.txtUpdate('P')
def qpress(self):
print('pressing q')
self.txtUpdate('Q')
def rpress(self):
print('pressing r')
self.txtUpdate('R')
def spress(self):
print('pressing s')
self.txtUpdate('S')
def tpress(self):
print('pressing t')
self.txtUpdate('T')
def upress(self):
print('pressing u')
self.txtUpdate('U')
def vpress(self):
print('pressing v')
self.txtUpdate('V')
def wpress(self):
print('pressing w')
self.txtUpdate('W')
def xpress(self):
print('pressing x')
self.txtUpdate('X')
def ypress(self):
print('pressing y')
self.txtUpdate('Y')
def zpress(self):
print('pressing z')
self.txtUpdate('Z')
def enter_press(self):
print('pressing enter')
mesg = '{}'.format(self._screen2.txtKeyboard_2.text())
if self.kb == 1:
self._screen2.txtbtn1.setText(mesg)
pass
elif self.kb == 2:
self._screen2.txtbtn2.setText(mesg)
pass
elif self.kb == 3:
self._screen2.txtbtn3.setText(mesg)
pass
self._screen2.txtKeyboard_2.setText('')
self._screen2.frame_keyboard.setGeometry(QtCore.QRect(630, 640, 711, 251))
self.kb = 0
def delete_press(self):
print('pressing delete')
# deleting last character
self.txtdelete()
def space_press(self):
print('pressing space')
# nothing happen actually
pass
def txtUpdate(self, txt):
lent = len(self._screen2.txtKeyboard_2.text())
if len(self._screen2.txtKeyboard_2.text()) == 0:
self._screen2.txtKeyboard_2.setText('{}'.format(txt))
else:
v = self._screen2.txtKeyboard_2.text()
self._screen2.txtKeyboard_2.setText('{}{}'.format(v, txt))
def txtdelete(self):
vr = self._screen2.txtKeyboard_2.text()
vrnew = ''
lr_length = len(vr) - 1
i = 0;
for str in vr:
if i == lr_length:
pass
else:
vrnew = '{}{}'.format(vrnew, str)
i += 1
print(vrnew)
self._screen2.txtKeyboard_2.setText(vrnew)
def run(self):
self.thread_loop = True
while self.thread_loop:
#time_new = pi.get_current_tick() + (1000000 * 15)
if self.screen1:
if self.i == 0:
print('SHOW SCREEN1')
self._screen1.show()
self._screen2.hide()
self.i = 1
self._screen1.lbl_pump1.setText('{}'.format(int(self.flow_rate1)))
self._screen1.lbl_pump2.setText('{}'.format(int(self.flow_rate2)))
self._screen1.lbl_pump3.setText('{}'.format(int(self.flow_rate3)))
self._screen1.lbl_pump4.setText('{}'.format(int(self.flow_rate4)))
if self.s1BtnStart == False:
#nothing happen clieck to start
self._screen1.btn_s1_start.setText('Start')
self.rpi.count1 = 0.0
self.rpi.count2 = 0.0
self.rpi.count3 = 0.0
self.rpi.count4 = 0.0
self.rpi.pump_1_off()
self.rpi.pump_2_off()
self.rpi.pump_3_off()
self.rpi.pump_4_off()
pass
else:
self._screen1.btn_s1_start.setText('Stop')
if self.motor1:
self.rpi.pump_1_on()
pass
if self.motor2:
self.rpi.pump_2_on()
pass
if self.motor3:
self.rpi.pump_3_on()
pass
if self.motor4:
self.rpi.pump_4_on()
pass
pass
elif self.screen2:
#print('In screen 2')
if self.i == 2:
print('SHOW SCREEN2')
self._screen2.show()
self._screen1.hide()
self.i = 3
else:
if self.mode == 'Time':
#time_new = pi.get_current_tick() + (1000000 * 15)
self._screen2.lblTime.setText('Time Active')
self._screen2.lblPulse.setText('')
self._screen2.lblPulse_p1.setText('')
self._screen2.lblPulse_p2.setText('')
self._screen2.lblPulse_p3.setText('')
self._screen2.lblPulse_p4.setText('')
#if self.motor1:
self.tresult1 = self.t1 - self.tt1
self._screen2.lblTime_p1.setText('{}'.format(self.tresult1))
#if self.motor2:
self.tresult2 = self.t2 - self.tt2
self._screen2.lblTime_p2.setText('{}'.format(self.tresult2))
#if self.motor3:
self.tresult3 = self.t3 - self.tt3
self._screen2.lblTime_p3.setText('{}'.format(self.tresult3))
#if self.motor4:
self.tresult4 = self.t4 - self.tt4
self._screen2.lblTime_p4.setText('{}'.format(self.tresult4))
pass
elif self.mode == 'Pulse':
self._screen2.lblTime.setText('')
self._screen2.lblPulse.setText('Pulse Active')
self._screen2.lblPulse_p1.setText('{}'.format(self.flow_rate1))
self._screen2.lblPulse_p2.setText('{}'.format(self.flow_rate2))
self._screen2.lblPulse_p3.setText('{}'.format(self.flow_rate3))
self._screen2.lblPulse_p4.setText('{}'.format(self.flow_rate4))
self._screen2.lblTime_p1.setText('')
self._screen2.lblTime_p2.setText('')
self._screen2.lblTime_p3.setText('')
self._screen2.lblTime_p4.setText('')
pass
if self.motor1:
self.rpi.pump_1_on()
else:
self.rpi.pump_1_off()
pass
if self.motor2:
self.rpi.pump_2_on()
else:
self.rpi.pump_2_off()
pass
if self.motor3:
self.rpi.pump_3_on()
else:
self.rpi.pump_3_off()
pass
if self.motor4:
self.rpi.pump_4_on()
else:
self.rpi.pump_4_off()
pass
print('Loop ended')
def main():
app = QtWidgets.QApplication(sys.argv)
project = GUI()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
pass
|
{"/test2.py": ["/RPI.py"], "/RPI.py": ["/EncoderClass.py"], "/GUI.py": ["/screen1.py", "/screen2.py", "/RPI.py"]}
|
42,631,404
|
Misbahhassan08/crowdbotics
|
refs/heads/main
|
/screen1.py
|
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QGraphicsDropShadowEffect, QPushButton, QApplication, QComboBox
import sys
class Ui_MainWindow1(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(775, 373)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.frame_s1 = QtWidgets.QFrame(self.centralwidget)
self.frame_s1.setGeometry(QtCore.QRect(0, 0, 761, 371))
self.frame_s1.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";")
self.frame_s1.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_s1.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_s1.setObjectName("frame_s1")
self.frame_s1_selection = QtWidgets.QFrame(self.frame_s1)
self.frame_s1_selection.setGeometry(QtCore.QRect(0, 230, 511, 151))
self.frame_s1_selection.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";")
self.frame_s1_selection.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_s1_selection.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_s1_selection.setObjectName("frame_s1_selection")
self.btn1 = QtWidgets.QPushButton(self.frame_s1_selection)
self.btn1.setGeometry(QtCore.QRect(10, 20, 141, 51))
self.btn1.setStyleSheet("background-color: rgb(60, 99, 98);\n"
"color:rgb(255, 255, 255);\n"
"font: 11pt \"Franklin Gothic Heavy\";\n"
"border-radius: 15px;")
self.btn1.setObjectName("btn1")
self.btn2 = QtWidgets.QPushButton(self.frame_s1_selection)
self.btn2.setGeometry(QtCore.QRect(190, 20, 141, 51))
self.btn2.setStyleSheet("background-color: rgb(60, 99, 98);\n"
"color:rgb(255, 255, 255);\n"
"font: 11pt \"Franklin Gothic Heavy\";\n"
"border-radius: 15px;")
self.btn2.setObjectName("btn2")
self.btn3 = QtWidgets.QPushButton(self.frame_s1_selection)
self.btn3.setGeometry(QtCore.QRect(360, 20, 141, 51))
self.btn3.setStyleSheet("background-color: rgb(60, 99, 98);\n"
"color:rgb(255, 255, 255);\n"
"font: 11pt \"Franklin Gothic Heavy\";\n"
"border-radius: 15px;")
self.btn3.setObjectName("btn3")
self.btn_s1_start = QtWidgets.QPushButton(self.frame_s1)
self.btn_s1_start.setGeometry(QtCore.QRect(530, 260, 221, 51))
self.btn_s1_start.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(34, 153, 129, 255), stop:1 rgba(255, 255, 255, 255));\n"
"font: 75 12pt \"MS Shell Dlg 2\";")
self.btn_s1_start.setObjectName("btn_s1_start")
self.btn_s1_calibrate = QtWidgets.QPushButton(self.frame_s1)
self.btn_s1_calibrate.setGeometry(QtCore.QRect(530, 310, 221, 51))
self.btn_s1_calibrate.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(34, 153, 129, 255), stop:1 rgba(255, 255, 255, 255));\n"
"font: 75 12pt \"MS Shell Dlg 2\";")
self.btn_s1_calibrate.setObjectName("btn_s1_calibrate")
self.frame_s1_output = QtWidgets.QFrame(self.frame_s1)
self.frame_s1_output.setGeometry(QtCore.QRect(509, -1, 261, 191))
self.frame_s1_output.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";")
self.frame_s1_output.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_s1_output.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_s1_output.setObjectName("frame_s1_output")
self.label = QtWidgets.QLabel(self.frame_s1_output)
self.label.setGeometry(QtCore.QRect(50, 40, 171, 31))
self.label.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";")
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.frame_s1_output)
self.label_2.setGeometry(QtCore.QRect(10, 70, 71, 16))
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.frame_s1_output)
self.label_3.setGeometry(QtCore.QRect(10, 90, 71, 16))
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.frame_s1_output)
self.label_4.setGeometry(QtCore.QRect(10, 110, 71, 16))
self.label_4.setObjectName("label_4")
self.label_5 = QtWidgets.QLabel(self.frame_s1_output)
self.label_5.setGeometry(QtCore.QRect(10, 160, 71, 21))
self.label_5.setObjectName("label_5")
self.lbl_pump1 = QtWidgets.QLabel(self.frame_s1_output)
self.lbl_pump1.setGeometry(QtCore.QRect(90, 70, 161, 16))
self.lbl_pump1.setObjectName("lbl_pump1")
self.lbl_pump2 = QtWidgets.QLabel(self.frame_s1_output)
self.lbl_pump2.setGeometry(QtCore.QRect(90, 90, 161, 16))
self.lbl_pump2.setObjectName("lbl_pump2")
self.lbl_pump3 = QtWidgets.QLabel(self.frame_s1_output)
self.lbl_pump3.setGeometry(QtCore.QRect(90, 110, 161, 16))
self.lbl_pump3.setObjectName("lbl_pump3")
self.lbl_msg = QtWidgets.QLabel(self.frame_s1_output)
self.lbl_msg.setGeometry(QtCore.QRect(80, 160, 320, 21))
self.lbl_msg.setObjectName("lbl_msg")
self.label_6 = QtWidgets.QLabel(self.frame_s1_output)
self.label_6.setGeometry(QtCore.QRect(70, 10, 101, 31))
self.label_6.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";\n"
"color: rgb(200, 0, 3);\n"
"")
self.label_6.setObjectName("label_6")
self.label_11 = QtWidgets.QLabel(self.frame_s1_output)
self.label_11.setGeometry(QtCore.QRect(10, 130, 71, 16))
self.label_11.setObjectName("label_11")
self.lbl_pump4 = QtWidgets.QLabel(self.frame_s1_output)
self.lbl_pump4.setGeometry(QtCore.QRect(90, 130, 161, 16))
self.lbl_pump4.setObjectName("lbl_pump4")
self.frame_logo = QtWidgets.QFrame(self.frame_s1)
self.frame_logo.setGeometry(QtCore.QRect(0, 0, 511, 225))
self.frame_logo.setStyleSheet("\n"
" \n"
"background:rgba(0,0,0,0.0);\n"
"background-image:url('Images/101.png');\n"
"background-position: center;\n"
"background-repeat: no-repeat;\n")
self.frame_logo.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_logo.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_logo.setObjectName("frame_logo")
self.cb_pump1 = QtWidgets.QCheckBox(self.frame_s1)
self.cb_pump1.setGeometry(QtCore.QRect(530, 200, 91, 18))
self.cb_pump1.setObjectName("cb_pump1")
self.cb_pump4 = QtWidgets.QCheckBox(self.frame_s1)
self.cb_pump4.setGeometry(QtCore.QRect(660, 230, 91, 18))
self.cb_pump4.setObjectName("cb_pump4")
self.cb_pump3 = QtWidgets.QCheckBox(self.frame_s1)
self.cb_pump3.setGeometry(QtCore.QRect(660, 200, 91, 18))
self.cb_pump3.setObjectName("cb_pump3")
self.cb_pump2 = QtWidgets.QCheckBox(self.frame_s1)
self.cb_pump2.setGeometry(QtCore.QRect(530, 230, 91, 18))
self.cb_pump2.setObjectName("cb_pump2")
#MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint)
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btn1.setText(_translate("MainWindow", "Button1 "))
self.btn2.setText(_translate("MainWindow", "Button1 "))
self.btn3.setText(_translate("MainWindow", "Button1 "))
self.btn_s1_start.setText(_translate("MainWindow", "Start"))
self.btn_s1_calibrate.setText(_translate("MainWindow", "Calibrate"))
self.label.setText(_translate("MainWindow", "STATUS/OUTPUT"))
self.label_2.setText(_translate("MainWindow", "PUMP1 :"))
self.label_3.setText(_translate("MainWindow", "PUMP2 :"))
self.label_4.setText(_translate("MainWindow", "PUMP3 :"))
self.label_5.setText(_translate("MainWindow", "Message:"))
self.lbl_pump1.setText(_translate("MainWindow", "0/200"))
self.lbl_pump2.setText(_translate("MainWindow", "0/200"))
self.lbl_pump3.setText(_translate("MainWindow", "0/200"))
self.lbl_msg.setText(_translate("MainWindow", "..."))
self.label_6.setText(_translate("MainWindow", "Version 3.0"))
self.label_11.setText(_translate("MainWindow", "PUMP4 :"))
self.lbl_pump4.setText(_translate("MainWindow", "0/200"))
self.cb_pump1.setText(_translate("MainWindow", "Pump1"))
self.cb_pump4.setText(_translate("MainWindow", "Pump4"))
self.cb_pump3.setText(_translate("MainWindow", "Pump3"))
self.cb_pump2.setText(_translate("MainWindow", "Pump2"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow1()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
|
{"/test2.py": ["/RPI.py"], "/RPI.py": ["/EncoderClass.py"], "/GUI.py": ["/screen1.py", "/screen2.py", "/RPI.py"]}
|
42,631,405
|
Misbahhassan08/crowdbotics
|
refs/heads/main
|
/screen2.py
|
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QGraphicsDropShadowEffect, QPushButton, QApplication, QComboBox
import sys
class Ui_MainWindow2(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(775, 375)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(220, 20, 221, 31))
font = QtGui.QFont()
font.setFamily("MS Shell Dlg 2")
font.setPointSize(14)
font.setBold(False)
font.setItalic(False)
font.setWeight(9)
self.label.setFont(font)
self.label.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";")
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.btnSave = QtWidgets.QPushButton(self.centralwidget)
self.btnSave.setGeometry(QtCore.QRect(470, 310, 271, 61))
self.btnSave.setStyleSheet("background-color: rgb(60, 99, 98);\n"
"color:rgb(255, 255, 255);\n"
"font: 11pt \"Franklin Gothic Heavy\";\n"
"border-radius: 15px;")
self.btnSave.setObjectName("btnSave")
self.btnPump1 = QtWidgets.QPushButton(self.centralwidget)
self.btnPump1.setGeometry(QtCore.QRect(470, 0, 151, 51))
self.btnPump1.setStyleSheet("background-color: rgb(60, 99, 98);\n"
"color:rgb(255, 255, 255);\n"
"font: 11pt \"Franklin Gothic Heavy\";\n"
"border-radius: 15px;")
self.btnPump1.setObjectName("btnPump1")
self.btnPump2 = QtWidgets.QPushButton(self.centralwidget)
self.btnPump2.setGeometry(QtCore.QRect(470, 60, 151, 51))
self.btnPump2.setStyleSheet("background-color: rgb(60, 99, 98);\n"
"color:rgb(255, 255, 255);\n"
"font: 11pt \"Franklin Gothic Heavy\";\n"
"border-radius: 15px;")
self.btnPump2.setObjectName("btnPump2")
self.btnPump3 = QtWidgets.QPushButton(self.centralwidget)
self.btnPump3.setGeometry(QtCore.QRect(470, 120, 151, 51))
self.btnPump3.setStyleSheet("background-color: rgb(60, 99, 98);\n"
"color:rgb(255, 255, 255);\n"
"font: 11pt \"Franklin Gothic Heavy\";\n"
"border-radius: 15px;")
self.btnPump3.setObjectName("btnPump3")
self.btnPump4 = QtWidgets.QPushButton(self.centralwidget)
self.btnPump4.setGeometry(QtCore.QRect(470, 180, 151, 51))
self.btnPump4.setStyleSheet("background-color: rgb(60, 99, 98);\n"
"color:rgb(255, 255, 255);\n"
"font: 11pt \"Franklin Gothic Heavy\";\n"
"border-radius: 15px;")
self.btnPump4.setObjectName("btnPump4")
self.lblTime_p1 = QtWidgets.QLabel(self.centralwidget)
self.lblTime_p1.setGeometry(QtCore.QRect(630, 10, 141, 20))
font = QtGui.QFont()
font.setPointSize(10)
self.lblTime_p1.setFont(font)
self.lblTime_p1.setAlignment(QtCore.Qt.AlignCenter)
self.lblTime_p1.setObjectName("lblTime_p1")
self.lblPulse_p1 = QtWidgets.QLabel(self.centralwidget)
self.lblPulse_p1.setGeometry(QtCore.QRect(630, 30, 141, 20))
font = QtGui.QFont()
font.setPointSize(10)
self.lblPulse_p1.setFont(font)
self.lblPulse_p1.setAlignment(QtCore.Qt.AlignCenter)
self.lblPulse_p1.setObjectName("lblPulse_p1")
self.lblPulse_p2 = QtWidgets.QLabel(self.centralwidget)
self.lblPulse_p2.setGeometry(QtCore.QRect(630, 80, 141, 20))
font = QtGui.QFont()
font.setPointSize(10)
self.lblPulse_p2.setFont(font)
self.lblPulse_p2.setAlignment(QtCore.Qt.AlignCenter)
self.lblPulse_p2.setObjectName("lblPulse_p2")
self.lblTime_p2 = QtWidgets.QLabel(self.centralwidget)
self.lblTime_p2.setGeometry(QtCore.QRect(630, 60, 141, 20))
font = QtGui.QFont()
font.setPointSize(10)
self.lblTime_p2.setFont(font)
self.lblTime_p2.setAlignment(QtCore.Qt.AlignCenter)
self.lblTime_p2.setObjectName("lblTime_p2")
self.lblPulse_p3 = QtWidgets.QLabel(self.centralwidget)
self.lblPulse_p3.setGeometry(QtCore.QRect(630, 150, 141, 20))
font = QtGui.QFont()
font.setPointSize(10)
self.lblPulse_p3.setFont(font)
self.lblPulse_p3.setAlignment(QtCore.Qt.AlignCenter)
self.lblPulse_p3.setObjectName("lblPulse_p3")
self.lblTime_p3 = QtWidgets.QLabel(self.centralwidget)
self.lblTime_p3.setGeometry(QtCore.QRect(630, 130, 141, 20))
font = QtGui.QFont()
font.setPointSize(10)
self.lblTime_p3.setFont(font)
self.lblTime_p3.setAlignment(QtCore.Qt.AlignCenter)
self.lblTime_p3.setObjectName("lblTime_p3")
self.lblPulse_p4 = QtWidgets.QLabel(self.centralwidget)
self.lblPulse_p4.setGeometry(QtCore.QRect(630, 210, 141, 20))
font = QtGui.QFont()
font.setPointSize(10)
self.lblPulse_p4.setFont(font)
self.lblPulse_p4.setAlignment(QtCore.Qt.AlignCenter)
self.lblPulse_p4.setObjectName("lblPulse_p4")
self.lblTime_p4 = QtWidgets.QLabel(self.centralwidget)
self.lblTime_p4.setGeometry(QtCore.QRect(630, 190, 141, 20))
font = QtGui.QFont()
font.setPointSize(10)
self.lblTime_p4.setFont(font)
self.lblTime_p4.setAlignment(QtCore.Qt.AlignCenter)
self.lblTime_p4.setObjectName("lblTime_p4")
self.lblPulse = QtWidgets.QLabel(self.centralwidget)
self.lblPulse.setGeometry(QtCore.QRect(20, 30, 141, 20))
font = QtGui.QFont()
font.setPointSize(10)
self.lblPulse.setFont(font)
self.lblPulse.setAlignment(QtCore.Qt.AlignCenter)
self.lblPulse.setObjectName("lblPulse")
self.lblTime = QtWidgets.QLabel(self.centralwidget)
self.lblTime.setGeometry(QtCore.QRect(20, 10, 141, 20))
font = QtGui.QFont()
font.setPointSize(10)
self.lblTime.setFont(font)
self.lblTime.setAlignment(QtCore.Qt.AlignCenter)
self.lblTime.setObjectName("lblTime")
self.btn1 = QtWidgets.QPushButton(self.centralwidget)
self.btn1.setGeometry(QtCore.QRect(10, 140, 191, 71))
self.btn1.setStyleSheet("background-color: rgb(60, 99, 98);\n"
"color:rgb(255, 255, 255);\n"
"font: 11pt \"Franklin Gothic Heavy\";\n"
"border-radius: 15px;")
self.btn1.setObjectName("btn1")
self.txtbtn1 = QtWidgets.QLineEdit(self.centralwidget)
self.txtbtn1.setGeometry(QtCore.QRect(210, 160, 191, 41))
self.txtbtn1.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(31, 31, 31,0.7);\n"
"font: 11pt \"Franklin Gothic Medium\";\n"
"border-radius: 15px;\n"
"background-size:10px;")
self.txtbtn1.setText("")
self.txtbtn1.setAlignment(QtCore.Qt.AlignCenter)
self.txtbtn1.setPlaceholderText("")
self.txtbtn1.setObjectName("txtbtn1")
self.btn2 = QtWidgets.QPushButton(self.centralwidget)
self.btn2.setGeometry(QtCore.QRect(10, 220, 191, 71))
self.btn2.setStyleSheet("background-color: rgb(60, 99, 98);\n"
"color:rgb(255, 255, 255);\n"
"font: 11pt \"Franklin Gothic Heavy\";\n"
"border-radius: 15px;")
self.btn2.setObjectName("btn2")
self.btn3 = QtWidgets.QPushButton(self.centralwidget)
self.btn3.setGeometry(QtCore.QRect(10, 300, 191, 71))
self.btn3.setStyleSheet("background-color: rgb(60, 99, 98);\n"
"color:rgb(255, 255, 255);\n"
"font: 11pt \"Franklin Gothic Heavy\";\n"
"border-radius: 15px;")
self.btn3.setObjectName("btn3")
self.txtbtn2 = QtWidgets.QLineEdit(self.centralwidget)
self.txtbtn2.setGeometry(QtCore.QRect(210, 240, 191, 41))
self.txtbtn2.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(31, 31, 31,0.7);\n"
"font: 11pt \"Franklin Gothic Medium\";\n"
"border-radius: 15px;\n"
"background-size:10px;")
self.txtbtn2.setText("")
self.txtbtn2.setAlignment(QtCore.Qt.AlignCenter)
self.txtbtn2.setPlaceholderText("")
self.txtbtn2.setObjectName("txtbtn2")
self.txtbtn3 = QtWidgets.QLineEdit(self.centralwidget)
self.txtbtn3.setGeometry(QtCore.QRect(210, 320, 191, 41))
self.txtbtn3.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgba(31, 31, 31,0.7);\n"
"font: 11pt \"Franklin Gothic Medium\";\n"
"border-radius: 15px;\n"
"background-size:10px;")
self.txtbtn3.setText("")
self.txtbtn3.setAlignment(QtCore.Qt.AlignCenter)
self.txtbtn3.setPlaceholderText("")
self.txtbtn3.setObjectName("txtbtn3")
self.btnBack = QtWidgets.QPushButton(self.centralwidget)
self.btnBack.setGeometry(QtCore.QRect(470, 240, 271, 61))
self.btnBack.setStyleSheet("background-color: rgb(60, 99, 98);\n"
"color:rgb(255, 255, 255);\n"
"font: 11pt \"Franklin Gothic Heavy\";\n"
"border-radius: 15px;")
self.btnBack.setObjectName("btnBack")
self.rbTime = QtWidgets.QRadioButton(self.centralwidget)
self.rbTime.setGeometry(QtCore.QRect(60, 63, 82, 21))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.rbTime.setFont(font)
self.rbTime.setObjectName("rbTime")
self.rbPulse = QtWidgets.QRadioButton(self.centralwidget)
self.rbPulse.setGeometry(QtCore.QRect(60, 90, 82, 20))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.rbPulse.setFont(font)
self.rbPulse.setObjectName("rbPulse")
self.frame_keyboard = QtWidgets.QFrame(self.centralwidget)
self.frame_keyboard.setGeometry(QtCore.QRect(740, 40, 711, 251))
self.frame_keyboard.setStyleSheet("background-color:rgba(0,0,0,0.0);")
self.frame_keyboard.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_keyboard.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_keyboard.setObjectName("frame_keyboard")
self.frame_5 = QtWidgets.QFrame(self.frame_keyboard)
self.frame_5.setGeometry(QtCore.QRect(1, 70, 711, 181))
self.frame_5.setStyleSheet("background-color: rgba(0,0,0,0.7);\n"
"border-radius: 25px;\n"
"")
self.frame_5.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_5.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_5.setObjectName("frame_5")
self.btnQ = QtWidgets.QPushButton(self.frame_5)
self.btnQ.setGeometry(QtCore.QRect(10, 20, 61, 41))
self.btnQ.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnQ.setObjectName("btnQ")
self.btnEnter_2 = QtWidgets.QPushButton(self.frame_5)
self.btnEnter_2.setGeometry(QtCore.QRect(640, 70, 61, 41))
self.btnEnter_2.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color: qlineargradient(spread:pad, x1:0.460227, y1:0, x2:0.466, y2:1, stop:0 rgba(187, 152, 9, 255), stop:0.704545 rgba(234, 181, 19, 255));")
self.btnEnter_2.setObjectName("btnEnter_2")
self.btnDelete_2 = QtWidgets.QPushButton(self.frame_5)
self.btnDelete_2.setGeometry(QtCore.QRect(640, 120, 61, 41))
self.btnDelete_2.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color: qlineargradient(spread:pad, x1:0.460227, y1:0, x2:0.466, y2:1, stop:0 rgba(187, 152, 9, 255), stop:0.704545 rgba(234, 181, 19, 255));")
self.btnDelete_2.setObjectName("btnDelete_2")
self.btnW = QtWidgets.QPushButton(self.frame_5)
self.btnW.setGeometry(QtCore.QRect(80, 20, 61, 41))
self.btnW.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnW.setObjectName("btnW")
self.btnE = QtWidgets.QPushButton(self.frame_5)
self.btnE.setGeometry(QtCore.QRect(150, 20, 61, 41))
self.btnE.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnE.setObjectName("btnE")
self.btnR = QtWidgets.QPushButton(self.frame_5)
self.btnR.setGeometry(QtCore.QRect(220, 20, 61, 41))
self.btnR.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnR.setObjectName("btnR")
self.btnT = QtWidgets.QPushButton(self.frame_5)
self.btnT.setGeometry(QtCore.QRect(290, 20, 61, 41))
self.btnT.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnT.setObjectName("btnT")
self.btnY = QtWidgets.QPushButton(self.frame_5)
self.btnY.setGeometry(QtCore.QRect(360, 20, 61, 41))
self.btnY.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnY.setObjectName("btnY")
self.btnU = QtWidgets.QPushButton(self.frame_5)
self.btnU.setGeometry(QtCore.QRect(430, 20, 61, 41))
self.btnU.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnU.setObjectName("btnU")
self.btnI = QtWidgets.QPushButton(self.frame_5)
self.btnI.setGeometry(QtCore.QRect(500, 20, 61, 41))
self.btnI.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnI.setObjectName("btnI")
self.btnO = QtWidgets.QPushButton(self.frame_5)
self.btnO.setGeometry(QtCore.QRect(570, 20, 61, 41))
self.btnO.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnO.setObjectName("btnO")
self.btnP = QtWidgets.QPushButton(self.frame_5)
self.btnP.setGeometry(QtCore.QRect(640, 20, 61, 41))
self.btnP.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnP.setObjectName("btnP")
self.btnS = QtWidgets.QPushButton(self.frame_5)
self.btnS.setGeometry(QtCore.QRect(80, 70, 61, 41))
self.btnS.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnS.setObjectName("btnS")
self.btnH = QtWidgets.QPushButton(self.frame_5)
self.btnH.setGeometry(QtCore.QRect(360, 70, 61, 41))
self.btnH.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnH.setObjectName("btnH")
self.btnG = QtWidgets.QPushButton(self.frame_5)
self.btnG.setGeometry(QtCore.QRect(290, 70, 61, 41))
self.btnG.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnG.setObjectName("btnG")
self.btnD = QtWidgets.QPushButton(self.frame_5)
self.btnD.setGeometry(QtCore.QRect(150, 70, 61, 41))
self.btnD.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnD.setObjectName("btnD")
self.btnA = QtWidgets.QPushButton(self.frame_5)
self.btnA.setGeometry(QtCore.QRect(10, 70, 61, 41))
self.btnA.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnA.setObjectName("btnA")
self.btnF = QtWidgets.QPushButton(self.frame_5)
self.btnF.setGeometry(QtCore.QRect(220, 70, 61, 41))
self.btnF.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnF.setObjectName("btnF")
self.btnJ = QtWidgets.QPushButton(self.frame_5)
self.btnJ.setGeometry(QtCore.QRect(430, 70, 61, 41))
self.btnJ.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnJ.setObjectName("btnJ")
self.btnK = QtWidgets.QPushButton(self.frame_5)
self.btnK.setGeometry(QtCore.QRect(500, 70, 61, 41))
self.btnK.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnK.setObjectName("btnK")
self.btnL = QtWidgets.QPushButton(self.frame_5)
self.btnL.setGeometry(QtCore.QRect(570, 70, 61, 41))
self.btnL.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnL.setObjectName("btnL")
self.btnN = QtWidgets.QPushButton(self.frame_5)
self.btnN.setGeometry(QtCore.QRect(360, 120, 61, 41))
self.btnN.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnN.setObjectName("btnN")
self.btnC = QtWidgets.QPushButton(self.frame_5)
self.btnC.setGeometry(QtCore.QRect(150, 120, 61, 41))
self.btnC.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnC.setObjectName("btnC")
self.btnZ = QtWidgets.QPushButton(self.frame_5)
self.btnZ.setGeometry(QtCore.QRect(10, 120, 61, 41))
self.btnZ.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnZ.setObjectName("btnZ")
self.btnB = QtWidgets.QPushButton(self.frame_5)
self.btnB.setGeometry(QtCore.QRect(290, 120, 61, 41))
self.btnB.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnB.setObjectName("btnB")
self.btnX = QtWidgets.QPushButton(self.frame_5)
self.btnX.setGeometry(QtCore.QRect(80, 120, 61, 41))
self.btnX.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnX.setObjectName("btnX")
self.btnV = QtWidgets.QPushButton(self.frame_5)
self.btnV.setGeometry(QtCore.QRect(220, 120, 61, 41))
self.btnV.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnV.setObjectName("btnV")
self.btnM = QtWidgets.QPushButton(self.frame_5)
self.btnM.setGeometry(QtCore.QRect(430, 120, 61, 41))
self.btnM.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color:qlineargradient(spread:pad, x1:0.534091, y1:0, x2:0.522727, y2:1, stop:0 rgba(77, 77, 77, 255), stop:0.579545 rgba(135, 135, 135, 255));\n"
"")
self.btnM.setObjectName("btnM")
self.btnSpace = QtWidgets.QPushButton(self.frame_5)
self.btnSpace.setGeometry(QtCore.QRect(500, 120, 131, 41))
self.btnSpace.setStyleSheet("\n"
"color: rgb(255, 255, 255);\n"
"font: 10pt \"Franklin Gothic Heavy\";\n"
"border-radius:10px;\n"
"background-color: qlineargradient(spread:pad, x1:0.460227, y1:0, x2:0.466, y2:1, stop:0 rgba(187, 152, 9, 255), stop:0.704545 rgba(234, 181, 19, 255));")
self.btnSpace.setObjectName("btnSpace")
self.txtKeyboard_2 = QtWidgets.QLineEdit(self.frame_keyboard)
self.txtKeyboard_2.setGeometry(QtCore.QRect(0, 20, 711, 41))
self.txtKeyboard_2.setStyleSheet("background-color: rgb(60, 99, 98);\n"
"color:rgb(255, 255, 255);\n"
"font: 11pt \"Franklin Gothic Heavy\";\n"
"border-radius: 15px;")
self.txtKeyboard_2.setAlignment(QtCore.Qt.AlignCenter)
self.txtKeyboard_2.setObjectName("txtKeyboard_2")
#MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint)
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Calibration"))
self.btnSave.setText(_translate("MainWindow", "SAVE"))
self.btnPump1.setText(_translate("MainWindow", "Pump 1"))
self.btnPump2.setText(_translate("MainWindow", "Pump 2"))
self.btnPump3.setText(_translate("MainWindow", "Pump 3"))
self.btnPump4.setText(_translate("MainWindow", "Pump 4"))
self.lblTime_p1.setText(_translate("MainWindow", "TIME"))
self.lblPulse_p1.setText(_translate("MainWindow", "PULSE"))
self.lblPulse_p2.setText(_translate("MainWindow", "PULSE"))
self.lblTime_p2.setText(_translate("MainWindow", "TIME"))
self.lblPulse_p3.setText(_translate("MainWindow", "PULSE"))
self.lblTime_p3.setText(_translate("MainWindow", "TIME"))
self.lblPulse_p4.setText(_translate("MainWindow", "PULSE"))
self.lblTime_p4.setText(_translate("MainWindow", "TIME"))
self.lblPulse.setText(_translate("MainWindow", "PULSE"))
self.lblTime.setText(_translate("MainWindow", "TIME"))
self.btn1.setText(_translate("MainWindow", "Button1 "))
self.btn2.setText(_translate("MainWindow", "Button 2"))
self.btn3.setText(_translate("MainWindow", "Button3"))
self.btnBack.setText(_translate("MainWindow", "BACK"))
self.rbTime.setText(_translate("MainWindow", "Time"))
self.rbPulse.setText(_translate("MainWindow", "Pulse"))
self.btnQ.setText(_translate("MainWindow", "Q"))
self.btnEnter_2.setText(_translate("MainWindow", "ENTER"))
self.btnDelete_2.setText(_translate("MainWindow", "DELETE"))
self.btnW.setText(_translate("MainWindow", "W"))
self.btnE.setText(_translate("MainWindow", "E"))
self.btnR.setText(_translate("MainWindow", "R"))
self.btnT.setText(_translate("MainWindow", "T"))
self.btnY.setText(_translate("MainWindow", "Y"))
self.btnU.setText(_translate("MainWindow", "U"))
self.btnI.setText(_translate("MainWindow", "I"))
self.btnO.setText(_translate("MainWindow", "O"))
self.btnP.setText(_translate("MainWindow", "P"))
self.btnS.setText(_translate("MainWindow", "S"))
self.btnH.setText(_translate("MainWindow", "H"))
self.btnG.setText(_translate("MainWindow", "G"))
self.btnD.setText(_translate("MainWindow", "D"))
self.btnA.setText(_translate("MainWindow", "A"))
self.btnF.setText(_translate("MainWindow", "F"))
self.btnJ.setText(_translate("MainWindow", "J"))
self.btnK.setText(_translate("MainWindow", "K"))
self.btnL.setText(_translate("MainWindow", "L"))
self.btnN.setText(_translate("MainWindow", "N"))
self.btnC.setText(_translate("MainWindow", "C"))
self.btnZ.setText(_translate("MainWindow", "Z"))
self.btnB.setText(_translate("MainWindow", "B"))
self.btnX.setText(_translate("MainWindow", "X"))
self.btnV.setText(_translate("MainWindow", "V"))
self.btnM.setText(_translate("MainWindow", "M"))
self.btnSpace.setText(_translate("MainWindow", "SPACE"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
|
{"/test2.py": ["/RPI.py"], "/RPI.py": ["/EncoderClass.py"], "/GUI.py": ["/screen1.py", "/screen2.py", "/RPI.py"]}
|
42,631,406
|
Misbahhassan08/crowdbotics
|
refs/heads/main
|
/Window2.py
|
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QGraphicsDropShadowEffect, QPushButton, QApplication, QComboBox
import sys
class Ui_MainWindow2(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(771, 381)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.frame = QtWidgets.QFrame(self.centralwidget)
self.frame.setGeometry(QtCore.QRect(0, 0, 761, 381))
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.btn_pump1 = QtWidgets.QPushButton(self.frame)
self.btn_pump1.setGeometry(QtCore.QRect(540, 10, 221, 51))
self.btn_pump1.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(34, 153, 129, 255), stop:1 rgba(255, 255, 255, 255));\n"
"font: 75 12pt \"MS Shell Dlg 2\";")
self.btn_pump1.setObjectName("btn_pump1")
self.btn_pump3 = QtWidgets.QPushButton(self.frame)
self.btn_pump3.setGeometry(QtCore.QRect(540, 130, 221, 51))
self.btn_pump3.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(34, 153, 129, 255), stop:1 rgba(255, 255, 255, 255));\n"
"font: 75 12pt \"MS Shell Dlg 2\";")
self.btn_pump3.setObjectName("btn_pump3")
self.frame_output = QtWidgets.QFrame(self.frame)
self.frame_output.setGeometry(QtCore.QRect(0, 0, 511, 361))
self.frame_output.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";")
self.frame_output.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_output.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_output.setObjectName("frame_output")
self.label_10 = QtWidgets.QLabel(self.frame_output)
self.label_10.setGeometry(QtCore.QRect(200, 0, 231, 31))
self.label_10.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";")
self.label_10.setObjectName("label_10")
self.txt_output = QtWidgets.QPlainTextEdit(self.frame_output)
self.txt_output.setGeometry(QtCore.QRect(20, 40, 471, 171))
self.txt_output.setObjectName("txt_output")
self.label_2 = QtWidgets.QLabel(self.frame_output)
self.label_2.setGeometry(QtCore.QRect(20, 240, 41, 16))
self.label_2.setObjectName("label_2")
self.lbl_ticks = QtWidgets.QLabel(self.frame_output)
self.lbl_ticks.setGeometry(QtCore.QRect(70, 300, 181, 16))
self.lbl_ticks.setObjectName("lbl_ticks")
self.label_4 = QtWidgets.QLabel(self.frame_output)
self.label_4.setGeometry(QtCore.QRect(20, 300, 51, 16))
self.label_4.setObjectName("label_4")
self.lbl_time = QtWidgets.QLabel(self.frame_output)
self.lbl_time.setGeometry(QtCore.QRect(80, 240, 171, 16))
self.lbl_time.setObjectName("lbl_time")
self.lbl_hertz = QtWidgets.QLabel(self.frame_output)
self.lbl_hertz.setGeometry(QtCore.QRect(70, 270, 181, 16))
self.lbl_hertz.setObjectName("lbl_hertz")
self.label_3 = QtWidgets.QLabel(self.frame_output)
self.label_3.setGeometry(QtCore.QRect(20, 270, 41, 16))
self.label_3.setObjectName("label_3")
self.lbl = QtWidgets.QLabel(self.frame_output)
self.lbl.setGeometry(QtCore.QRect(260, 240, 71, 21))
self.lbl.setObjectName("lbl")
self.lbl_msg = QtWidgets.QLabel(self.frame_output)
self.lbl_msg.setGeometry(QtCore.QRect(260, 270, 191, 21))
self.lbl_msg.setObjectName("lbl_msg")
self.lbl_error = QtWidgets.QLabel(self.frame_output)
self.lbl_error.setGeometry(QtCore.QRect(260, 330, 191, 16))
self.lbl_error.setObjectName("lbl_error")
self.label_6 = QtWidgets.QLabel(self.frame_output)
self.label_6.setGeometry(QtCore.QRect(260, 310, 71, 16))
self.label_6.setObjectName("label_6")
self.btn_back = QtWidgets.QPushButton(self.frame)
self.btn_back.setGeometry(QtCore.QRect(540, 310, 221, 61))
self.btn_back.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(34, 153, 129, 255), stop:1 rgba(255, 255, 255, 255));\n"
"font: 75 12pt \"MS Shell Dlg 2\";")
self.btn_back.setObjectName("btn_back")
self.btn_calibrate = QtWidgets.QPushButton(self.frame)
self.btn_calibrate.setGeometry(QtCore.QRect(540, 240, 221, 61))
self.btn_calibrate.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(34, 153, 129, 255), stop:1 rgba(255, 255, 255, 255));\n"
"font: 75 12pt \"MS Shell Dlg 2\";")
self.btn_calibrate.setObjectName("btn_calibrate")
self.btn_pump2 = QtWidgets.QPushButton(self.frame)
self.btn_pump2.setGeometry(QtCore.QRect(540, 70, 221, 51))
self.btn_pump2.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(34, 153, 129, 255), stop:1 rgba(255, 255, 255, 255));\n"
"font: 75 12pt \"MS Shell Dlg 2\";")
self.btn_pump2.setObjectName("btn_pump2")
#MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint)
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btn_pump1.setText(_translate("MainWindow", "PUMP1"))
self.btn_pump3.setText(_translate("MainWindow", "PUMP3"))
self.label_10.setText(_translate("MainWindow", "Calibration Test"))
self.label_2.setText(_translate("MainWindow", "Time"))
self.lbl_ticks.setText(_translate("MainWindow", "0"))
self.label_4.setText(_translate("MainWindow", "TICKS"))
self.lbl_time.setText(_translate("MainWindow", "00:00"))
self.lbl_hertz.setText(_translate("MainWindow", "0 Hz"))
self.label_3.setText(_translate("MainWindow", "Hertz"))
self.lbl.setText(_translate("MainWindow", "Message :"))
self.lbl_msg.setText(_translate("MainWindow", "NO message"))
self.lbl_error.setText(_translate("MainWindow", "No Error"))
self.label_6.setText(_translate("MainWindow", "ERROR :"))
self.btn_back.setText(_translate("MainWindow", "BACK "))
self.btn_calibrate.setText(_translate("MainWindow", "Calibrate Each Motor"))
self.btn_pump2.setText(_translate("MainWindow", "PUMP2"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
|
{"/test2.py": ["/RPI.py"], "/RPI.py": ["/EncoderClass.py"], "/GUI.py": ["/screen1.py", "/screen2.py", "/RPI.py"]}
|
42,631,407
|
Misbahhassan08/crowdbotics
|
refs/heads/main
|
/Window3.py
|
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QGraphicsDropShadowEffect, QPushButton, QApplication, QComboBox
import sys
class Ui_MainWindow3(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(771, 381)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.frame_s3 = QtWidgets.QFrame(self.centralwidget)
self.frame_s3.setGeometry(QtCore.QRect(20, 30, 751, 371))
self.frame_s3.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_s3.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_s3.setObjectName("frame_s3")
self.frame_s3_setting = QtWidgets.QFrame(self.frame_s3)
self.frame_s3_setting.setGeometry(QtCore.QRect(0, 0, 751, 361))
self.frame_s3_setting.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";")
self.frame_s3_setting.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_s3_setting.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_s3_setting.setObjectName("frame_s3_setting")
self.label_11 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_11.setGeometry(QtCore.QRect(10, 50, 41, 16))
self.label_11.setObjectName("label_11")
self.label_12 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_12.setGeometry(QtCore.QRect(10, 90, 31, 16))
self.label_12.setObjectName("label_12")
self.label_13 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_13.setGeometry(QtCore.QRect(10, 130, 41, 16))
self.label_13.setObjectName("label_13")
self.comboBox = QtWidgets.QComboBox(self.frame_s3_setting)
self.comboBox.setGeometry(QtCore.QRect(590, 50, 151, 31))
self.comboBox.setObjectName("comboBox")
self.label_16 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_16.setGeometry(QtCore.QRect(480, 10, 261, 31))
self.label_16.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";")
self.label_16.setObjectName("label_16")
self.btn_save = QtWidgets.QPushButton(self.frame_s3_setting)
self.btn_save.setGeometry(QtCore.QRect(590, 220, 151, 41))
self.btn_save.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(34, 153, 129, 255), stop:1 rgba(255, 255, 255, 255));\n"
"font: 75 12pt \"MS Shell Dlg 2\";")
self.btn_save.setObjectName("btn_save")
self.lblOzhigh = QtWidgets.QLabel(self.frame_s3_setting)
self.lblOzhigh.setGeometry(QtCore.QRect(240, 50, 61, 16))
self.lblOzhigh.setObjectName("lblOzhigh")
self.btn_back = QtWidgets.QPushButton(self.frame_s3_setting)
self.btn_back.setGeometry(QtCore.QRect(590, 270, 151, 41))
self.btn_back.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(34, 153, 129, 255), stop:1 rgba(255, 255, 255, 255));\n"
"font: 75 12pt \"MS Shell Dlg 2\";")
self.btn_back.setObjectName("btn_back")
self.label_23 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_23.setGeometry(QtCore.QRect(10, 10, 151, 31))
self.label_23.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";")
self.label_23.setObjectName("label_23")
self.txt_output = QtWidgets.QPlainTextEdit(self.frame_s3_setting)
self.txt_output.setGeometry(QtCore.QRect(590, 120, 151, 91))
self.txt_output.setObjectName("txt_output")
self.label_26 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_26.setGeometry(QtCore.QRect(590, 90, 151, 31))
self.label_26.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";")
self.label_26.setObjectName("label_26")
self.sliderOnceHigh = QtWidgets.QSlider(self.frame_s3_setting)
self.sliderOnceHigh.setGeometry(QtCore.QRect(60, 50, 171, 22))
self.sliderOnceHigh.setMaximum(1000)
self.sliderOnceHigh.setOrientation(QtCore.Qt.Horizontal)
self.sliderOnceHigh.setObjectName("sliderOnceHigh")
self.sliderOnceMid = QtWidgets.QSlider(self.frame_s3_setting)
self.sliderOnceMid.setGeometry(QtCore.QRect(60, 90, 171, 22))
self.sliderOnceMid.setMaximum(1000)
self.sliderOnceMid.setOrientation(QtCore.Qt.Horizontal)
self.sliderOnceMid.setObjectName("sliderOnceMid")
self.sliderOnceLow = QtWidgets.QSlider(self.frame_s3_setting)
self.sliderOnceLow.setGeometry(QtCore.QRect(60, 130, 171, 22))
self.sliderOnceLow.setMaximum(1000)
self.sliderOnceLow.setOrientation(QtCore.Qt.Horizontal)
self.sliderOnceLow.setObjectName("sliderOnceLow")
self.lblOzMid = QtWidgets.QLabel(self.frame_s3_setting)
self.lblOzMid.setGeometry(QtCore.QRect(240, 90, 61, 16))
self.lblOzMid.setObjectName("lblOzMid")
self.lblOzLow = QtWidgets.QLabel(self.frame_s3_setting)
self.lblOzLow.setGeometry(QtCore.QRect(240, 130, 61, 16))
self.lblOzLow.setObjectName("lblOzLow")
self.label_24 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_24.setGeometry(QtCore.QRect(10, 160, 151, 31))
self.label_24.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";")
self.label_24.setObjectName("label_24")
self.label_14 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_14.setGeometry(QtCore.QRect(10, 240, 31, 16))
self.label_14.setObjectName("label_14")
self.label_15 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_15.setGeometry(QtCore.QRect(10, 200, 41, 16))
self.label_15.setObjectName("label_15")
self.lblGallonHigh = QtWidgets.QLabel(self.frame_s3_setting)
self.lblGallonHigh.setGeometry(QtCore.QRect(240, 200, 61, 16))
self.lblGallonHigh.setObjectName("lblGallonHigh")
self.sliderGallonMid = QtWidgets.QSlider(self.frame_s3_setting)
self.sliderGallonMid.setGeometry(QtCore.QRect(60, 240, 171, 22))
self.sliderGallonMid.setMaximum(1000)
self.sliderGallonMid.setOrientation(QtCore.Qt.Horizontal)
self.sliderGallonMid.setObjectName("sliderGallonMid")
self.lblGallonLow = QtWidgets.QLabel(self.frame_s3_setting)
self.lblGallonLow.setGeometry(QtCore.QRect(240, 280, 61, 16))
self.lblGallonLow.setObjectName("lblGallonLow")
self.sliderGallonLow = QtWidgets.QSlider(self.frame_s3_setting)
self.sliderGallonLow.setGeometry(QtCore.QRect(60, 280, 171, 22))
self.sliderGallonLow.setMaximum(1000)
self.sliderGallonLow.setOrientation(QtCore.Qt.Horizontal)
self.sliderGallonLow.setObjectName("sliderGallonLow")
self.sliderGallonHigh = QtWidgets.QSlider(self.frame_s3_setting)
self.sliderGallonHigh.setGeometry(QtCore.QRect(60, 200, 171, 22))
self.sliderGallonHigh.setMaximum(1000)
self.sliderGallonHigh.setOrientation(QtCore.Qt.Horizontal)
self.sliderGallonHigh.setObjectName("sliderGallonHigh")
self.label_22 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_22.setGeometry(QtCore.QRect(10, 280, 41, 16))
self.label_22.setObjectName("label_22")
self.lblGallonMid = QtWidgets.QLabel(self.frame_s3_setting)
self.lblGallonMid.setGeometry(QtCore.QRect(240, 240, 61, 16))
self.lblGallonMid.setObjectName("lblGallonMid")
self.label_27 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_27.setGeometry(QtCore.QRect(290, 10, 151, 31))
self.label_27.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";")
self.label_27.setObjectName("label_27")
self.label_28 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_28.setGeometry(QtCore.QRect(290, 90, 31, 16))
self.label_28.setObjectName("label_28")
self.label_29 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_29.setGeometry(QtCore.QRect(290, 50, 41, 16))
self.label_29.setObjectName("label_29")
self.lblLitreHigh = QtWidgets.QLabel(self.frame_s3_setting)
self.lblLitreHigh.setGeometry(QtCore.QRect(520, 50, 61, 16))
self.lblLitreHigh.setObjectName("lblLitreHigh")
self.sliderLitreMid = QtWidgets.QSlider(self.frame_s3_setting)
self.sliderLitreMid.setGeometry(QtCore.QRect(340, 90, 171, 22))
self.sliderLitreMid.setMaximum(1000)
self.sliderLitreMid.setOrientation(QtCore.Qt.Horizontal)
self.sliderLitreMid.setObjectName("sliderLitreMid")
self.lblLitreLow = QtWidgets.QLabel(self.frame_s3_setting)
self.lblLitreLow.setGeometry(QtCore.QRect(520, 130, 61, 16))
self.lblLitreLow.setObjectName("lblLitreLow")
self.sliderLitreLow = QtWidgets.QSlider(self.frame_s3_setting)
self.sliderLitreLow.setGeometry(QtCore.QRect(340, 130, 171, 22))
self.sliderLitreLow.setMaximum(1000)
self.sliderLitreLow.setOrientation(QtCore.Qt.Horizontal)
self.sliderLitreLow.setObjectName("sliderLitreLow")
self.sliderLitreHigh = QtWidgets.QSlider(self.frame_s3_setting)
self.sliderLitreHigh.setGeometry(QtCore.QRect(340, 50, 171, 22))
self.sliderLitreHigh.setMaximum(1000)
self.sliderLitreHigh.setOrientation(QtCore.Qt.Horizontal)
self.sliderLitreHigh.setObjectName("sliderLitreHigh")
self.label_32 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_32.setGeometry(QtCore.QRect(290, 130, 41, 16))
self.label_32.setObjectName("label_32")
self.lblLitreMid = QtWidgets.QLabel(self.frame_s3_setting)
self.lblLitreMid.setGeometry(QtCore.QRect(520, 90, 61, 16))
self.lblLitreMid.setObjectName("lblLitreMid")
self.lbl1oz = QtWidgets.QLabel(self.frame_s3_setting)
self.lbl1oz.setGeometry(QtCore.QRect(520, 240, 61, 16))
self.lbl1oz.setObjectName("lbl1oz")
self.label_58 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_58.setGeometry(QtCore.QRect(300, 280, 61, 16))
self.label_58.setObjectName("label_58")
self.sliderMinHz = QtWidgets.QSlider(self.frame_s3_setting)
self.sliderMinHz.setGeometry(QtCore.QRect(360, 280, 151, 22))
self.sliderMinHz.setMaximum(100)
self.sliderMinHz.setOrientation(QtCore.Qt.Horizontal)
self.sliderMinHz.setObjectName("sliderMinHz")
self.lblMinHz = QtWidgets.QLabel(self.frame_s3_setting)
self.lblMinHz.setGeometry(QtCore.QRect(520, 280, 61, 16))
self.lblMinHz.setObjectName("lblMinHz")
self.label_60 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_60.setGeometry(QtCore.QRect(300, 240, 61, 16))
self.label_60.setObjectName("label_60")
self.slider1oz = QtWidgets.QSlider(self.frame_s3_setting)
self.slider1oz.setGeometry(QtCore.QRect(360, 240, 151, 22))
self.slider1oz.setMaximum(100)
self.slider1oz.setOrientation(QtCore.Qt.Horizontal)
self.slider1oz.setObjectName("slider1oz")
self.label_61 = QtWidgets.QLabel(self.frame_s3_setting)
self.label_61.setGeometry(QtCore.QRect(370, 190, 151, 31))
self.label_61.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";")
self.label_61.setObjectName("label_61")
self.label_10 = QtWidgets.QLabel(self.centralwidget)
self.label_10.setGeometry(QtCore.QRect(240, 0, 231, 31))
self.label_10.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";")
self.label_10.setObjectName("label_10")
#MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint)
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label_11.setText(_translate("MainWindow", "HIGH"))
self.label_12.setText(_translate("MainWindow", "MID"))
self.label_13.setText(_translate("MainWindow", "LOW"))
self.label_16.setText(_translate("MainWindow", "Select The Pump To calibrate"))
self.btn_save.setText(_translate("MainWindow", "SAVE"))
self.lblOzhigh.setText(_translate("MainWindow", "0"))
self.btn_back.setText(_translate("MainWindow", "BACK"))
self.label_23.setText(_translate("MainWindow", "OUNCE"))
self.label_26.setText(_translate("MainWindow", "MESSAGE BOX"))
self.lblOzMid.setText(_translate("MainWindow", "0"))
self.lblOzLow.setText(_translate("MainWindow", "0"))
self.label_24.setText(_translate("MainWindow", "GALLON"))
self.label_14.setText(_translate("MainWindow", "MID"))
self.label_15.setText(_translate("MainWindow", "HIGH"))
self.lblGallonHigh.setText(_translate("MainWindow", "0"))
self.lblGallonLow.setText(_translate("MainWindow", "0"))
self.label_22.setText(_translate("MainWindow", "LOW"))
self.lblGallonMid.setText(_translate("MainWindow", "0"))
self.label_27.setText(_translate("MainWindow", "LITRE"))
self.label_28.setText(_translate("MainWindow", "MID"))
self.label_29.setText(_translate("MainWindow", "HIGH"))
self.lblLitreHigh.setText(_translate("MainWindow", "0"))
self.lblLitreLow.setText(_translate("MainWindow", "0"))
self.label_32.setText(_translate("MainWindow", "LOW"))
self.lblLitreMid.setText(_translate("MainWindow", "0"))
self.lbl1oz.setText(_translate("MainWindow", "0"))
self.label_58.setText(_translate("MainWindow", "Min Hz"))
self.lblMinHz.setText(_translate("MainWindow", "0"))
self.label_60.setText(_translate("MainWindow", "1 OZ"))
self.label_61.setText(_translate("MainWindow", "UNIT VALUE"))
self.label_10.setText(_translate("MainWindow", "Calibration Area"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
|
{"/test2.py": ["/RPI.py"], "/RPI.py": ["/EncoderClass.py"], "/GUI.py": ["/screen1.py", "/screen2.py", "/RPI.py"]}
|
42,631,408
|
Misbahhassan08/crowdbotics
|
refs/heads/main
|
/test2.py
|
import json
import time
import threading
import sys
from datetime import datetime
import pigpio
from RPI import RPI
pos1 = 0
pos2 = 0
pos3 = 0
pos4 = 0
t1 = 0.0
t2 = 0.0
t3 = 0.0
t4 = 0.0
rpi = RPI()
pi = pigpio.pi()
def flowrate1(p,t):
global pos1
global t1
pos1 = p
t1 = t
print("call flow rate 1")
pass
def flowrate2(p,t):
global pos2
global t2
pos2 = p
t2 = t
print("call flow rate 2")
pass
time_new = pi.get_current_tick() + (1000000 * 15)
rpi.pump_1_on()
rpi.pump_2_on()
while pi.get_current_tick() <= time_new:
#rpi.SensorFlow1.connect(flowrate1)
#rpi.SensorFlow2.connect(flowrate2)
print("Sensor1 : {} with tick {} , Sensor2 :{} with tick {}".format(rpi.count1,rpi.tick1,rpi.count2,rpi.tick2))
pass
rpi.pump_1_off()
rpi.pump_2_off()
|
{"/test2.py": ["/RPI.py"], "/RPI.py": ["/EncoderClass.py"], "/GUI.py": ["/screen1.py", "/screen2.py", "/RPI.py"]}
|
42,631,409
|
Misbahhassan08/crowdbotics
|
refs/heads/main
|
/Window1.py
|
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QGraphicsDropShadowEffect, QPushButton, QApplication, QComboBox
import sys
class Ui_MainWindow1(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
#MainWindow.setEnabled(True)
MainWindow.resize(771, 381)
MainWindow.setStyleSheet("")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
self.graphicsView.setGeometry(QtCore.QRect(0, 2, 511, 225))
#self.graphicsView.setStyleSheet("background-image:url('Images/100.png')")
self.graphicsView.setStyleSheet("\n"
" \n"
"background:rgba(0,0,0,0.0);\n"
"background-image:url('Images/101.png');\n"
"background-position: center;\n"
"background-repeat: no-repeat;\n"
)
self.graphicsView.setObjectName("graphicsView")
#self.frame_logo = QtWidgets.QFrame(self.centralwidget)
#self.frame_logo.setGeometry(QtCore.QRect(0, 0, 511, 225))
#self.frame_logo.setStyleSheet("background-color: rgb(170, 255, 255);")
#self.frame_logo.setFrameShape(QtWidgets.QFrame.StyledPanel)
#self.frame_logo.setFrameShadow(QtWidgets.QFrame.Raised)
#self.frame_logo.setObjectName("frame_logo")
self.frame_output = QtWidgets.QFrame(self.centralwidget)
self.frame_output.setGeometry(QtCore.QRect(509, -1, 261, 231))
self.frame_output.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";")
self.frame_output.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_output.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_output.setObjectName("frame_output")
self.label = QtWidgets.QLabel(self.frame_output)
self.label.setGeometry(QtCore.QRect(50, 10, 171, 31))
self.label.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";")
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.frame_output)
self.label_2.setGeometry(QtCore.QRect(10, 60, 71, 16))
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.frame_output)
self.label_3.setGeometry(QtCore.QRect(10, 90, 71, 16))
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.frame_output)
self.label_4.setGeometry(QtCore.QRect(10, 120, 71, 16))
self.label_4.setObjectName("label_4")
self.label_5 = QtWidgets.QLabel(self.frame_output)
self.label_5.setGeometry(QtCore.QRect(10, 160, 71, 21))
self.label_5.setObjectName("label_5")
self.label_6 = QtWidgets.QLabel(self.frame_output)
self.label_6.setGeometry(QtCore.QRect(10, 190, 71, 16))
self.label_6.setObjectName("label_6")
self.lbl_pump1 = QtWidgets.QLabel(self.frame_output)
self.lbl_pump1.setGeometry(QtCore.QRect(90, 60, 181, 16))
self.lbl_pump1.setObjectName("lbl_pump1")
self.lbl_pump2 = QtWidgets.QLabel(self.frame_output)
self.lbl_pump2.setGeometry(QtCore.QRect(90, 90, 181, 16))
self.lbl_pump2.setObjectName("lbl_pump2")
self.lbl_pump3 = QtWidgets.QLabel(self.frame_output)
self.lbl_pump3.setGeometry(QtCore.QRect(90, 120, 181, 16))
self.lbl_pump3.setObjectName("lbl_pump3")
self.lbl_msg = QtWidgets.QLabel(self.frame_output)
self.lbl_msg.setGeometry(QtCore.QRect(80, 160, 181, 20))
self.lbl_msg.setObjectName("lbl_msg")
self.lbl_error = QtWidgets.QLabel(self.frame_output)
self.lbl_error.setGeometry(QtCore.QRect(70, 190, 191, 20))
self.lbl_error.setObjectName("lbl_error")
self.frame_selection = QtWidgets.QFrame(self.centralwidget)
self.frame_selection.setGeometry(QtCore.QRect(0, 230, 511, 151))
self.frame_selection.setStyleSheet("font: 75 12pt \"MS Shell Dlg 2\";")
self.frame_selection.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_selection.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_selection.setObjectName("frame_selection")
self.dial = QtWidgets.QDial(self.frame_selection)
self.dial.setGeometry(QtCore.QRect(60, 40, 111, 111))
self.dial.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(34, 153, 129, 255), stop:1 rgba(255, 255, 255, 255));")
self.dial.setMaximum(2)
self.dial.setProperty("value", 1)
self.dial.setSliderPosition(1)
self.dial.setObjectName("dial")
self.label_7 = QtWidgets.QLabel(self.frame_selection)
self.label_7.setGeometry(QtCore.QRect(10, 120, 41, 16))
self.label_7.setObjectName("label_7")
self.label_8 = QtWidgets.QLabel(self.frame_selection)
self.label_8.setGeometry(QtCore.QRect(100, 20, 41, 16))
self.label_8.setObjectName("label_8")
self.label_9 = QtWidgets.QLabel(self.frame_selection)
self.label_9.setGeometry(QtCore.QRect(170, 120, 41, 16))
self.label_9.setObjectName("label_9")
self.cb_pump1 = QtWidgets.QCheckBox(self.frame_selection)
self.cb_pump1.setGeometry(QtCore.QRect(420, 60, 81, 18))
self.cb_pump1.setObjectName("cb_pump1")
self.cb_pump2 = QtWidgets.QCheckBox(self.frame_selection)
self.cb_pump2.setGeometry(QtCore.QRect(420, 90, 81, 18))
self.cb_pump2.setObjectName("cb_pump2")
self.cb_pump3 = QtWidgets.QCheckBox(self.frame_selection)
self.cb_pump3.setGeometry(QtCore.QRect(420, 120, 81, 18))
self.cb_pump3.setObjectName("cb_pump3")
self.label_10 = QtWidgets.QLabel(self.frame_selection)
self.label_10.setGeometry(QtCore.QRect(280, 10, 231, 31))
self.label_10.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";")
self.label_10.setObjectName("label_10")
self.label_27 = QtWidgets.QLabel(self.frame_selection)
self.label_27.setGeometry(QtCore.QRect(200, 50, 181, 31))
self.label_27.setStyleSheet("font: 75 14pt \"MS Shell Dlg 2\";")
self.label_27.setObjectName("label_27")
self.comboBox = QtWidgets.QComboBox(self.frame_selection)
self.comboBox.setGeometry(QtCore.QRect(210, 80, 121, 22))
self.comboBox.setObjectName("comboBox")
self.btn_start = QtWidgets.QPushButton(self.centralwidget)
self.btn_start.setGeometry(QtCore.QRect(530, 250, 221, 51))
self.btn_start.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(34, 153, 129, 255), stop:1 rgba(255, 255, 255, 255));\n"
"font: 75 12pt \"MS Shell Dlg 2\";")
self.btn_start.setObjectName("btn_start")
self.btn_calibrate = QtWidgets.QPushButton(self.centralwidget)
self.btn_calibrate.setGeometry(QtCore.QRect(530, 310, 221, 51))
self.btn_calibrate.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(34, 153, 129, 255), stop:1 rgba(255, 255, 255, 255));\n"
"font: 75 12pt \"MS Shell Dlg 2\";")
self.btn_calibrate.setObjectName("btn_calibrate")
#MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint)
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "STATUS/OUTPUT"))
self.label_2.setText(_translate("MainWindow", "PUMP1 :"))
self.label_3.setText(_translate("MainWindow", "PUMP2 :"))
self.label_4.setText(_translate("MainWindow", "PUMP3 :"))
self.label_5.setText(_translate("MainWindow", "TIME :"))
self.label_6.setText(_translate("MainWindow", "ERROR:"))
self.lbl_pump1.setText(_translate("MainWindow", "0.0"))
self.lbl_pump2.setText(_translate("MainWindow", "0.0"))
self.lbl_pump3.setText(_translate("MainWindow", "0.0"))
self.lbl_msg.setText(_translate("MainWindow", "..."))
self.lbl_error.setText(_translate("MainWindow", "..."))
self.label_27.setText(_translate("MainWindow", "Select Oz/Ltl/ Gal"))
self.label_7.setText(_translate("MainWindow", "LOW"))
self.label_8.setText(_translate("MainWindow", "MID"))
self.label_9.setText(_translate("MainWindow", "HIGH"))
self.cb_pump1.setText(_translate("MainWindow", "Pump1"))
self.cb_pump2.setText(_translate("MainWindow", "Pump2"))
self.cb_pump3.setText(_translate("MainWindow", "Pump3"))
self.label_10.setText(_translate("MainWindow", "Select Pumps"))
self.btn_start.setText(_translate("MainWindow", "Start"))
self.btn_calibrate.setText(_translate("MainWindow", "Calibrate"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow1()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
|
{"/test2.py": ["/RPI.py"], "/RPI.py": ["/EncoderClass.py"], "/GUI.py": ["/screen1.py", "/screen2.py", "/RPI.py"]}
|
42,668,247
|
EdLeafe/leafe
|
refs/heads/main
|
/trace.py
|
import pudb
pudb.set_trace()
|
{"/threadize.py": ["/utils.py"], "/twitterthread.py": ["/threadize.py"], "/ircsearch.py": ["/utils.py"], "/zipcodes.py": ["/utils.py"], "/leafe.py": ["/archives.py", "/art.py", "/downloads.py", "/drstandup.py", "/galleries.py", "/ircsearch.py", "/twitterthread.py", "/zipcodes.py"], "/cloud_upload.py": ["/utils.py"], "/downloads.py": ["/utils.py"], "/galleries.py": ["/utils.py"], "/archives.py": ["/utils.py"]}
|
42,668,248
|
EdLeafe/leafe
|
refs/heads/main
|
/threadize.py
|
from __future__ import absolute_import, print_function, unicode_literals
import os
import re
import sys
MAX_LENGTH = 280
BREAK_ON_SENTENCE = True
END_TXT = " /end"
CONTINUATION = "..."
TEST_FILE = "towel.txt"
SENTENCE_END = r"[\.\?!]"
SENTENCE_END_PAT = re.compile(SENTENCE_END)
BREAK_CHARS = r"[:;,]"
BREAK_CHARS_PAT = re.compile(BREAK_CHARS)
NOT_PUNC = r"[^\.\?!;:,]+"
SEP = "^@^"
TOTAL_HOLDER = "@"
URL_PAT = re.compile(
r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
)
# All URLs count as 23 characters in tweets
URL_PLACEHOLDER = "@" * 23
tag_position = None
holder = None
def make_thread(txt, num_style, break_style, end_text):
txt = remove_newlines(txt)
pg_pat = _get_page_pattern(num_style, len(txt))
tokens = tokenize(txt, break_style)
chunks = chunker(tokens, num_style, pg_pat, end_text)
if holder:
chunks = [chunk.replace(holder, str(len(chunks))) for chunk in chunks]
return chunks
def _get_page_pattern(num_style, txtlen):
global tag_position, holder
tag_position = num_style[-1]
if num_style.startswith("nsn"):
# Need to get a rough idea of the maximum number of chunks, so that we know how many spaces
# to reserve for the total in 1/N style numbering. For this, take the total length divided
# by the max per tweet, and double it.
maxnum = int(txtlen / MAX_LENGTH) * 2
holder = TOTAL_HOLDER * len(str(maxnum))
pg_pat = "{}/" + holder
if tag_position == "b":
pg_pat = pg_pat + " "
else:
pg_pat = " " + pg_pat
else:
pg_pat = "{}/ " if tag_position == "b" else " /{}"
return pg_pat
def remove_newlines(txt):
t1 = re.sub(r"[\n\r]+", r"\n", txt)
return re.sub(r"\n", " ", t1)
def rejoin(fragments, separators, num):
frags = fragments[:num]
seps = separators[: num - 1]
frag_join = "{}".join(frags)
return frag_join.format(*seps)
def reduce_urls(txt):
"""Twitter counts all URLs as only 23 characters, so this replaces all URLs
in the text with a 23-character placeholder.
"""
return URL_PAT.sub(URL_PLACEHOLDER, txt)
def split_sentence(sentence, pg_txt):
# see if there is any punctuation in the second half of the sentence that
# would be a natural break point
senlen = len(sentence)
len_pg_txt = len(pg_txt)
midpoint = senlen / 2
fragments = BREAK_CHARS_PAT.split(sentence)
separators = BREAK_CHARS_PAT.findall(sentence)
pos = 0
if separators:
shorter = sentence
pos = num_frags = len(fragments)
while len(shorter) + len_pg_txt > MAX_LENGTH and pos > 0:
shorter = shorter.rstrip(fragments[pos - 1])
pos -= 1
if pos:
extra = sentence.lstrip(shorter)
if tag_position == "e":
extra = extra.rstrip(pg_txt).strip(" ")
shorter = shorter.rstrip() + pg_txt
else:
extra = extra.lstrip(pg_txt).strip(" ")
shorter = pg_txt + shorter.rstrip()
return shorter, extra
else:
# Cannot split into smaller parts based on break characters. Just find the word break that
# maximizes the chunk.
max_sentence_length = MAX_LENGTH - len_pg_txt
max_short = sentence[:max_sentence_length]
try:
last_space = max_short.rindex(" ")
except ValueError:
# No way to separate; just return the longest substring
max_sentence_length = MAX_LENGTH - len_pg_txt - len(CONTINUATION)
if tag_position == "e":
shorter = sentence[:max_sentence_length] + CONTINUATION + pg_txt
else:
shorter = pg_txt + sentence[:max_sentence_length] + CONTINUATION
extra = sentence[max_sentence_length + 1 :]
return shorter, extra
if tag_position == "e":
shorter = sentence[:last_space] + pg_txt
else:
shorter = pg_txt + sentence[:last_space]
extra = sentence[last_space + 1 :]
return shorter, extra
def chunker(tokens, num_style, pg_pat, end_text):
pos = 0
sentences = []
sentence_end = 0
from utils import logit
logit("TOKENS AT START", tokens)
while True:
try:
sentence_end = tokens.index(SEP)
except ValueError:
# Add the last bit
sentences.append(" ".join(tokens[-1:]))
logit("LAST", sentence_end, tokens[-1:])
break
sentences.append(" ".join(tokens[:sentence_end]))
tokens = tokens[sentence_end + 1 :]
chunks = []
to_skip = 0
for pos, sentence in enumerate(sentences):
if to_skip:
to_skip -= 1
continue
sentence = sentence.strip()
chunk_num = len(chunks) + 1
pg_txt = pg_pat.format(chunk_num)
args = (sentence, pg_txt) if tag_position == "e" else (pg_txt, sentence)
proposed_with_pg_txt = "{}{}".format(*args)
len_proposed_with_pg_txt = len(reduce_urls(proposed_with_pg_txt))
# Need to iterate through long sentences until done.
while len_proposed_with_pg_txt > MAX_LENGTH:
proposed_with_pg_txt, extra = split_sentence(sentence, pg_txt)
chunks.append(proposed_with_pg_txt)
sentence = extra.strip()
chunk_num = len(chunks) + 1
pg_txt = pg_pat.format(chunk_num)
args = (sentence, pg_txt) if tag_position == "e" else (pg_txt, sentence)
proposed_with_pg_txt = "{}{}".format(*args)
len_proposed_with_pg_txt = len(reduce_urls(proposed_with_pg_txt))
proposed = proposed_with_pg_txt
len_proposed = len(reduce_urls(proposed))
ahead = 1
# See if we can add more sentences.
while True:
extra_room = MAX_LENGTH - len_proposed
try:
next_sentence = sentences[pos + ahead]
except IndexError:
# At the end of the text; need to change the pg_txt for the last chunk
if len(chunks):
# If no end_text, leave the tag as is
if end_text:
end_pat = "{}/ " if tag_position == "b" else " /{}"
proposed = proposed.replace(pg_txt, end_pat.format(end_text))
else:
# Just a single chunk, so remove the pg_txt.
proposed = proposed.replace(pg_txt, "")
break
if len(reduce_urls(next_sentence)) < extra_room:
# Add that to the current chunk
if tag_position == "e":
proposed = "{} {}{}".format(proposed.rstrip(pg_txt), next_sentence, pg_txt)
else:
proposed = "{}{} {}".format(pg_txt, proposed.lstrip(pg_txt), next_sentence)
to_skip += 1
ahead += 1
len_proposed = len(reduce_urls(proposed))
else:
break
# We've reached the maximum size.
chunks.append(proposed)
return chunks
def tokenize(txt, break_style):
tokens = []
def spc(scn, txt):
pass
def snt(scn, txt):
brk(scn, txt)
tokens.append(SEP)
def brk(scn, txt):
if tokens:
tokens[-1] += txt
else:
tokens.append(txt)
def char(scn, txt):
tokens.append(txt)
# The text may contain URLs that have punctuation that we don't want to
# break on, so reduce them with the placeholders, and then restore the URLs
# afterwards.
urls = URL_PAT.findall(txt)
reduced_text = reduce_urls(txt)
if break_style == "sentence":
scanner = re.Scanner(
[
(r" ", spc),
(SENTENCE_END, snt),
(BREAK_CHARS, brk),
(NOT_PUNC, char),
]
)
else:
scanner = re.Scanner(
[
(r" ", spc),
(SENTENCE_END, snt),
(BREAK_CHARS, snt),
(NOT_PUNC, char),
]
)
scanner.scan(reduce_urls(txt))
# Now replace the URLs where their placeholders were
for pos, token in enumerate(tokens):
while urls and URL_PLACEHOLDER in token:
tokens[pos] = token = token.replace(URL_PLACEHOLDER, urls[0], 1)
urls.pop(0)
return tokens
def main():
if len(sys.argv) < 2:
fname = TEST_FILE
number_style = "sne"
break_at = "sentence"
end_text = "/end"
else:
fname = sys.argv[1]
if not os.path.exists(fname):
raise IOError("The file '{}' does not exist".format(name))
number_style = sys.argv[2] if len(sys.argv) > 2 else "sne"
break_at = sys.argv[3] if len(sys.argv) > 3 else "sentence"
end_text = sys.argv[4] if len(sys.argv) > 4 else "/end"
with open(fname) as ff:
txt = ff.read()
txt = remove_newlines(txt)
chunks = make_thread(txt, number_style, break_at, end_text)
for chunk in chunks:
print(chunk)
if __name__ == "__main__":
main()
|
{"/threadize.py": ["/utils.py"], "/twitterthread.py": ["/threadize.py"], "/ircsearch.py": ["/utils.py"], "/zipcodes.py": ["/utils.py"], "/leafe.py": ["/archives.py", "/art.py", "/downloads.py", "/drstandup.py", "/galleries.py", "/ircsearch.py", "/twitterthread.py", "/zipcodes.py"], "/cloud_upload.py": ["/utils.py"], "/downloads.py": ["/utils.py"], "/galleries.py": ["/utils.py"], "/archives.py": ["/utils.py"]}
|
42,668,249
|
EdLeafe/leafe
|
refs/heads/main
|
/twitterthread.py
|
import json
import re
from flask import g, render_template, request
import threadize
def show_form():
g.chunks = []
return render_template("twitterthread_form.html")
def make_thread():
rf = request.form
txt = rf["source"]
number_style = rf["number_style"]
break_at = rf["break_at"]
end_text = rf["end_text"]
g.number_style = number_style
g.break_at = break_at
g.chunks = threadize.make_thread(txt, number_style, break_at, end_text)
if request.headers.get("Accept") == "application/json":
return json.dumps(g.chunks)
return render_template("twitterthread_results.html")
|
{"/threadize.py": ["/utils.py"], "/twitterthread.py": ["/threadize.py"], "/ircsearch.py": ["/utils.py"], "/zipcodes.py": ["/utils.py"], "/leafe.py": ["/archives.py", "/art.py", "/downloads.py", "/drstandup.py", "/galleries.py", "/ircsearch.py", "/twitterthread.py", "/zipcodes.py"], "/cloud_upload.py": ["/utils.py"], "/downloads.py": ["/utils.py"], "/galleries.py": ["/utils.py"], "/archives.py": ["/utils.py"]}
|
42,668,250
|
EdLeafe/leafe
|
refs/heads/main
|
/ircsearch.py
|
import copy
import datetime as dt
import hashlib
import html
import random
import re
import time
from elasticsearch import Elasticsearch
from flask import abort, g, render_template, request, session
import utils
from utils import logit
START_DATE = "2016-01-01"
END_DATE = "2020-12-31"
INDEX = "irclog"
HOST = "dodata"
QUERY_MAX = 10000
PER_PAGE = 100
LINK_PAT = re.compile(r"(.*)\b(https?://\S+)(.*)", re.I)
COLORS = (
"#407a40",
"#42427e",
"#488888",
"#4b904b",
"#4d4d93",
"#539e9e",
"#57a657",
"#5959a9",
"#5fb4b4",
"#62bb62",
"#6464bf",
"#6acaca",
"#6ed16e",
"#7070d5",
"#76e0e0",
"#818144",
"#854685",
"#8c4a4a",
"#97974f",
"#9b519b",
"#a25555",
"#a9a942",
"#ad5b5b",
"#adad5b",
"#b15db1",
"#b86161",
"#c3c366",
"#c668c6",
"#ce6c6c",
"#dc74dc",
)
es_client = Elasticsearch(host=HOST)
def _make_username():
now = dt.datetime.now().strftime("%T.%f").encode("utf8")
return hashlib.md5(now).hexdigest()
def _get_channels():
logit(
"CHANNELS",
{"aggs": {"channels": {"terms": {"field": "channel", "size": 1000}}}},
)
resp = es_client.search(
index=INDEX,
body={"aggs": {"channels": {"terms": {"field": "channel", "size": 1000}}}},
size=0,
)
clist = resp.get("aggregations").get("channels").get("buckets")
retlist = [cl["key"] for cl in clist]
retlist.sort()
return retlist
def _get_sort_order(order_by):
sorttext = {"recent_first": "posted:desc", "oldest_first": "posted:asc"}.get(order_by)
return [sorttext]
def show_search_form():
g.channels = _get_channels()
logit("Got channels")
g.startdate = START_DATE
g.enddate = END_DATE
return render_template("irc_search_form.html")
def make_clickable(p):
mtch = LINK_PAT.match(p)
if not mtch:
if "<span " in p or "<b>" in p:
return p
return html.escape(p)
pre, uri, post = mtch.groups()
if "<span " in uri:
# Hilited text, don't make a link
return p
link = '<a href="%s" target="_new">%s</a>' % (uri, uri)
return "".join((pre, link, post))
def POST_search_results():
form = request.form
sel_channel = form.get("channel")
sort_order = form.get("sort_order")
search_terms = form.get("msg_text")
search_nick = form.get("nick")
if not (search_terms or search_nick):
abort(400, "You must supply search terms and/or a nick")
start_date = form.get("start_date")
end_date = form.get("end_date")
kwargs = utils.search_term_query(search_terms, "remark", start_date, end_date)
bqbm = kwargs["body"]["query"]["bool"]["must"]
neg_bqbm = kwargs["body"]["query"]["bool"]["must_not"]
bqbf = kwargs["body"]["query"]["bool"]["filter"]
if sel_channel:
bqbf.append({"term": {"channel": sel_channel}})
if search_nick:
bqbf.append({"term": {"nick": search_nick}})
if sort_order:
kwargs["sort"] = _get_sort_order(sort_order)
kwargs["size"] = QUERY_MAX
startTime = time.time()
logit("POST SEARCH KW", kwargs)
resp = es_client.search(index=INDEX, **kwargs)
g.elapsed = "%.4f" % (time.time() - startTime)
hits = resp["hits"]["hits"]
hit_count = len(hits)
if hit_count == QUERY_MAX:
kwargs["size"] = 0
tot = es_client.search(index=INDEX, track_total_hits=True, **kwargs)
hit_count = tot["hits"]["total"]["value"]
def hilite(s):
"""Hilite the search terms in the remark"""
if isinstance(search_terms, (list, tuple)):
terms = search_terms
else:
terms = [search_terms]
for term in terms:
# s = s.replace(term, "<span class=hilite>%s</span>" % term)
s = re.sub(term, f"<span class=hilite>{term}</span>", s, flags=re.I)
return s
g.hilite = hilite
g.results = [hit["_source"] for hit in hits]
g.num_results = hit_count
g.formatted_results = f"{hit_count:,}"
g.kwargs = kwargs
return render_template("irc_search_results.html", make_clickable=make_clickable)
def earlier(channel, end, size):
return chan_range(channel, "lt", end, size, "desc")
def later(channel, start, size):
return chan_range(channel, "gte", start, size, "asc")
def chan_range(chan, op, tm, size, ordr):
return {
"body": {
"query": {
"bool": {
"filter": [
{"term": {"channel": chan}},
{"range": {"posted": {op: tm}}},
]
}
}
},
"size": size,
"sort": ["posted:{}".format(ordr)],
}
def _pick_color():
return random.choice(COLORS)
def show_timeline(channel, start, end, middle=False):
"""If 'middle' is True, we need to do 2 queries, with half of the results
earlier than the 'start', and the other half later.
"""
if middle:
before = earlier(channel, start, 10)
logit("BEFORE", before)
resp = es_client.search(index=INDEX, **before)
hits_before = resp["hits"]["hits"]
hits_before.reverse()
after = later(channel, start, PER_PAGE - 10)
logit("AFTER", after)
resp = es_client.search(index=INDEX, **after)
hits_after = resp["hits"]["hits"]
hits = hits_before + hits_after
g.rows = [hit["_source"] for hit in hits]
g.hilite_time = start
else:
if end:
adjective = "earlier"
kwargs = earlier(channel, end, PER_PAGE)
else:
adjective = "later"
kwargs = later(channel, start, PER_PAGE)
logit("TIMELINE", kwargs)
resp = es_client.search(index=INDEX, **kwargs)
hits = resp["hits"]["hits"]
if not hits:
abort(404, "There are no %s messages" % adjective)
if end:
hits.reverse()
g.rows = [hit["_source"] for hit in hits]
g.hilite_time = ""
sess_map = session.get("color_map", {})
g.color_map = {}
for row in g.rows:
nick = row["nick"]
if nick in g.color_map:
continue
g.color_map[nick] = sess_map.get(nick) or _pick_color()
session["color_map"] = g.color_map
logit("ROWS", g.rows)
return render_template("irc_timeline.html", make_clickable=make_clickable)
|
{"/threadize.py": ["/utils.py"], "/twitterthread.py": ["/threadize.py"], "/ircsearch.py": ["/utils.py"], "/zipcodes.py": ["/utils.py"], "/leafe.py": ["/archives.py", "/art.py", "/downloads.py", "/drstandup.py", "/galleries.py", "/ircsearch.py", "/twitterthread.py", "/zipcodes.py"], "/cloud_upload.py": ["/utils.py"], "/downloads.py": ["/utils.py"], "/galleries.py": ["/utils.py"], "/archives.py": ["/utils.py"]}
|
42,668,251
|
EdLeafe/leafe
|
refs/heads/main
|
/timeline.py
|
import copy
import datetime as dt
import hashlib
from elasticsearch import Elasticsearch
from flask import Flask, abort, g, redirect, render_template, request, session
from flask import url_for, make_response, render_template
import dbutil
INDEX = "irclog"
HOST = "159.203.122.132"
es_client = Elasticsearch(host=HOST)
def show(channel, start):
return "Received: %s @ %s" % (channel, start)
def _make_username():
now = dt.datetime.now().strftime("%T.%f").encode("utf8")
return hashlib.md5(now).hexdigest()
def _get_channels():
resp = es_client.search("irclog", body={"aggs": {"channels": {"terms": {"field": "channel"}}}})
clist = resp.get("aggregations").get("channels").get("buckets")
return [cl["key"] for cl in clist]
def show_search_form():
g.channels = _get_channels()
return render_template("search_form.html")
def POST_search_results():
form = request.form
sel_channel = form.get("select_channel")
user_data = session.get("user", {})
if user_data:
username = user_data["username"]
data = dbutil.get_user_data(username)
if data:
user_data.update(data)
else:
username = _make_username()
session["user"] = username
user_data = {"username": username}
sort_order = form.get("sort_order")
search_terms = form.get("search_terms")
if not search_terms:
abort(400, "You must supply search terms")
exact = bool(form.get("phrase"))
match_type = "match_phrase" if exact else "match"
if sel_channel == "_all":
body = {"query": {match_type: {"remark": search_terms}}}
else:
body = {
"query": {
"bool": {
"must": [{match_type: {"remark": search_terms}}],
"filter": [{"term": {"channel": sel_channel}}],
}
}
}
kwargs = {"body": body, "size": 10000, "sort": ["posted:%s" % sort_order]}
resp = es_client.search(INDEX, **kwargs)
hits = resp["hits"]["hits"]
def hilite(s):
"""Hilite the search terms in the remark"""
if isinstance(search_terms, (list, tuple)):
terms = search_terms
else:
terms = [search_terms]
for term in terms:
s = s.replace(term, "<span class=hilite>%s</span>" % term)
return s
g.hilite = hilite
g.rows = [hit["_source"] for hit in hits]
g.offset = user_data.get("offset", 0)
dbutil.store_data(username, user_data)
session["user"] = copy.deepcopy(user_data)
return render_template("search_results.html")
|
{"/threadize.py": ["/utils.py"], "/twitterthread.py": ["/threadize.py"], "/ircsearch.py": ["/utils.py"], "/zipcodes.py": ["/utils.py"], "/leafe.py": ["/archives.py", "/art.py", "/downloads.py", "/drstandup.py", "/galleries.py", "/ircsearch.py", "/twitterthread.py", "/zipcodes.py"], "/cloud_upload.py": ["/utils.py"], "/downloads.py": ["/utils.py"], "/galleries.py": ["/utils.py"], "/archives.py": ["/utils.py"]}
|
42,668,252
|
EdLeafe/leafe
|
refs/heads/main
|
/art.py
|
import requests
from flask import render_template
BLOG_URL = "https://blog.leafe.com/category/art,photography/feed/"
def about():
return render_template("art_about.html")
def design():
return render_template("art_design.html")
def photo_principles():
return render_template("art_photo_principles.html")
def art_blog():
resp = requests.get(BLOG_URL)
with open("blog.xml", "w") as ff:
ff.write(resp.text)
|
{"/threadize.py": ["/utils.py"], "/twitterthread.py": ["/threadize.py"], "/ircsearch.py": ["/utils.py"], "/zipcodes.py": ["/utils.py"], "/leafe.py": ["/archives.py", "/art.py", "/downloads.py", "/drstandup.py", "/galleries.py", "/ircsearch.py", "/twitterthread.py", "/zipcodes.py"], "/cloud_upload.py": ["/utils.py"], "/downloads.py": ["/utils.py"], "/galleries.py": ["/utils.py"], "/archives.py": ["/utils.py"]}
|
42,668,253
|
EdLeafe/leafe
|
refs/heads/main
|
/utils.py
|
import datetime
from functools import wraps, update_wrapper
import logging
import math
import os
import random
import re
from subprocess import Popen, PIPE
import time
import uuid
import boto
from flask import make_response
import pymysql
from pymysql.err import InternalError as PymysqlInternalError
import requests
main_cursor = None
HOST = "dodata"
conn = None
LOG = logging.getLogger(__name__)
BASE_DIR = "/home/ed/projects/leafe"
LOGIT_FILE = os.path.join(BASE_DIR, "LOGOUT")
PHRASE_PAT = re.compile('"([^"]*)"*')
IntegrityError = pymysql.err.IntegrityError
def logit(*msgs):
tm = datetime.datetime.utcnow().replace(microsecond=0)
tmstr = time.strftime("%Y-%m-%dT%H:%M:%S")
msg_str = " ".join(["%s" % m for m in msgs])
msg = tmstr + " " + msg_str
with open(LOGIT_FILE, "a") as ff:
ff.write(f"{msg}\n")
class DotDict(dict):
"""
Dictionary subclass that allows accessing keys via dot notation.
If the key is not present, an AttributeError is raised.
"""
_att_mapper = {}
_fail = object()
def __init__(self, *args, **kwargs):
super(DotDict, self).__init__(*args, **kwargs)
def __getattr__(self, att):
att = self._att_mapper.get(att, att)
ret = self.get(att, self._fail)
if ret is self._fail:
raise AttributeError(
"'%s' object has no attribute '%s'" % (self.__class__.__name__, att)
)
return ret
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def runproc(cmd):
proc = Popen([cmd], shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
stdout_text, stderr_text = proc.communicate()
return stdout_text, stderr_text
def parse_creds():
with open("/home/ed/projects/leafe/.dbcreds") as ff:
lines = ff.read().splitlines()
ret = {}
for ln in lines:
key, val = ln.split("=")
ret[key] = val
return DotDict(ret)
def connect(creds=None):
cls = pymysql.cursors.DictCursor
# If credentials aren't supplied, use the ones in .dbcreds
creds = creds or parse_creds()
ret = pymysql.connect(
host=creds.get("host") or HOST,
user=creds["username"],
passwd=creds["password"],
db=creds["dbname"],
charset="utf8",
cursorclass=cls,
)
return ret
def gen_uuid():
return str(uuid.uuid4())
def get_cursor():
global conn, main_cursor
if not (conn and conn.open):
LOG.debug("No DB connection")
main_cursor = None
conn = connect()
conn.ping(reconnect=True)
if not main_cursor:
LOG.debug("No cursor")
main_cursor = conn.cursor(pymysql.cursors.DictCursor)
return main_cursor
def commit():
conn.commit()
def debugout(*args):
with open("/tmp/debugout", "a") as ff:
ff.write("YO!")
argtxt = [str(arg) for arg in args]
msg = " ".join(argtxt) + "\n"
with open("/tmp/debugout", "a") as ff:
ff.write(msg)
def nocache(view):
@wraps(view)
def no_cache(*args, **kwargs):
response = make_response(view(*args, **kwargs))
response.headers["Last-Modified"] = datetime.datetime.now()
response.headers["Cache-Control"] = (
"no-store, no-cache, " "must-revalidate, post-check=0, pre-check=0, max-age=0"
)
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "-1"
return response
return update_wrapper(no_cache, view)
def human_fmt(num):
"""Human friendly file size"""
# Make sure that we get a valid input. If an invalid value is passed, we
# want the exception to be raised.
num = int(num)
units = list(zip(["bytes", "K", "MB", "GB", "TB", "PB"], [0, 0, 1, 2, 2, 2]))
if num > 1:
exponent = min(int(math.log(num, 1024)), len(units) - 1)
quotient = float(num) / 1024 ** exponent
unit, num_decimals = units[exponent]
format_string = "{:.%sf} {}" % (num_decimals)
return format_string.format(quotient, unit)
if num == 0:
return "0 bytes"
if num == 1:
return "1 byte"
def _user_creds():
with open("/home/ed/docreds.rc") as ff:
creds = ff.read()
user_creds = {}
for ln in creds.splitlines():
if ln.startswith("spacekey"):
user_creds["spacekey"] = ln.split("=")[-1].strip()
elif ln.startswith("secret"):
user_creds["secret"] = ln.split("=")[-1].strip()
elif ln.startswith("bucket"):
user_creds["bucket"] = ln.split("=")[-1].strip()
return user_creds
def get_client():
user_creds = _user_creds()
conn = boto.connect_s3(
aws_access_key_id=user_creds["spacekey"],
aws_secret_access_key=user_creds["secret"],
host="nyc3.digitaloceanspaces.com",
)
bucket = conn.get_bucket(user_creds["bucket"])
return bucket
def upload_to_DO(fpath, folder=None, public=False):
"""Uploads the specified file to the default DigitalOcean space. If a
folder is specified, that will be used as a prefix for the remote file.
Example:
fpath = "/home/ed/photos/test_image.jpg"
folder = None
-> will create the key 'test_image.jpg'
fpath = "/home/ed/photos/test_image.jpg"
folder = "Family Photos/June"
-> will create the key 'Family Photos/June/test_image.jpg'
If the parameter 'public' is True, the remote file will be made publicly available.
"""
folder = folder or ""
fname = os.path.basename(fpath)
remote_path = os.path.join(folder, fname)
clt = get_client()
remote_file = clt.new_key(remote_path)
with open(fpath, "rb") as file_to_upload:
remote_file.set_contents_from_file(file_to_upload)
if public:
remote_file.make_public()
def get_gallery_names():
clt = get_client()
prefix = "galleries/"
all_names = clt.list(prefix=prefix, delimiter="/")
full_names = (itm.name for itm in all_names)
names = (itm.split(prefix)[-1] for itm in full_names)
cleaned = [itm.rstrip("/") for itm in names if itm]
return cleaned
def get_photos_in_gallery(gallery_name):
clt = get_client()
prefix = f"galleries/{gallery_name}/"
all_photos = clt.list(prefix=prefix)
photos_with_meta = {
itm.name.split("galleries/")[-1]: clt.get_key(itm).metadata for itm in all_photos
}
photo_keys = list(photos_with_meta.keys())
random.shuffle(photo_keys)
shuffled_photos = {pk: photos_with_meta.get(pk) for pk in photo_keys if not pk.endswith("/")}
return shuffled_photos
def download(remote_url, folder, fname):
"""Download the file at the remote address, and write it to the specified
folder
"""
dl = requests.get(remote_url, allow_redirects=True)
location = os.path.join(folder, fname)
with open(location, "wb") as ff:
ff.write(dl.content)
def _parse_search_terms(term_string):
phrases = PHRASE_PAT.findall(term_string)
# logit("Phrases:", phrases)
terms = PHRASE_PAT.split(term_string)
# logit("Terms:", terms)
for phrase in phrases:
terms.remove(phrase)
words_required = []
words_forbidden = []
phrases_required = []
phrases_forbidden = []
for phrase in phrases:
phrase = phrase.strip()
if phrase.startswith("-"):
# logit("Forbidden phrase:", phrase)
phrases_forbidden.append(phrase[1:])
else:
# logit("Allowed phrase:", phrase)
phrases_required.append(phrase)
for term in terms:
# A 'term' can consist of multiple words.
term_words = term.split()
for term_word in term_words:
term_word = term_word.strip()
if term_word.startswith("-"):
# logit("Forbidden term:", term_word)
words_forbidden.append(term_word[1:])
else:
# logit("Allowed term:", term_word)
words_required.append(term_word)
# We have the values in lists, but we need simple strings
return (
" ".join(words_required),
" ".join(words_forbidden),
" ".join(phrases_required),
" ".join(phrases_forbidden),
)
def add_match(lst, key, val, operator=None):
if operator:
lst.append({"match": {key: {"query": val, "operator": operator}}})
else:
lst.append({"match": {key: val}})
def add_match_phrase(lst, key, val):
lst.append({"match_phrase": {key: val}})
def search_term_query(search_text, search_field, start_date, end_date):
kwargs = {
"body": {
"query": {
"bool": {
"filter": [],
"must": [],
"must_not": [],
}
}
}
}
bqbm = kwargs["body"]["query"]["bool"]["must"]
neg_bqbm = kwargs["body"]["query"]["bool"]["must_not"]
bqbf = kwargs["body"]["query"]["bool"]["filter"]
(
words_required,
words_forbidden,
phrases_required,
phrases_forbidden,
) = _parse_search_terms(search_text)
if words_required:
add_match(bqbm, search_field, words_required, operator="and")
if words_forbidden:
add_match(neg_bqbm, search_field, words_forbidden, operator="and")
if phrases_required:
add_match_phrase(bqbm, search_field, phrases_required)
if phrases_forbidden:
add_match_phrase(neg_bqbm, search_field, phrases_forbidden)
bqbf.append({"range": {"posted": {"gte": start_date, "lt": end_date}}})
return kwargs
|
{"/threadize.py": ["/utils.py"], "/twitterthread.py": ["/threadize.py"], "/ircsearch.py": ["/utils.py"], "/zipcodes.py": ["/utils.py"], "/leafe.py": ["/archives.py", "/art.py", "/downloads.py", "/drstandup.py", "/galleries.py", "/ircsearch.py", "/twitterthread.py", "/zipcodes.py"], "/cloud_upload.py": ["/utils.py"], "/downloads.py": ["/utils.py"], "/galleries.py": ["/utils.py"], "/archives.py": ["/utils.py"]}
|
42,668,254
|
EdLeafe/leafe
|
refs/heads/main
|
/drstandup.py
|
import datetime
import hashlib
import random
from flask import abort, g, redirect, render_template, request, url_for
team_names = []
with open("cx_team_names.txt") as ff:
team_names = ff.readlines()
def random_order():
dtstr = datetime.datetime.utcnow().strftime("%Y%m%d")
dated_team = [("{}{}".format(dtstr, nm), nm) for nm in team_names]
hashed_team = [(hashlib.md5(dtnm.encode("UTF-8")).hexdigest(), nm) for dtnm, nm in dated_team]
hashed_team.sort()
names = "".join(["• {}".format(nm) for _, nm in hashed_team])
line = "--------------------------------------------\n"
return "{}{}{}".format(line, names, line)
|
{"/threadize.py": ["/utils.py"], "/twitterthread.py": ["/threadize.py"], "/ircsearch.py": ["/utils.py"], "/zipcodes.py": ["/utils.py"], "/leafe.py": ["/archives.py", "/art.py", "/downloads.py", "/drstandup.py", "/galleries.py", "/ircsearch.py", "/twitterthread.py", "/zipcodes.py"], "/cloud_upload.py": ["/utils.py"], "/downloads.py": ["/utils.py"], "/galleries.py": ["/utils.py"], "/archives.py": ["/utils.py"]}
|
42,668,255
|
EdLeafe/leafe
|
refs/heads/main
|
/zipcodes.py
|
import time
from flask import abort, g, redirect, render_template, request, url_for
import utils
class SearchObj:
def __init__(self, form=None):
self.form = form
self.results = []
self.statement = ""
self.elapsed = 0.0
self.parts = []
self.search_terms = []
self.params = []
self.statement_parts = []
self.exception = ""
self.strict = True
def strictify(self, val):
if self.strict:
if not val.startswith("^"):
val = "^{}".format(val)
if not val.endswith("$"):
val = "{}$".format(val)
return val
def process_term(self, term, field=None):
val = self.form.get(term)
field = field or term
if val:
self.parts.append("{} REGEXP %s".format(field))
self.search_terms.append(val)
self.params.append(self.strictify(val))
self.statement_parts.append("{} matches '{}'".format(term, val))
def search(self):
if not self.form:
return
self.process_term("zipcode", "postal_code")
self.process_term("city")
self.process_term("state")
where_clause = ""
if self.parts:
where_clause = "where {}".format(" and ".join(self.parts))
self.statement = ", ".join(self.statement_parts)
sql = "select * from zip {} order by postal_code limit 100;".format(where_clause)
crs = utils.get_cursor()
print("SQL", sql)
print("PRMS", self.params)
start = time.time()
try:
crs.execute(sql, self.params)
self.results = crs.fetchall()
except utils.PymysqlInternalError:
terms = ", ".join(self.search_terms)
self.exception = f"Search failed: illegal regex expression: '{terms}'"
self.elapsed = time.time() - start
def run_search():
search_obj = SearchObj(request.form)
search_obj.search()
return search_obj
def show():
g.show_results = request.method == "POST"
if g.show_results:
search_obj = run_search()
g.results = search_obj.results
g.query = search_obj.statement
g.num_results = len(g.results)
g.elapsed = round(search_obj.elapsed, 4)
g.exception = search_obj.exception
else:
g.results = []
g.query = ""
g.num_results = 0
g.elapsed = 0.0
g.exception = ""
return render_template("zipcodes.html")
|
{"/threadize.py": ["/utils.py"], "/twitterthread.py": ["/threadize.py"], "/ircsearch.py": ["/utils.py"], "/zipcodes.py": ["/utils.py"], "/leafe.py": ["/archives.py", "/art.py", "/downloads.py", "/drstandup.py", "/galleries.py", "/ircsearch.py", "/twitterthread.py", "/zipcodes.py"], "/cloud_upload.py": ["/utils.py"], "/downloads.py": ["/utils.py"], "/galleries.py": ["/utils.py"], "/archives.py": ["/utils.py"]}
|
42,668,256
|
EdLeafe/leafe
|
refs/heads/main
|
/leafe.py
|
import datetime
import os
import random
from flask import Flask, abort, g, render_template, request, session, url_for
from flask_session import Session
import archives
import art
import downloads
import drstandup
import galleries
import ircsearch
import twitterthread
import zipcodes
from logging.config import dictConfig
dictConfig(
{
"version": 1,
"formatters": {
"default": {
"format": "[%(asctime)s] %(levelname)s in %(module)s: %(message)s",
}
},
"handlers": {
"wsgi": {
"class": "logging.StreamHandler",
"stream": "ext://flask.logging.wsgi_errors_stream",
"formatter": "default",
}
},
"root": {"level": "INFO", "handlers": ["wsgi"]},
}
)
INDEX_IMAGE_PATH = "static/images/index/"
app = Flask(__name__)
app.secret_key = b"C\xba\x87\xbf\xca'i\xbf\xab\xc4\x9b\x97\xdc\xef\xb0\x9a\xed"
app.url_map.strict_slashes = False
# For uwsgi
application = app
app.config["SESSION_PERMANENT"] = True
app.config["SESSION_TYPE"] = "filesystem"
app.config["PERMANENT_SESSION_LIFETIME"] = datetime.timedelta(hours=12)
Session(app)
def _select_images():
pth = os.path.join(os.getcwd(), INDEX_IMAGE_PATH)
images = os.listdir(pth)
return random.sample(images, 5)
#### Basic routes ####
@app.route("/")
def index():
g.timenow = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
g.param_str = "%s" % dir(request)
g.images = _select_images()
return render_template("index.html")
@app.route("/robots.txt")
def robots():
return """User-agent: *
Disallow: /
"""
@app.errorhandler(404)
def not_found(e):
g.url = request.url
g.error = e
return render_template("not_found.html")
@app.route("/addalias")
def addalias():
return "<h3>The addalias function is not yet implemented.</h3>"
@app.route("/ip.html")
def get_ip():
g.remote_ip = request.environ["REMOTE_ADDR"]
return render_template("ip.html")
@app.route("/ip")
def get_plain_ip():
addr = request.environ["REMOTE_ADDR"]
return f"{addr}"
#### Email list routes ####
@app.route("/email_lists")
def show_email_lists():
g.email_list_card_color = "light-blue lighten-5 black-text "
return render_template("email_lists.html")
@app.route("/profox_faq")
def show_profox_faq():
g.email_list_card_color = "light-blue lighten-5 black-text "
return render_template("profox_faq.html")
@app.route("/archives/showFullThd")
def old_full_thread():
session["listname"] = request.args.get("cList", "")
msg_num = request.args.get("cMsgNum")
if not msg_num:
abort(400, f"Invalid URL: {request.url}")
return archives.show_full_thread(msg_num)
@app.route("/archives/full_thread/<msg_num>", methods=["GET"])
def show_full_thread(msg_num, the_rest=None):
return archives.show_full_thread(msg_num)
@app.route("/archives/showMsg/<msg_num>", methods=["GET"])
@app.route("/archives/msg/<msg_num>", methods=["GET"])
def show_message(msg_num):
return archives.show_message(msg_num)
@app.route("/archives/byMID/<listname>/<msg_id>", methods=["GET"])
@app.route("/archives/byMID/<msg_id>", methods=["GET"])
def show_message_by_msgid(msg_id, listname=None):
return archives.show_message_by_msgid(msg_id)
@app.route("/archives/results", methods=["POST"])
def achives_post_results():
return archives.archives_results_POST()
@app.route("/archives/results", methods=["GET"])
def achives_get_results():
return archives.archives_results_GET()
@app.route("/archives/search", methods=["GET"])
@app.route("/archives", methods=["GET"])
def achives_get():
return archives.archives_form()
#### Download routes ####
@app.route("/dls")
@app.route("/downloads")
def dls():
return downloads.main_page()
@app.route("/search_dls", methods=["POST"])
def search_dls():
return downloads.search_dls()
@app.route("/download_list")
def list_downloads():
return downloads.all_dls()
@app.route("/download_file/<url>/<url2>")
@app.route("/download_file/<url>")
def download_file(url, url2=None):
return downloads.download_file(url, url2=url2)
@app.route("/uploads")
def uploads():
return downloads.upload()
@app.route("/upload_file", methods=["POST"])
def upload_file():
return downloads.upload_file()
@app.route("/upload_test", methods=["POST"])
def upload_test():
return downloads.upload_test(app)
#### IRC log routes ####
@app.route("/ircsearch", methods=["GET"])
def get_ircsearch():
return ircsearch.show_search_form()
@app.route("/ircsearch", methods=["POST"])
def post_ircsearch():
return ircsearch.POST_search_results()
@app.route("/timeline-middle/<channel>/<start>")
def timeline_middle(channel, start, end=None):
return ircsearch.show_timeline(channel, start, end, True)
@app.route("/timeline/<channel>/<start>", defaults={"end": ""})
@app.route("/timeline/<channel>/<start>/<end>")
def timeline(channel, start, end=None):
return ircsearch.show_timeline(channel, start, end, False)
#### Twitter threading routes ####
@app.route("/twitterthread", methods=["GET"])
def get_twitterthread():
return twitterthread.show_form()
@app.route("/twitter_format", methods=["POST"])
def make_twitter_thread():
return twitterthread.make_thread()
#### Art / photo routes ####
@app.route("/art")
def get_art():
return art.about()
@app.route("/art/design")
def get_art_design():
return art.design()
@app.route("/art/photo_principles")
def get_photo_principles():
return art.photo_principles()
@app.route("/art/galleries")
def show_galleries():
return galleries.index()
@app.route("/art/galleries/<gallery>")
def show_gallery(gallery):
return galleries.show_gallery(gallery)
@app.route("/imgtest")
def imgtest():
return render_template("imgtest.html")
@app.route("/zipcodes", methods=["GET", "POST"])
def show_zip():
return zipcodes.show()
#### DataRobot routes
@app.route("/drstandup", methods=["GET", "POST"])
def standup_order():
return drstandup.random_order()
#### Linda routes ####
@app.route("/linda")
def show_linda():
return render_template("linda.html")
if __name__ == "__main__":
app.run(host="0.0.0.0")
|
{"/threadize.py": ["/utils.py"], "/twitterthread.py": ["/threadize.py"], "/ircsearch.py": ["/utils.py"], "/zipcodes.py": ["/utils.py"], "/leafe.py": ["/archives.py", "/art.py", "/downloads.py", "/drstandup.py", "/galleries.py", "/ircsearch.py", "/twitterthread.py", "/zipcodes.py"], "/cloud_upload.py": ["/utils.py"], "/downloads.py": ["/utils.py"], "/galleries.py": ["/utils.py"], "/archives.py": ["/utils.py"]}
|
42,668,257
|
EdLeafe/leafe
|
refs/heads/main
|
/cloud_upload.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import utils
def write_to_log(txt):
with open("cloud_upload.log", "a") as ff:
ff.write("{}\n".format(txt))
crs = utils.get_cursor()
crs.execute("select iid, ctype, cfile from files where uploaded = 0")
recs = crs.fetchall()
if not recs:
sys.exit()
for rec in recs:
iid = rec["iid"]
section = rec["ctype"]
filename = rec["cfile"]
fname = os.path.basename(filename)
remote_folder = "cb" if section == "c" else ""
local = os.path.join("/", "var", "www", "uploads", fname)
folder = os.path.join("ftp", remote_folder)
write_to_log("{}: Uploading {} to: {}".format(time.ctime(), local, folder))
try:
utils.upload_to_DO(local, folder=folder, public=True)
except Exception as e:
write_to_log("{}".format(e))
raise
write_to_log("{}: Completed upload of {}\n\n".format(time.ctime(), local))
crs.execute("update files set uploaded=1 where iid = %s", (iid,))
|
{"/threadize.py": ["/utils.py"], "/twitterthread.py": ["/threadize.py"], "/ircsearch.py": ["/utils.py"], "/zipcodes.py": ["/utils.py"], "/leafe.py": ["/archives.py", "/art.py", "/downloads.py", "/drstandup.py", "/galleries.py", "/ircsearch.py", "/twitterthread.py", "/zipcodes.py"], "/cloud_upload.py": ["/utils.py"], "/downloads.py": ["/utils.py"], "/galleries.py": ["/utils.py"], "/archives.py": ["/utils.py"]}
|
42,668,258
|
EdLeafe/leafe
|
refs/heads/main
|
/upload_to_do.py
|
import os
import boto
PHOTO_DIR = "/home/ed/dls/photos/"
def _user_creds():
with open("/home/ed/docreds.rc") as ff:
creds = ff.read()
user_creds = {}
for ln in creds.splitlines():
if ln.startswith("spacekey"):
user_creds["spacekey"] = ln.split("=")[-1].strip()
elif ln.startswith("secret"):
user_creds["secret"] = ln.split("=")[-1].strip()
elif ln.startswith("bucket"):
user_creds["bucket"] = ln.split("=")[-1].strip()
return user_creds
def create_client():
user_creds = _user_creds()
conn = boto.connect_s3(
aws_access_key_id=user_creds["spacekey"],
aws_secret_access_key=user_creds["secret"],
host="nyc3.digitaloceanspaces.com",
)
bucket = conn.get_bucket(user_creds["bucket"])
return bucket
def make_folder_public(folder):
"""By default DO makes everything private. Given a folder prefix, this
makes all files beginning with that prefix public.
"""
clt = create_client()
keys = clt.get_all_keys(prefix=folder)
for key in keys:
key.make_public()
def main():
import pudb
pudb.set_trace()
clt = create_client()
for root, dirs, files in os.walk(PHOTO_DIR, topdown=True):
container_name = os.path.basename(root)
for photo_name in files:
full_name = os.path.join(root, photo_name)
remote_path = os.path.join(container_name, photo_name)
remote_file = clt.new_key(remote_path)
with open(full_name, "rb") as file_to_upload:
remote_file.set_contents_from_file(file_to_upload)
remote_file.set_acl("public-read")
if __name__ == "__main__":
main()
|
{"/threadize.py": ["/utils.py"], "/twitterthread.py": ["/threadize.py"], "/ircsearch.py": ["/utils.py"], "/zipcodes.py": ["/utils.py"], "/leafe.py": ["/archives.py", "/art.py", "/downloads.py", "/drstandup.py", "/galleries.py", "/ircsearch.py", "/twitterthread.py", "/zipcodes.py"], "/cloud_upload.py": ["/utils.py"], "/downloads.py": ["/utils.py"], "/galleries.py": ["/utils.py"], "/archives.py": ["/utils.py"]}
|
42,668,259
|
EdLeafe/leafe
|
refs/heads/main
|
/helpers.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Helper functions
Consists of functions to typically be used within templates, but also
available to Controllers. This module is available to templates as 'h'.
"""
# Import helpers as desired, or define your own, ie:
# from webhelpers.html.tags import checkbox, password
import datetime
import inspect
import logging
import random
import re
from subprocess import Popen, PIPE
from textwrap import TextWrapper
MAIN_CONF = "/etc/postfix/main.cf"
VALID_NAMES = ("leafe_com", "daboserver_com", "sa_home", "iphone", "hotel", "roaming")
copyright = u"Copyright ©%s Ed Leafe" % datetime.datetime.now().year
def runproc(cmd):
proc = Popen([cmd], shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
stdout_text, stderr_text = proc.communicate()
return stdout_text, stderr_text
def wrapper(txt):
tw = TextWrapper(width=100)
out = []
for ln in txt.splitlines():
wrapped = tw.wrap(ln)
if wrapped:
out.extend(wrapped)
else:
out.extend(" ")
return "\n".join(out)
def maskEmail(val):
pat = re.compile("([^@]+)@([^@\.]+)\.([^@]+)")
ats = ("AT", "at", "At", "(AT)", "(at)", "/at/", "/AT/", ".AT.", ".at.")
atString = random.choice(ats)
dot1 = "DOT"
dot = ""
for ch in dot1:
if random.randrange(0, 2):
dot += "."
dot += ch
return pat.sub("\g<1> " + atString + " \g<2> " + dot + " \g<3>", val)
def _location_line(loc):
mtch = "%s =" % loc
cmd = "grep '%s' %s" % (mtch, MAIN_CONF)
out, err = runproc(cmd)
return out.strip()
def get_location_addr(loc):
"""Returns the current address for the specified location."""
# Make sure that the address is valid
if not loc in VALID_NAMES:
return "Invalid location: '%s'\n" % loc
line = _location_line(loc)
return line.split(" = ")[-1]
def write_conf(txt, log):
fname = "/tmp/mainconftempfile"
with open(fname, "w") as tmp:
tmp.write(txt)
cmd = "sudo cp %s %s" % (fname, MAIN_CONF)
out, err = runproc(cmd)
return err, out
def get_sa_home_ip():
return get_location_addr("sa_home")
class DotDict(dict):
"""
Dictionary subclass that allows accessing keys via dot notation.
If the key is not present, an AttributeError is raised.
"""
_att_mapper = {}
_fail = object()
def __init__(self, *args, **kwargs):
super(DotDict, self).__init__(*args, **kwargs)
def __getattr__(self, att):
att = self._att_mapper.get(att, att)
ret = self.get(att, self._fail)
if ret is self._fail:
raise AttributeError(
"'%s' object has no attribute '%s'" % (self.__class__.__name__, att)
)
return ret
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
|
{"/threadize.py": ["/utils.py"], "/twitterthread.py": ["/threadize.py"], "/ircsearch.py": ["/utils.py"], "/zipcodes.py": ["/utils.py"], "/leafe.py": ["/archives.py", "/art.py", "/downloads.py", "/drstandup.py", "/galleries.py", "/ircsearch.py", "/twitterthread.py", "/zipcodes.py"], "/cloud_upload.py": ["/utils.py"], "/downloads.py": ["/utils.py"], "/galleries.py": ["/utils.py"], "/archives.py": ["/utils.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.