text stringlengths 0 1.05M | meta dict |
|---|---|
"""Admin interface definition for certificates"""
from django.contrib import admin
from .forms import CertificateForm, DistinguishedNameForm
from .models import Certificate, DistinguishedName
class X509_pki_DistinguishedNameAdmin(admin.ModelAdmin):
search_fields = ['commonName', 'organizationName']
list_display = (
'commonName',
'countryName',
'stateOrProvinceName',
'localityName',
'organizationName',
'organizationalUnitName',
'emailAddress',
'subjectAltNames')
form = DistinguishedNameForm
def get_readonly_fields(self, request, obj=None):
if obj: # This is the case when obj is already created i.e. it's an edit
return [
'countryName',
'stateOrProvinceName',
'localityName',
'organizationName',
'organizationalUnitName',
'emailAddress',
'commonName',
'subjectAltNames']
else:
return []
admin.site.register(DistinguishedName, X509_pki_DistinguishedNameAdmin)
class X509_pki_CertificateAdmin(admin.ModelAdmin):
search_fields = ['shortname', 'name']
list_display = (
'shortname',
'name',
'parent',
'type',
'dn',
'created_at',
'expires_at',
'days_valid',
'revoked_at',
'crl_distribution_url',
'ocsp_distribution_host')
form = CertificateForm
def get_readonly_fields(self, request, obj=None):
if obj: # This is the case when obj is already created i.e. it's an edit
return [
'shortname',
'name',
'parent',
'type',
'dn',
'crl_distribution_url',
'ocsp_distribution_host',
'created_at',
'expires_at',
'revoked_at']
else:
return []
admin.site.register(Certificate, X509_pki_CertificateAdmin)
| {
"repo_name": "repleo/bounca",
"path": "x509_pki/admin.py",
"copies": "1",
"size": "2053",
"license": "apache-2.0",
"hash": -6581996418660943000,
"line_mean": 27.9154929577,
"line_max": 81,
"alpha_frac": 0.5513882124,
"autogenerated": false,
"ratio": 4.250517598343685,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005782663460437422,
"num_lines": 71
} |
'''Admin interface for credit app exposes Inline for ordered credits and
registers Credit model with admin interface.
'''
from django.contrib import admin
from django.contrib.contenttypes import generic
from django.forms.widgets import HiddenInput
from django.db.models import PositiveIntegerField
from django.utils.translation import ugettext as _
from models import Credit, OrderedCredit
class OrderedCreditInline(generic.GenericTabularInline):
verbose_name = _('author or source')
verbose_name_plural = _('authors or sources')
classes = ('collapse open',)
model = OrderedCredit
raw_id_fields = ('credit',)
related_lookup_fields = {
'fk': ['credit'],
}
extra = 0
# formfield_overrides = {
# PositiveIntegerField: {'widget': HiddenInput},
# }
sortable_field_name = 'position'
class CreditAdmin(admin.ModelAdmin):
search_fields = ('first_names','last_name')
list_display = ('id', 'first_names', 'last_name', 'is_person', 'url')
list_editable = ('first_names', 'last_name', 'is_person', 'url')
list_filter = ('is_person',)
class OrderedCreditAdmin(admin.ModelAdmin):
list_display = ('id', 'content_type', 'object_id', 'content_object', 'position', 'credit')
admin.site.register(Credit, CreditAdmin)
admin.site.register(OrderedCredit, OrderedCreditAdmin) | {
"repo_name": "nathangeffen/tbonline-2",
"path": "tbonlineproject/credit/admin.py",
"copies": "1",
"size": "1367",
"license": "mit",
"hash": -7379956046245526000,
"line_mean": 31.5714285714,
"line_max": 94,
"alpha_frac": 0.6905632772,
"autogenerated": false,
"ratio": 3.96231884057971,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.515288211777971,
"avg_score": null,
"num_lines": null
} |
'''Admin interface for posts.
'''
from django.contrib import admin
from django.utils.translation import ugettext as _
from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib.flatpages.models import FlatPage
from django.contrib.comments.models import Comment, CommentFlag
from django.contrib.comments.admin import CommentsAdmin
from django import forms
from django.contrib.sites.models import Site
from sorl.thumbnail.admin import AdminImageMixin
from post.models import BasicPost, PostWithImage, PostWithSlideshow, \
PostWithSimpleImage, PostWithEmbeddedObject, \
SubmittedArticle, EditorChoice
from archive.admin import TaggedItemInline
from credit.admin import OrderedCreditInline
from relatedcontent.admin import RelatedContentInline
from enhancedtext.admin import enhancedtextcss, enhancedtextjs
post_fieldsets = (
(_('Title'), {
'classes' : ['collapse open'],
'fields': ('title', 'subtitle','slug','date_published'),
}),
(_('Content'), {
'classes' : ['collapse open',],
'fields': ('body',)
}),
(_('Display features'), {
'classes' : ['collapse open',],
'fields': ('homepage','sticky', 'category', 'allow_comments', 'copyright')
}),
(_('Teaser. introduction and pullout text'), {
'classes' : ['collapse closed',],
'fields': ('teaser','introduction', 'pullout_text',)
}),
(_('HTML templates'), {
'classes' : ['collapse closed',],
'fields': (('detail_post_template','list_post_template',),
('detail_post_css_classes','list_post_css_classes',))
}),
(_('Sites on which this post is published'), {
'classes' : ['collapse closed',],
'fields' : ('sites',)
})
)
class BasicPostAdmin(admin.ModelAdmin):
search_fields = ('title', 'teaser', 'body')
list_display = ('render_admin_url', 'title', 'describe_for_admin',
'date_published', 'category', 'homepage','is_published',
'date_added', 'last_modified')
list_editable = ('title', 'date_published','category', 'homepage', )
list_filter = ('date_published',)
date_hierarchy = 'date_published'
prepopulated_fields = {"slug": ("title",)}
inlines = [OrderedCreditInline, TaggedItemInline, RelatedContentInline]
ordering = ('-last_modified',)
fieldsets = post_fieldsets
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == 'sites':
kwargs["initial"] = [Site.objects.get_current()]
return super(BasicPostAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
class Media:
css = enhancedtextcss
js = enhancedtextjs
class PostWithSimpleImageAdmin(AdminImageMixin, BasicPostAdmin):
fieldsets = post_fieldsets[0:3] + \
((_('Image'), {
'classes' : ['collapse open',],
'fields': ('image', 'caption', 'url',)
}),) + \
post_fieldsets[3:]
class PostWithImageAdmin(BasicPostAdmin):
#list_display = ('id', 'title', 'image_thumbnail', 'date_published', 'category', 'homepage','is_published', 'date_added', 'last_modified')
raw_id_fields = ['image',]
related_lookup_fields = {
'fk': ['image'],
}
fieldsets = post_fieldsets[0:3] + \
((_('Image'), {
'classes' : ['collapse open',],
'fields': ('image',)
}),) + \
post_fieldsets[3:]
class PostWithSlideshowAdmin(BasicPostAdmin):
#list_display = ('id', 'title', 'slideshow_thumbnail', 'date_published', 'category', 'homepage','is_published', 'date_added', 'last_modified')
raw_id_fields = ['gallery',]
related_lookup_fields = {
'fk': ['gallery'],
}
fieldsets = post_fieldsets[0:3] + \
((_('Gallery to use for slideshow'), {
'classes' : ['collapse open',],
'fields': ('gallery', 'slideshow_options')
}),) + \
post_fieldsets[3:]
class PostWithEmbeddedObjectAdmin(BasicPostAdmin):
fieldsets = post_fieldsets[0:3] + \
((_('Embedded object'), {
'classes' : ['collapse open',],
'fields': ('list_post_embedded_html', 'detail_post_embedded_html')
}),) + \
post_fieldsets[3:]
class FlatPageForm(forms.ModelForm):
model = FlatPage
class Media:
js = [
'grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js',
'grappelli/tinymce_setup/tinymce_setup.js',
]
class CustomFlatPageAdmin(FlatPageAdmin):
form = FlatPageForm
class EditorsChoiceInline(admin.StackedInline):
model = EditorChoice
max_num = 1
fields = ['editors_choice']
can_delete = False
class CustomCommentAdmin(CommentsAdmin):
list_display = ('id', 'name', 'content_type', 'object_pk', 'ip_address', 'submit_date', 'is_public', 'is_removed')
inlines = [EditorsChoiceInline]
admin.site.register(BasicPost, BasicPostAdmin)
admin.site.register(PostWithSimpleImage, PostWithSimpleImageAdmin)
admin.site.register(PostWithImage, PostWithImageAdmin)
admin.site.register(PostWithSlideshow, PostWithSlideshowAdmin)
admin.site.register(PostWithEmbeddedObject, PostWithEmbeddedObjectAdmin)
admin.site.register(SubmittedArticle)
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, CustomFlatPageAdmin)
admin.site.unregister(Comment)
admin.site.register(Comment, CustomCommentAdmin)
admin.site.register(CommentFlag)
| {
"repo_name": "nathangeffen/tbonline-old",
"path": "tbonlineproject/post/admin.py",
"copies": "1",
"size": "5686",
"license": "mit",
"hash": 5406693430041175000,
"line_mean": 32.0581395349,
"line_max": 146,
"alpha_frac": 0.6160745691,
"autogenerated": false,
"ratio": 3.8601493550577053,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9863404125691342,
"avg_score": 0.02256395969327272,
"num_lines": 172
} |
'''Admin interface for stories.
'''
from django.contrib import admin
from django.contrib.contenttypes import generic
from django.utils.translation import ugettext as _
from django.forms.widgets import HiddenInput
from django.db.models import PositiveIntegerField
from tagging.models import TaggedItem
from post.models import BasicPost
from post.admin import TaggedItemInline
from credit.admin import OrderedCreditInline
from models import Story
class PostInline(admin.TabularInline):
classes = ('collapse open')
model = Story.posts.through
raw_id_fields = ['post',]
related_lookup_fields = {
'fk': ['post'],
}
extra = 0
formfield_overrides = {
PositiveIntegerField: {'widget': HiddenInput},
}
sortable_field_name = 'position'
class StoryAdmin(admin.ModelAdmin):
search_fields = ('title', 'description',)
list_display = ('id', 'title', 'date_published', 'date_added', 'last_modified')
list_editable = ('title', 'date_published')
list_filter = ('date_published',)
date_hierarchy = 'date_published'
prepopulated_fields = {"slug": ("title",)}
inlines = [OrderedCreditInline, PostInline, TaggedItemInline]
class Media:
js = [
'grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js',
'grappelli/tinymce_setup/tinymce_setup.js',
]
admin.site.register(Story, StoryAdmin)
| {
"repo_name": "nathangeffen/tbonline-2",
"path": "tbonlineproject/story/admin.py",
"copies": "2",
"size": "1418",
"license": "mit",
"hash": -7565679701377930000,
"line_mean": 28.5416666667,
"line_max": 83,
"alpha_frac": 0.6798307475,
"autogenerated": false,
"ratio": 3.8221024258760106,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.036443706756206756,
"num_lines": 48
} |
'''Admin interface registers Image model with admin.site.
'''
from django.contrib import admin
from django.contrib.contenttypes import generic
from django.forms.widgets import HiddenInput
from django.db.models import PositiveIntegerField
from credit.admin import OrderedCreditInline
from gallery.models import Gallery, Image
from archive.admin import TaggedItemInline
class ImageInline(admin.TabularInline):
classes = ('collapse open')
model = Gallery.images.through
extra = 0
raw_id_fields = ('image',)
formfield_overrides = {
PositiveIntegerField: {'widget': HiddenInput},
}
sortable_field_name = 'position'
class GalleryAdmin(admin.ModelAdmin):
search_fields = ('title','description',)
list_display = ('id', 'title',)
list_editable = ('title',)
inlines = [TaggedItemInline, ImageInline,]
class Media:
js = [
'grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js',
'grappelli/tinymce_setup/tinymce_setup.js',
]
class ImageAdmin(admin.ModelAdmin):
search_fields = ('title','caption','description')
list_display = ('id', 'title', 'image_thumbnail','file','date_added', 'last_modified')
list_editable = ('title',)
prepopulated_fields = {"slug": ("title",)}
inlines = [TaggedItemInline, OrderedCreditInline, ]
class Media:
js = [
'grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js',
'grappelli/tinymce_setup/tinymce_setup.js',
]
admin.site.register(Image, ImageAdmin)
admin.site.register(Gallery, GalleryAdmin)
| {
"repo_name": "nathangeffen/tbonline-2",
"path": "tbonlineproject/gallery/admin.py",
"copies": "2",
"size": "1624",
"license": "mit",
"hash": 922478386968745700,
"line_mean": 28,
"line_max": 90,
"alpha_frac": 0.6594827586,
"autogenerated": false,
"ratio": 3.7855477855477857,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.02188190501850396,
"num_lines": 56
} |
"""Administration form for avatar settings."""
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext, ugettext_lazy as _
from djblets.siteconfig.forms import SiteSettingsForm
from reviewboard.avatars import avatar_services
class AvatarServicesForm(SiteSettingsForm):
"""A form for managing avatar services."""
avatars_enabled = forms.BooleanField(
label=_('Enable avatars'),
help_text=_('We recommend enabling avatars on all installations, '
'and enabling or disabling the services you prefer.'),
required=False)
enabled_services = forms.MultipleChoiceField(
label=_('Enabled services'),
required=False,
help_text=_("If no services are enabled, a fallback avatar will be "
"shown that displays the user's initials."),
widget=forms.CheckboxSelectMultiple())
default_service = forms.ChoiceField(
label=_('Default service'),
help_text=_('The avatar service to be used by default for users who '
'do not have an avatar service configured. This must be '
'one of the enabled avatar services below.'),
required=False
)
def __init__(self, *args, **kwargs):
"""Initialize the settings form.
This will populate the choices and initial values for the form fields
based on the current avatar configuration.
Args:
*args (tuple):
Additional positional arguments for the parent class.
**kwargs (dict):
Additional keyword arguments for the parent class.
"""
super(AvatarServicesForm, self).__init__(*args, **kwargs)
default_choices = [('none', 'None')]
enable_choices = []
for service in avatar_services:
default_choices.append((service.avatar_service_id, service.name))
enable_choices.append((service.avatar_service_id, service.name))
default_service_field = self.fields['default_service']
enabled_services_field = self.fields['enabled_services']
default_service_field.choices = default_choices
enabled_services_field.choices = enable_choices
enabled_services_field.initial = [
service.avatar_service_id
for service in avatar_services.enabled_services
]
default_service = avatar_services.default_service
if avatar_services.default_service is not None:
default_service_field.initial = default_service.avatar_service_id
def clean_enabled_services(self):
"""Clean and validate the enabled_services field.
Raises:
django.core.exceptions.ValidationError:
Raised if an unknown service is attempted to be enabled.
"""
for service_id in self.cleaned_data['enabled_services']:
if not avatar_services.has_service(service_id):
raise ValidationError(
ugettext('"%s" is not an available avatar service.')
% service_id)
return self.cleaned_data['enabled_services']
def clean(self):
"""Clean and validate the form.
This will clean the form, handling any fields that need cleaned
that depend on the cleaned data of other fields.
Raises:
django.core.exceptions.ValidationError:
Raised if an unknown service or disabled service is set to be
the default.
"""
cleaned_data = super(AvatarServicesForm, self).clean()
enabled_services = set(cleaned_data['enabled_services'])
service_id = cleaned_data['default_service']
if service_id == 'none':
default_service = None
else:
if not avatar_services.has_service(service_id):
raise ValidationError(
ugettext('"%s" is not an available avatar service.')
% service_id)
elif service_id not in enabled_services:
raise ValidationError(
ugettext('The "%s" avatar service is disabled and cannot '
'be set.')
% service_id)
default_service = avatar_services.get('avatar_service_id',
service_id)
cleaned_data['default_service'] = default_service
return cleaned_data
def save(self):
"""Save the enabled services and default service to the database."""
avatar_services.set_enabled_services(
[
avatar_services.get('avatar_service_id', service_id)
for service_id in self.cleaned_data['enabled_services']
],
save=False)
avatar_services.set_default_service(
self.cleaned_data['default_service'],
save=False)
avatar_services.avatars_enabled = self.cleaned_data['avatars_enabled']
avatar_services.save()
class Meta:
title = _('Avatar Settings')
fieldsets = (
{
'fields': (
'avatars_enabled',
'enabled_services',
'default_service',
),
},
)
| {
"repo_name": "chipx86/reviewboard",
"path": "reviewboard/admin/forms/avatar_settings.py",
"copies": "2",
"size": "5409",
"license": "mit",
"hash": 6387389274225873000,
"line_mean": 34.821192053,
"line_max": 78,
"alpha_frac": 0.5923460899,
"autogenerated": false,
"ratio": 4.962385321100918,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6554731411000918,
"avg_score": null,
"num_lines": null
} |
"""Administration form for diff viewer settings."""
from __future__ import unicode_literals
import re
from django import forms
from django.utils.translation import ugettext_lazy as _
from djblets.siteconfig.forms import SiteSettingsForm
class DiffSettingsForm(SiteSettingsForm):
"""Diff settings for Review Board."""
diffviewer_syntax_highlighting = forms.BooleanField(
label=_('Show syntax highlighting'),
required=False)
diffviewer_syntax_highlighting_threshold = forms.IntegerField(
label=_('Syntax highlighting threshold'),
help_text=_('Files with lines greater than this number will not have '
'syntax highlighting. Enter 0 for no limit.'),
required=False,
widget=forms.TextInput(attrs={'size': '5'}))
diffviewer_show_trailing_whitespace = forms.BooleanField(
label=_('Show trailing whitespace'),
help_text=_('Show excess trailing whitespace as red blocks. This '
'helps to visualize when a text editor added unwanted '
'whitespace to the end of a line.'),
required=False)
include_space_patterns = forms.CharField(
label=_('Show all whitespace for'),
required=False,
help_text=_('A comma-separated list of file patterns for which all '
'whitespace changes should be shown. '
'(e.g., "*.py, *.txt")'),
widget=forms.TextInput(attrs={'size': '60'}))
diffviewer_context_num_lines = forms.IntegerField(
label=_('Lines of Context'),
help_text=_('The number of unchanged lines shown above and below '
'changed lines.'),
initial=5,
widget=forms.TextInput(attrs={'size': '5'}))
diffviewer_paginate_by = forms.IntegerField(
label=_('Paginate by'),
help_text=_('The number of files to display per page in the diff '
'viewer.'),
initial=20,
widget=forms.TextInput(attrs={'size': '5'}))
diffviewer_paginate_orphans = forms.IntegerField(
label=_('Paginate orphans'),
help_text=_('The number of extra files required before adding another '
'page to the diff viewer.'),
initial=10,
widget=forms.TextInput(attrs={'size': '5'}))
diffviewer_max_diff_size = forms.IntegerField(
label=_('Max diff size (bytes)'),
help_text=_('The maximum size (in bytes) for any given diff. Enter 0 '
'to disable size restrictions.'),
widget=forms.TextInput(attrs={'size': '15'}))
def load(self):
"""Load settings from the form.
This will populate initial fields based on the site configuration.
"""
super(DiffSettingsForm, self).load()
self.fields['include_space_patterns'].initial = \
', '.join(self.siteconfig.get('diffviewer_include_space_patterns'))
def save(self):
"""Save the form.
This will write the new configuration to the database.
"""
self.siteconfig.set(
'diffviewer_include_space_patterns',
re.split(r',\s*', self.cleaned_data['include_space_patterns']))
super(DiffSettingsForm, self).save()
class Meta:
title = _('Diff Viewer Settings')
save_blacklist = ('include_space_patterns',)
fieldsets = (
{
'classes': ('wide',),
'fields': ('diffviewer_syntax_highlighting',
'diffviewer_syntax_highlighting_threshold',
'diffviewer_show_trailing_whitespace',
'include_space_patterns'),
},
{
'title': _('Advanced'),
'description': _(
'These are advanced settings that control the behavior '
'and display of the diff viewer. In general, these '
'settings do not need to be changed.'
),
'classes': ('wide',),
'fields': ('diffviewer_max_diff_size',
'diffviewer_context_num_lines',
'diffviewer_paginate_by',
'diffviewer_paginate_orphans')
}
)
| {
"repo_name": "chipx86/reviewboard",
"path": "reviewboard/admin/forms/diff_settings.py",
"copies": "2",
"size": "4312",
"license": "mit",
"hash": 186954210815068000,
"line_mean": 37.1592920354,
"line_max": 79,
"alpha_frac": 0.5693413729,
"autogenerated": false,
"ratio": 4.769911504424779,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6339252877324778,
"avg_score": null,
"num_lines": null
} |
"""Administration form for logging settings."""
from __future__ import unicode_literals
import os
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import (ugettext,
ugettext_lazy as _)
from djblets.siteconfig.forms import SiteSettingsForm
from reviewboard.admin.siteconfig import load_site_config
class LoggingSettingsForm(SiteSettingsForm):
"""Logging settings for Review Board."""
LOG_LEVELS = (
('DEBUG', _('Debug')),
('INFO', _('Info')),
('WARNING', _('Warning')),
('ERROR', _('Error')),
('CRITICAL', _('Critical')),
)
logging_enabled = forms.BooleanField(
label=_('Enable logging'),
help_text=_("Enables logging of Review Board operations. This is in "
"addition to your web server's logging and does not log "
"all page visits."),
required=False)
logging_directory = forms.CharField(
label=_('Log directory'),
help_text=_('The directory where log files will be stored. This must '
'be writable by the web server.'),
required=False,
widget=forms.TextInput(attrs={'size': '60'}))
logging_level = forms.ChoiceField(
label=_('Log level'),
help_text=_('Indicates the logging threshold. Please note that this '
'may increase the size of the log files if a low '
'threshold is selected.'),
required=False,
choices=LOG_LEVELS)
logging_allow_profiling = forms.BooleanField(
label=_('Allow code profiling'),
help_text=_('Logs the time spent on certain operations. This is '
'useful for debugging but may greatly increase the '
'size of log files.'),
required=False)
def clean_logging_directory(self):
"""Validate that the logging_directory path is valid.
This checks that the directory path exists, and is writable by the web
server. If valid, the directory with whitespace stripped will be
returned.
Returns:
unicode:
The logging directory, with whitespace stripped.
Raises:
django.core.exceptions.ValidationError:
The directory was not valid.
"""
logging_dir = self.cleaned_data['logging_directory'].strip()
if not os.path.exists(logging_dir):
raise ValidationError(ugettext('This path does not exist.'))
if not os.path.isdir(logging_dir):
raise ValidationError(ugettext('This is not a directory.'))
if not os.access(logging_dir, os.W_OK):
raise ValidationError(
ugettext('This path is not writable by the web server.'))
return logging_dir
def save(self):
"""Save the form.
This will write the new configuration to the database. It will then
force a site configuration reload.
"""
super(LoggingSettingsForm, self).save()
# Reload any important changes into the Django settings.
load_site_config()
class Meta:
title = _('Logging Settings')
fieldsets = (
{
'classes': ('wide',),
'fields': ('logging_enabled',
'logging_directory',
'logging_level'),
},
{
'title': _('Advanced'),
'classes': ('wide',),
'fields': ('logging_allow_profiling',),
}
)
| {
"repo_name": "reviewboard/reviewboard",
"path": "reviewboard/admin/forms/logging_settings.py",
"copies": "2",
"size": "3651",
"license": "mit",
"hash": -5763952761813097000,
"line_mean": 32.1909090909,
"line_max": 78,
"alpha_frac": 0.5702547247,
"autogenerated": false,
"ratio": 4.960597826086956,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6530852550786956,
"avg_score": null,
"num_lines": null
} |
"""Administration form for privacy settings."""
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from djblets.avatars.registry import AvatarServiceRegistry
from djblets.siteconfig.forms import SiteSettingsForm
class PrivacySettingsForm(SiteSettingsForm):
"""Site-wide user privacy settings for Review Board."""
terms_of_service_url = forms.URLField(
label=_('Terms of service URL'),
required=False,
help_text=_('URL to your terms of service. This will be displayed on '
'the My Account page and during login and registration.'),
widget=forms.widgets.URLInput(attrs={
'size': 80,
}))
privacy_policy_url = forms.URLField(
label=_('Privacy policy URL'),
required=False,
help_text=_('URL to your privacy policy. This will be displayed on '
'the My Account page and during login and registration.'),
widget=forms.widgets.URLInput(attrs={
'size': 80,
}))
privacy_info_html = forms.CharField(
label=_('Privacy information'),
required=False,
help_text=_('A description of the privacy guarantees for users on '
'this server. This will be displayed on the My Account '
'-> Your Privacy page. HTML is allowed.'),
widget=forms.widgets.Textarea(attrs={
'cols': 60,
}))
privacy_enable_user_consent = forms.BooleanField(
label=_('Require consent for usage of personal information'),
required=False,
help_text=_('Require consent from users when using their personally '
'identifiable information (usernames, e-mail addresses, '
'etc.) for when talking to third-party services, like '
'Gravatar. This is required for EU GDPR compliance.'))
def save(self):
"""Save the privacy settings form.
This will write the new configuration to the database.
"""
self.siteconfig.set(AvatarServiceRegistry.ENABLE_CONSENT_CHECKS,
self.cleaned_data['privacy_enable_user_consent'])
super(PrivacySettingsForm, self).save()
class Meta:
title = _('User Privacy Settings')
fieldsets = (
{
'classes': ('wide',),
'fields': (
'terms_of_service_url',
'privacy_policy_url',
'privacy_info_html',
'privacy_enable_user_consent',
),
},
)
| {
"repo_name": "chipx86/reviewboard",
"path": "reviewboard/admin/forms/privacy_settings.py",
"copies": "2",
"size": "2667",
"license": "mit",
"hash": -4533156802189475300,
"line_mean": 36.0416666667,
"line_max": 78,
"alpha_frac": 0.5856767904,
"autogenerated": false,
"ratio": 4.535714285714286,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 72
} |
"""Administration form for SSH settings."""
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import (ugettext,
ugettext_lazy as _)
from reviewboard.ssh.client import SSHClient
class SSHSettingsForm(forms.Form):
"""SSH key settings for Review Board."""
keyfile = forms.FileField(
label=_('Key file'),
required=False,
widget=forms.FileInput(attrs={'size': '35'}))
# These will ultimately map to the submit buttons.
generate_key = forms.BooleanField(
required=False,
initial=True,
widget=forms.HiddenInput)
delete_key = forms.BooleanField(
required=False,
initial=True,
widget=forms.HiddenInput)
upload_key = forms.BooleanField(
required=False,
initial=True,
widget=forms.HiddenInput)
def clean(self):
"""Clean the form data.
This will perform an additional validation check to see if the user
requested to upload a key, but failed to provide a key file.
Returns:
dict:
The resulting cleaned data for the form.
"""
cleaned_data = super(SSHSettingsForm, self).clean()
if cleaned_data.get('upload_key') and not cleaned_data.get('keyfile'):
self.add_error(
'keyfile',
ValidationError(
self.fields['keyfile'].error_messages['required'],
code='required'))
return cleaned_data
def create(self, files):
"""Generate or import an SSH key.
This will generate a new SSH key if :py:attr:`generate_key` was set
to ``True``. Otherwise, a if :py:attr:`keyfile` was provided, its
corresponding file upload will be used as the new key.
In either case, the key will be validated, and if validation fails,
an error will be set for the appropriate field.
Args:
files (django.utils.datastructures.MultiValueDict):
The files uploaded in the request. This may contain a
``keyfile`` entry representing a key to upload.
Raises:
Exception:
There was an error generating or importing a key. The form
will have a suitable error for the field triggering the
error.
"""
if self.cleaned_data['generate_key']:
try:
SSHClient().generate_user_key()
except IOError as e:
self.add_error(
'generate_key',
ugettext('Unable to write SSH key file: %s') % e)
raise
except Exception as e:
self.add_error(
'generate_key',
ugettext('Error generating SSH key: %s') % e)
raise
elif self.cleaned_data['upload_key']:
try:
SSHClient().import_user_key(files['keyfile'])
except IOError as e:
self.add_error(
'keyfile',
ugettext('Unable to write SSH key file: %s') % e)
raise
except Exception as e:
self.add_error(
'keyfile',
ugettext('Error uploading SSH key: %s') % e)
raise
def did_request_delete(self):
"""Return whether the user has requested to delete the user SSH key.
This checks that :py:attr:`delete_key`` was set in the request.
Returns:
``True`` if the user requested to delete the key. ``False`` if
they did not.
"""
return self.cleaned_data.get('delete_key', False)
def delete(self):
"""Delete the configured SSH user key.
This will only delete the key if :py:attr:`delete_key` was set.
Raises:
Exception:
There was an unexpected error deleting the key. A validation
error will be set for the ``delete_key`` field.
"""
if self.did_request_delete():
try:
SSHClient().delete_user_key()
except Exception as e:
self.add_error(
'delete_key',
ugettext('Unable to delete SSH key file: %s') % e)
raise
class Meta:
title = _('SSH Settings')
| {
"repo_name": "chipx86/reviewboard",
"path": "reviewboard/admin/forms/ssh_settings.py",
"copies": "2",
"size": "4514",
"license": "mit",
"hash": -2873328182912856000,
"line_mean": 32.437037037,
"line_max": 78,
"alpha_frac": 0.5478511298,
"autogenerated": false,
"ratio": 4.843347639484978,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 135
} |
"""Administration form for support settings."""
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from djblets.siteconfig.forms import SiteSettingsForm
from reviewboard.admin.support import get_install_key
class SupportSettingsForm(SiteSettingsForm):
"""Support settings for Review Board."""
install_key = forms.CharField(
label=_('Install key'),
help_text=_('The installation key to provide when purchasing a '
'support contract.'),
required=False,
widget=forms.TextInput(attrs={
'size': '80',
'readonly': 'readonly'
}))
support_url = forms.CharField(
label=_('Custom Support URL'),
help_text=_("The location of your organization's own Review Board "
"support page. Leave blank to use the default support "
"page."),
required=False,
widget=forms.TextInput(attrs={'size': '80'}))
send_support_usage_stats = forms.BooleanField(
label=_('Send support-related usage statistics'),
help_text=_('Basic usage information will be sent to us at times to '
'help with some support issues and to provide a more '
'personalized support page for your users. '
'<i>No information is ever given to a third party.</i>'),
required=False)
def load(self):
"""Load settings from the form.
This will populate initial fields based on the site configuration
and the current install key.
"""
super(SupportSettingsForm, self).load()
self.fields['install_key'].initial = get_install_key()
class Meta:
title = _('Support Settings')
save_blacklist = ('install_key',)
fieldsets = ({
'classes': ('wide',),
'description': (
'<p>'
'For fast one-on-one support, plus other benefits, '
'purchase a <a href="https://www.reviewboard.org/support/">'
'support contract</a>.'
'</p>'
'<p>'
'You can also customize where your users will go for '
'support by changing the Custom Support URL below. If left '
'blank, they will be taken to our support channel.'
'</p>'),
'fields': ('install_key', 'support_url',
'send_support_usage_stats'),
},)
| {
"repo_name": "chipx86/reviewboard",
"path": "reviewboard/admin/forms/support_settings.py",
"copies": "2",
"size": "2547",
"license": "mit",
"hash": -8627610399341852000,
"line_mean": 35.9130434783,
"line_max": 77,
"alpha_frac": 0.5696898312,
"autogenerated": false,
"ratio": 4.760747663551402,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 69
} |
"""Administration related routes"""
import json
import os
import re
from typing import Dict, Union, List
from botocore.exceptions import EndpointConnectionError
from flask import jsonify, request, render_template, send_file, url_for, \
flash, redirect, Response
from flask_user import login_required
from werkzeug.datastructures import ImmutableDict
from werkzeug.utils import secure_filename
from pma_api.error import ExistingDatasetError, PmaApiTaskDenialError
from pma_api.routes import root
@root.route('/admin', methods=['GET', 'POST'])
@login_required
def admin_route():
"""Route to admin portal for uploading and managing datasets.
.. :quickref: admin; Route to admin portal for uploading and managing
datasets.
Notes:
- flash() uses Bootstrap 4.0 alert categories,
https://getbootstrap.com/docs/4.0/components/alerts/
# GET REQUESTS
Args: n/a
Query Args: n/a
Returns:
flask.render_template(): A rendered HTML template.
Examples: n/a
# POST REQUESTS
Receives a file uploaded, which is of the type:
ImmutableMultiDict([('file', <FileStorage: 'FILENAME' ('FILETYPE')>)])
"""
from pma_api.manage.db_mgmt import list_cloud_datasets, download_dataset, \
delete_dataset
from pma_api.models import ApiMetadata, Task
from pma_api.task_utils import upload_dataset
# upload
if request.method == 'POST':
try:
file = request.files['file']
filename = secure_filename(file.filename)
file_url: str = upload_dataset(filename=filename, file=file)
return jsonify({'success': bool(file_url)})
except ExistingDatasetError as err:
return jsonify({'success': False, 'message': str(err)})
except Exception as err:
msg = 'An unexpected error occurred.\n' + \
err.__class__.__name__ + ': ' + str(err)
return jsonify({'success': False, 'message': msg})
elif request.method == 'GET':
if request.args:
args = request.args.to_dict()
if 'download' in args:
# TODO: Delete tempfile after sending
tempfile_path: str = download_dataset(
version_number=int(args['download']))
return send_file(
filename_or_fp=tempfile_path,
attachment_filename=os.path.basename(tempfile_path),
as_attachment=True)
if 'delete' in args:
try:
delete_dataset(version_number=int(args['delete']))
except FileNotFoundError as err:
msg = 'FileNotFoundError: ' + str(err)
flash(message=msg, category='danger')
return redirect(url_for('root.admin_route'))
active_api_dataset: Dict = \
ApiMetadata.get_current_api_data(as_json=True)
# TODO 2019.04.18-jef: active_dataset_version seems messy / breakable
active_dataset_version: str = \
re.findall(r'-v[0-9]*', active_api_dataset['name'])[0]\
.replace('-v', '')
present_task_list: List[str] = Task.get_present_tasks()
task_id_url_map: Dict[str, str] = {
task_id: url_for('root.taskstatus', task_id=task_id)
for task_id in present_task_list}
present_tasks: str = json.dumps(task_id_url_map)
try:
datasets: List[Dict[str, str]] = list_cloud_datasets()
except EndpointConnectionError:
msg = 'Connection Error: Unable to connect to data storage ' \
'server to retrieve list of datasets.'
datasets: List[Dict[str, str]] = []
flash(message=msg, category='danger')
return render_template(
'admin.html',
datasets=datasets, # List[Dict[str, str]]
active_dataset_version=active_dataset_version, # int
active_tasks=present_tasks, # str(json({id: url}))
this_env=os.getenv('ENV_NAME', 'development')) # str
# @login_required # Transfer creds from sending to receiving server?
@root.route('/activate_dataset', methods=['POST'])
def activate_dataset() -> jsonify:
"""Activate dataset to the this server.
Params:
dataset_name (str): Name of dataset.
Returns:
json.jsonify: Results.
"""
from pma_api.tasks import activate_dataset as activate
from pma_api.task_utils import start_task
try:
form: ImmutableDict = request.form # Browser request
if not form:
form: Dict = request.get_json(force=True) # CLI request
python_var, js_var = 'datasetID', 'dataset_ID'
dataset_id: str = form[js_var] if js_var in form else form[python_var]
task_id: str = \
start_task(func=activate, kwarg_dict={'dataset_id': dataset_id})
host_url: str = request.host_url # localhost, pma-api.pma2020.org, etc
host_url: str = host_url[:-1] # remove trailing / character
url_path: str = url_for('root.taskstatus', task_id=task_id) # /status
url: str = host_url + url_path
response_http_code: int = 202 # Accepted
response_data: Response = jsonify({})
response_headers: Dict[str, str] = {'Content-Location': url}
except PmaApiTaskDenialError as err:
response_http_code: int = 403 # Forbidden
response_data: Response = jsonify({})
response_headers: Dict[str, str] = {'detail': str(err)}
return response_data, response_http_code, response_headers
# @login_required
# Resulting in error:
# File "flask_user/user_mixin.py", line 52, in get_user_by_token
# user_password = '' if user_manager.USER_ENABLE_AUTH0 else user.password[-8:]
# AttributeError: 'NoneType' object has no attribute 'password'
@root.route('/status/<task_id>', methods=['GET'])
def taskstatus(task_id: str) -> jsonify:
"""Get task status
TODOs
1. Low priority. Get correct exception types or find some other
way to do this better. Annoyingly, sometimes info isn't a dict, and
sometimes doesn't have key 'args', and I think there are even more
edge cases.
Args:
task_id (str): ID with which to look up task in task queue
Returns:
jsonify: Response object
"""
from pma_api.task_utils import get_task_status
report: Dict[str, Union[str, int, float]] = \
get_task_status(task_id=task_id, return_format='dict')
report['url']: str = request.url
return jsonify(report)
# TODO 2019.04.15-jef: This feature would be ideal to add back. This would
# allow the user to remotely activate dataset on another server (e.g. prod
# from staging).
# @root.route('/activate_dataset_request', methods=['POST'])
# @login_required
# def activate_dataset_request() -> jsonify:
# """Activate dataset to be uploaded and actively used on target server.
#
# Params:
# dataset_name (str): Name of dataset to send.
# destination_host_url (str): URL of server to apply dataset.
#
# Returns:
# json.jsonify: Results.
# """
# from pma_api.tasks import activate_dataset_request
#
# dataset_id: str = request.form['datasetID']
# destination_env: str = request.form['destinationEnv']
# # destination: str = \
# # os.getenv('PRODUCTION_URL') \
# # if destination_env == 'production' else \
# # os.getenv('STAGING_URL') \
# # if destination_env == 'staging' else \
# # LOCAL_DEVELOPMENT_URL
#
# # TO-DO: upload dataset if needed
# dataset_needed = False
# dataset: FileStorage = None if dataset_needed else None
# #
#
# # TO-DO: If using this code again, use start_task() function, or make
# # sure to otherwise specify the correct queue
# # TO-DO - yield: init_wb, celery tasks and routes
# task = activate_dataset_request.apply_async(kwargs={
# 'dataset_id': dataset_id,
# # 'destination_host_url': destination,
# 'dataset': dataset})
#
# response_data = jsonify({})
# response_http_code = 202 # Accepted
# response_headers = \
# {'Content-Location': url_for('root.taskstatus', task_id=task.id)}
#
# return response_data, response_http_code, response_headers
| {
"repo_name": "joeflack4/pma-api",
"path": "pma_api/routes/administration.py",
"copies": "1",
"size": "8338",
"license": "mit",
"hash": -3573450050307872000,
"line_mean": 35.8938053097,
"line_max": 79,
"alpha_frac": 0.6184936436,
"autogenerated": false,
"ratio": 3.7865576748410534,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4905051318441053,
"avg_score": null,
"num_lines": null
} |
"""administration URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.i18n import i18n_patterns
from views import home, home_files
urlpatterns = [
url(r'^(?P<filename>(robots.txt)|(humans.txt))$',
home_files,
name='home-files')
]
urlpatterns += i18n_patterns(
url(r'^admin/', include(admin.site.urls)),
url(r'^$', home, name='home'),
url(r'^account/', include('allauth.urls')),
url(r'^account/', include('accounts.urls')),
)
| {
"repo_name": "GriMel/TB_Tutor",
"path": "administration/urls.py",
"copies": "1",
"size": "1113",
"license": "mit",
"hash": 6093445890247702000,
"line_mean": 33.78125,
"line_max": 77,
"alpha_frac": 0.6783468104,
"autogenerated": false,
"ratio": 3.3727272727272726,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4551074083127273,
"avg_score": null,
"num_lines": null
} |
"""Administrative commands."""
from code import InteractiveConsole
from contextlib import redirect_stdout, redirect_stderr
from inspect import getdoc, _empty
from sqlalchemy import Boolean, Enum, inspect
from .commands import command, LocationTypes
from ..db import (
Player, BuildingType, UnitType, AttackType, FeatureType, Base,
BuildingRecruit, UnitActions, SkillTypes, SkillType
)
from ..menus import Menu, YesNoMenu
from ..options import options
from ..util import english_list
consoles = {}
class Console(InteractiveConsole):
"""A console with updated push and write methods."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for cls in Base.classes():
self.locals[cls.__name__] = cls
self.locals['options'] = options
self.locals['Base'] = Base
self.locals['UnitActions'] = UnitActions
self.locals['SkillTypes'] = SkillTypes
def write(self, string):
"""Send the provided string to self.player.message."""
self.player.message(string)
def push(self, con, player, location, entry_point, code):
"""Update self.locals, then run the code."""
self.player = player
kwargs = con.get_default_kwargs(player, location, entry_point)
self.locals.update(**kwargs, console=self)
res = super().push(code)
for name in kwargs:
del self.locals[name]
self.player = None
return res
@command(location_type=LocationTypes.any, admin=True)
def disconnect(con, command_name, player, args, id, response=None):
"""Disconnect another player."""
p = Player.get(id)
if p is None:
con.message('Invalid ID.')
elif response is None:
m = YesNoMenu(
f'Are you sure you want to disconnect {p}?', command_name,
args=args
)
m.send(con)
elif response:
if not p.connected:
con.message('They are already disconnected.')
else:
p.message(f'You have been booted off the server by {player}.')
p.disconnect()
else:
con.message('Cancelled.')
@command(location_type=LocationTypes.any, admin=True)
def delete_player(con, command_name, player, args, id, response=None):
"""Delete another player."""
p = Player.get(id)
if p is None:
con.message('Invalid ID.')
elif response is None:
m = YesNoMenu(
f'Are you sure you want to delete {p}?', command_name, args=args
)
m.send(con)
elif response:
p.message(f'You have been deleted by {player}.')
p.disconnect()
p.delete()
player.message('Done.')
else:
player.message('Cancelled.')
@command(location_type=LocationTypes.any, admin=True)
def make_admin(player, id):
"""Make another player an administrator."""
p = Player.get(id)
if p is None:
player.message('Invalid ID.')
else:
p.admin = True
player.message(f'{p} is now an admin.')
@command(location_type=LocationTypes.any, admin=True)
def revoke_admin(player, id):
"""Revoke admin privileges for another player."""
p = Player.get(id)
if p is None:
player.message('Invalid ID.')
else:
p.admin = False
player.message(f'{p} is no longer an admin.')
@command(location_type=LocationTypes.any, admin=True, hotkey='backspace')
def python(command_name, con, player, location, entry_point, text=None):
"""Run some code."""
if text is None:
con.text('Code', command_name, value=player.code)
else:
player.code = text
if player.id not in consoles:
consoles[player.id] = Console()
c = consoles[player.id]
with redirect_stdout(c), redirect_stderr(c):
res = c.push(con, player, location, entry_point, text)
if res:
consoles[player.id] = c
@command(location_type=LocationTypes.any, hotkey='m', admin=True)
def make_menu(con):
"""Add / remove types."""
m = Menu('Add / Remove Types')
for cls in (UnitType, BuildingType, AttackType, FeatureType):
m.add_label(cls.__tablename__.replace('_', ' ').title())
for action in ('add', 'edit', 'remove'):
m.add_item(
action.title(), f'{action}_type',
args=dict(class_name=cls.__name__)
)
m.send(con)
@command(location_type=LocationTypes.any, admin=True)
def add_type(con, class_name):
"""Add a new type."""
cls = Base._decl_class_registry[class_name]
obj = cls(name='Untitled')
obj.save()
con.call_command('edit_type', class_name=class_name, id=obj.id)
@command(location_type=LocationTypes.any, admin=True)
def remove_type(con, command_name, class_name, id=None, response=None):
"""Remove a type."""
cls = Base._decl_class_registry[class_name]
if id is None:
m = Menu('Select Object')
for obj in cls.all():
m.add_item(
obj.get_name(), command_name,
args=dict(class_name=class_name, id=obj.id)
)
m.send(con)
else:
kwargs = dict(class_name=class_name, id=id)
if response is None:
m = YesNoMenu('Are you sure?', command_name, args=kwargs)
m.send(con)
elif response:
obj = cls.get(id)
if obj is None:
con.message('Invalid type.')
else:
obj.delete()
con.message('Done.')
else:
con.message('Cancelled.')
@command(location_type=LocationTypes.any, admin=True)
def edit_type(con, command_name, class_name, id=None, column=None, text=None):
"""Edit a type."""
cls = Base._decl_class_registry[class_name]
if id is None:
m = Menu('Objects')
for obj in cls.all():
m.add_item(
obj.get_name(), command_name,
args=dict(class_name=class_name, id=obj.id)
)
m.send(con)
else:
i = inspect(cls)
obj = cls.get(id)
if column is not None:
kwargs = dict(class_name=class_name, id=id, column=column)
c = i.c[column]
if text is None:
keys = list(c.foreign_keys)
if len(keys) == 1:
key = keys[0]
remote_class = Base.get_class_from_table(
key.column.table
)
m = Menu('Select Object')
if c.nullable:
null_kwargs = kwargs.copy()
null_kwargs['text'] = ''
m.add_item('NULL', command_name, args=null_kwargs)
for thing in remote_class.all():
remote_kwargs = kwargs.copy()
remote_kwargs['text'] = str(thing.id)
m.add_item(
thing.get_name(), command_name, args=remote_kwargs
)
return m.send(con)
if isinstance(c.type, Enum):
m = Menu('Enumeration')
if c.nullable:
null_kwargs = kwargs.copy()
null_kwargs['text'] = ''
m.add_item('NULL', command_name, args=null_kwargs)
for value in c.type.python_type.__members__.values():
item_kwargs = kwargs.copy()
item_kwargs['text'] = value.name
m.add_item(str(value), command_name, args=item_kwargs)
return m.send(con)
value = getattr(obj, column)
if value is None:
value = ''
else:
value = str(value)
return con.text(
'Enter value', command_name, value=value, args=kwargs
)
else:
if text == '': # Same as None.
if c.nullable:
value = None
else:
con.message('That column is not nullble.')
value = _empty
else:
try:
if isinstance(c.type, Enum):
value = getattr(c.type.python_type, text)
else:
value = c.type.python_type(text)
except (ValueError, AttributeError):
con.message('Invalid value.')
value = _empty
if value is not _empty:
setattr(obj, column, value)
obj.save()
m = Menu(obj.get_name())
m.add_label(getdoc(cls))
kwargs = dict(class_name=class_name, id=obj.id)
for c in sorted(i.c, key=lambda thing: thing.name):
if c.primary_key:
continue
name = c.name
column_kwargs = kwargs.copy()
column_kwargs['column'] = name
title = name.replace('_', ' ').title()
value = getattr(obj, name)
keys = list(c.foreign_keys)
new_value = None
if value is not None:
if isinstance(c.type, Boolean):
new_value = not value
if keys:
key = keys[0]
remote_class = Base.get_class_from_table(
key.column.table
)
value = remote_class.get(value).get_name()
else:
value = repr(value)
column_kwargs['text'] = new_value
m.add_item(
f'{title}: {value} [{c.type}]', command_name,
args=column_kwargs
)
if cls is BuildingType:
kwargs = dict(building_type_id=obj.id)
el = english_list(obj.builders, empty='None')
m.add_item(
f'Unit types that can build this building: {el}',
'edit_builders', args=kwargs
)
el = english_list(obj.recruits, empty='None')
m.add_item(
f'Unit types this building can recruit: {el}',
'edit_recruits', args=kwargs
)
if any([obj.depends, obj.dependencies]):
if obj.depends is not None:
m.add_label('Depends')
m.add_item(
obj.depends.get_name(), command_name, args=dict(
class_name=class_name, id=obj.depends_id
)
)
if obj.dependencies:
m.add_label('Dependencies')
for d in obj.dependencies:
m.add_item(
d.get_name(), command_name,
args=dict(class_name=class_name, id=d.id)
)
m.add_label('Skill Types')
m.add_item('Add', 'add_skill_type', args=kwargs)
for st in obj.skill_types:
name = f'{st.skill_type.name} ({st.resources_string()}'
m.add_item(
name, 'edit_type', args=dict(
class_name='SkillType', id=st.id
)
)
m.add_item(
'Delete', 'delete_object', args=dict(
class_name='SkillType', id=st.id
)
)
elif cls is UnitType:
m.add_label('Buildings which can be built by units of this type')
for bt in obj.can_build:
m.add_item(
bt.get_name(), 'edit_type', args=dict(
class_name='BuildingType', id=bt.id
)
)
m.add_label('Buildings which can recruit units of this type')
for bm in BuildingRecruit.all(unit_type_id=obj.id):
bt = BuildingType.get(bm.building_type_id)
m.add_item(
bt.get_name(), 'edit_recruits', args=dict(
building_type_id=bt.id, building_unit_id=bm.id
)
)
if cls is SkillType:
class_name = 'BuildingType'
m.add_item('Done', command_name, args=dict(class_name=class_name))
m.send(con)
@command(location_type=LocationTypes.any, admin=True)
def edit_builders(con, command_name, building_type_id, unit_type_id=None):
"""Add and remove unit types that can build buildings."""
bt = BuildingType.get(building_type_id)
if unit_type_id is None:
m = Menu('Unit Types')
for mt in UnitType.all():
if bt in mt.can_build:
checked = '*'
else:
checked = ' '
m.add_item(
f'{mt.get_name()} ({checked})', command_name, args=dict(
building_type_id=bt.id, unit_type_id=mt.id
)
)
m.add_item(
'Done', 'edit_type', args=dict(class_name='BuildingType', id=bt.id)
)
m.send(con)
else:
mt = UnitType.get(unit_type_id)
if mt in bt.builders:
bt.builders.remove(mt)
action = 'no longer'
else:
bt.builders.append(mt)
action = 'now'
con.message(f'{mt.get_name()} can {action} build {bt.get_name()}.')
con.call_command(command_name, building_type_id=bt.id)
@command(location_type=LocationTypes.any, admin=True)
def delete_object(con, command_name, class_name, id=None, response=None):
"""Delete the given object."""
cls = Base._decl_class_registry[class_name]
if id is None:
m = Menu('Objects')
for obj in cls.all():
m.add_item(
str(obj), command_name, args=dict(
class_name=class_name, id=obj.id
)
)
m.send(con)
elif response is None:
m = YesNoMenu(
'Are you sure?', command_name, args=dict(
class_name=class_name, id=id
)
)
m.send(con)
elif response:
obj = cls.get(id)
obj.delete()
con.message('Done.')
else:
con.message('Cancelled.')
@command(location_type=LocationTypes.any, admin=True)
def add_recruit(con, command_name, building_type_id, unit_type_id=None):
"""Add a recruit to the given building type."""
bt = BuildingType.get(building_type_id)
if unit_type_id is None:
m = Menu('Unit Types')
for mt in UnitType.all():
m.add_item(
mt.get_name(), command_name, args=dict(
building_type_id=bt.id, unit_type_id=mt.id
)
)
m.send(con)
else:
mt = UnitType.get(unit_type_id)
bt.add_recruit(mt).save()
con.call_command('edit_recruits', building_type_id=bt.id)
@command(location_type=LocationTypes.any, admin=True)
def edit_recruits(
con, command_name, building_type_id, building_unit_id=None,
resource_name=None, text=None
):
"""Edit recruits for the given building type."""
columns = inspect(BuildingRecruit).c
resource_names = BuildingRecruit.resource_names()
resource_names.append('pop_time')
bt = BuildingType.get(building_type_id)
if building_unit_id is None:
m = Menu('Recruits')
m.add_item(
'Add Recruit', 'add_recruit', args=dict(building_type_id=bt.id)
)
for bm in BuildingRecruit.all(building_type_id=bt.id):
mt = UnitType.get(bm.unit_type_id)
m.add_item(
f'{mt.get_name()}: {bm.resources_string()}', command_name,
args=dict(building_type_id=bt.id, building_unit_id=bm.id)
)
m.add_item(
'Done', 'edit_type', args=dict(class_name='BuildingType', id=bt.id)
)
m.send(con)
else:
bm = BuildingRecruit.get(building_unit_id)
kwargs = dict(building_type_id=bt.id, building_unit_id=bm.id)
if resource_name is not None:
if text is None:
kwargs['resource_name'] = resource_name
value = getattr(bm, resource_name)
if value is None:
value = ''
return con.text(
'Enter value', command_name, value=value, args=kwargs
)
else:
if not text:
if columns[resource_name].nullable:
value = None
else:
con.message('Value cannot be null.')
value = _empty
else:
try:
value = int(text)
except ValueError:
con.message('Invalid value.')
value = _empty
if value is not _empty:
if resource_name in resource_names:
setattr(bm, resource_name, value)
bm.save()
else:
con.message('Invalid resource name.')
kwargs = dict(building_type_id=bt.id, building_unit_id=bm.id)
m = Menu('Recruit Options')
for name in resource_names:
resource_kwargs = kwargs.copy()
resource_kwargs['resource_name'] = name
value = getattr(bm, name)
m.add_item(
f'{name.title()}: {value}', command_name, args=resource_kwargs
)
m.add_item(
'Delete', 'delete_object', args=dict(
class_name='BuildingRecruit', id=bm.id
)
)
m.add_item(
'Done', 'edit_type', args=dict(class_name='BuildingType', id=bt.id)
)
m.send(con)
@command(location_type=LocationTypes.any, admin=True)
def add_skill_type(con, command_name, building_type_id, skill_type_name=None):
"""Add a SkillType instance to a BuildingType instance."""
bt = BuildingType.get(building_type_id)
if skill_type_name is None:
m = Menu('Skill Types')
for name, member in SkillTypes.__members__.items():
m.add_item(
f'{name}: {member.value}', command_name, args=dict(
building_type_id=bt.id, skill_type_name=name
)
)
m.send(con)
else:
member = getattr(SkillTypes, skill_type_name)
st = SkillType(building_type_id=bt.id, skill_type=member)
st.save()
con.call_command('edit_type', class_name='SkillType', id=st.id)
| {
"repo_name": "chrisnorman7/pyrts",
"path": "server/commands/administration.py",
"copies": "1",
"size": "18864",
"license": "mpl-2.0",
"hash": -8775361409495927000,
"line_mean": 35.2769230769,
"line_max": 79,
"alpha_frac": 0.5096480068,
"autogenerated": false,
"ratio": 3.9655244902249316,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9975172497024931,
"avg_score": 0,
"num_lines": 520
} |
"""Administrative commands."""
import logging
import re
from functools import partial
from socket import gethostbyname, error
from time import time
from subprocess import Popen, PIPE
from twisted.internet import reactor
from sqlalchemy import or_
from gsb.intercept import Menu, MenuItem
from shell import Shell
from db import CommunicationChannel, BannedIP, session, ServerOptions, \
ChangelogEntry
from permissions import is_admin, is_programmer
from util import pluralise, done
from parsers import parser
from forms import ObjectForm
logger = logging.getLogger(__name__)
shells = {} # All the shells.
with parser.default_kwargs(allowed=is_admin) as command:
@command(names='@server-options')
def do_server_options(caller):
"""Configure the server options profiles."""
m = Menu(title='Server Options', restore_parser=parser)
m.add_label('Profiles', None)
for p in ServerOptions.objects():
m.item(repr(p))(
lambda c, profile=p: c.connection.notify(ObjectForm, p)
)
if m.items:
m.add_label('Actions', m.items[-1])
m.item('Add Profile')(
lambda caller: caller.connection.notify(
ObjectForm,
ServerOptions()
)
)
caller.connection.notify(m)
@command(names='@join', help='@join <thing>')
def do_join(caller):
"""Moves you to join another object."""
player = caller.connection.player
thing = player.match_object(caller.args_str).get_single_match(player)
if thing is not None:
if thing.location is player.location and \
thing.coordinates == player.coordinates:
player.notify('You are already there.')
else:
player.notify('Moving you to %s.', thing)
player.do_social(player.teleport_leave_msg)
player.location = thing.location
player.coordinates = thing.coordinates
player.do_social(player.teleport_arrive_msg, exclude=[player])
player.notify(player.do_look())
@command(
names='@reload',
help='@reload commands\n@reload tasks',
args_regexp='^(commands|tasks)$'
)
def do_reload(caller):
"""Reload commands or tasks."""
what = caller.args[0]
if what:
stuff = what.title()
else:
stuff = 'Commands and Tasks'
started = time()
player = caller.connection.player
logger.info('%s reloaded by %s.', stuff, caller.connection.player)
caller.connection.server.broadcast('%s reloading.', stuff)
p = Popen(['git', 'pull'], stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
if stderr:
player.notify(stderr.decode())
if stdout:
player.notify(stdout.decode())
if what is None:
caller.connection.server.reload_commands()
caller.connection.server.reload_tasks()
else:
getattr(caller.connection.server, 'reload_%s' % what)()
caller.connection.server.broadcast(
'Reload completed in %g seconds.',
time() - started
)
@command(
names='@broadcast',
help='@broadcast <anything>'
)
def do_broadcast(caller):
"""Broadcasts <message> to everyone in the game."""
player = caller.connection.player
argstring = caller.args_str
if not argstring:
return player.notify(
'Please broadcast something. See help @broadcast for more '
'info.'
)
logger.info('Broadcast message from %s: "%s"', player, caller.args_str)
caller.connection.server.broadcast(
'%s broadcasts: "%s"',
player.name,
caller.args_str
)
@command(
names='@change',
help="@change <changelog entry>"
)
def do_add_change(caller):
"""Add a changelog entry from within the game."""
player = caller.connection.player
argstring = caller.args_str
if not argstring:
return player.notify(
'Text must be given as an argument. See help @change.'
)
elif len(argstring) > ChangelogEntry.text.type.length:
return player.notify(
'Your change text is too long (%d > %d characters).',
len(argstring),
ChangelogEntry.text.type.length
)
def f(caller):
caller.connection.server.broadcast(
'Game change by %s: %s',
player.name,
caller.text
)
entry = ChangelogEntry(
text=caller.text,
owner=player
)
entry.save()
player.notify(
caller.connection.server.get_spell_checker(caller),
argstring,
f,
restore_parser=caller.connection.parser
)
@command(names='@shutdown')
def do_shutdown(caller):
"""@shutdown
Shuts down the server."""
if caller.args_str:
return caller.connection.notify('This command takes no arguments.')
logger.info(
'Server shutdown initiated by %s.',
caller.connection.player
)
caller.connection.server.broadcast('The server is shutting down now.')
reactor.callLater(1.0, reactor.stop)
@command(names='@dump')
def do_dump(caller):
"""Dump the database to disk."""
started = time()
player = caller.connection.player
logger.info('Dump initiated by %s.', player)
caller.connection.server.dump()
player.notify(
'Dumped completed on %s in %.2f seconds.',
caller.connection.server.db_filename,
time() - started
)
@command(
names='@make-communication-channel',
help='@make-communication-channel <name> <description>',
args_regexp='^([^ ]+) ([^$]+)$'
)
def make_communication_channel(caller):
"""Make a communication channel named <name> with the description
<description>."""
name, description = caller.args
c = CommunicationChannel(name=name, description=description)
c.save()
caller.connection.player.notify('Created %r.', c)
@command(names='@ban', help='@ban <hostname>', args_regexp='([^$]+)')
def do_ban(caller):
"""Ban an IP address."""
player = caller.connection.player
hostname = caller.args_str
try:
ip = gethostbyname(hostname)
except error:
return player.notify(
'%s is neither a valid host name or IP address.',
hostname
)
# Make sure we're not adding a duplicate:
if session.query(BannedIP).filter_by(ip=ip).count():
player.notify('%s (%s) is already banned.', hostname, ip)
else:
h = BannedIP(owner=player, ip=ip, hostname=hostname)
h.save()
player.notify('Banned %s.', h)
@command(
names='@unban',
help='@unban <ip>\n@unban <hostname>\n@unban <id>'
)
def unbann(caller):
"""Unban an IP address."""
player = caller.connection.player
thing = caller.args_str
row = session.query(BannedIP).filter(
or_(
BannedIP.ip == thing,
BannedIP.hostname == thing,
BannedIP.id == thing
)
).first()
if row is not None:
player.notify('Unbanned %s.', row)
row.delete()
else:
player.notify('%s not found. Try the @banned-ips command.', thing)
@command(names='@banned-ips')
def banned_ips(caller):
"""Show all banned IP addresses."""
player = caller.connection.player
ips = session.query(BannedIP)
c = ips.count()
if c:
player.notify(
'Showing %d banned IP %s:',
c,
pluralise(c, 'address', plural='addresses')
)
for row in ips:
player.notify(
'[%d] %s (%s) banned by %s on %s',
row.id,
row.hostname,
row.ip,
row.owner,
row.banned.ctime()
)
else:
player.notify('There are no banned IP addresses.')
@command(names='@idle', help='@idle <player>')
def do_idle(caller):
"""Shows how long <player> has been idle for."""
player = caller.connection.player
thing = player.match_player(caller.args_str).get_single_match(player)
if thing is not None:
idle = thing.idle_time()
if idle is None:
player.notify('%s has never entered a command.', thing)
else:
player.notify(
'%s has been idle for %s since %s.',
thing,
idle,
thing.commands[-1].sent.ctime()
)
@command(names='@bring', help='@bring <player>')
def do_bring(caller):
"""Bring the player named <name> to your current location."""
player = caller.connection.player
target = player.match_object(caller.args_str).get_single_match(player)
if target is not None:
if target.location is player.location:
player.notify('%s is already with you.', target)
else:
target.do_social('%1T vanish%1e.')
target.location = player.location
target.save()
target.do_social('%1T appear%1s.')
@command(names='@boot', help='@boot[ <player>]')
def do_boot(caller):
"""Boot a player names <player>. If <player is not provided, choose a
connection from the resulting menu."""
def f(connection, caller):
"""Boot the connection and tell the player."""
caller.connection.server.disconnect(connection)
done(caller.connection)
player = caller.connection.player
who = caller.args_str
if not who:
player.notify(
Menu,
title='Select a connection to disconnect:',
restore_parser=parser,
items=[
MenuItem(
'%s:%d (%s)' % (
con.host,
con.port,
'No player' if con.player is None else con.player
),
partial(f, con)
) for con in caller.connection.server.connections
]
)
else:
who = player.match_player(who).get_single_match(player)
if who is not None:
if getattr(who, 'connection', None) is None:
player.notify('%s is not connected.', who)
else:
f(who.connection, caller)
with parser.default_kwargs(allowed=is_programmer):
@command(names='@eval', help='@eval <code>')
def do_eval(caller):
"""Evaluates <code and prints the result to you.
You can use MOO-style object numbers (#15 for example).
Any semicolon (;) characters are replaced with \n so you can enter
multiline code.
The following globals are available:
logger - The "commands.admin" logger.
server - The main server object.
All the members of the db module.
reactor - The twisted reactor.
caller - The caller which was sent with this command.
con - Your connection.
player - Your player object.
account - Your account object."""
player = caller.connection.player
if player.id not in shells:
shells[player.id] = Shell(player)
shell = shells[player.id]
shell.locals['caller'] = caller
shell.locals['here'] = player.location
code = re.sub(
r'(\#([0-9]+))',
r'toobj(\2)',
caller.args_str
)
shell.push(code.replace(';', '\n') + '\n')
logger.info('%s eval: "%s"', player, code)
| {
"repo_name": "chrisnorman7/game",
"path": "commands/admin.py",
"copies": "1",
"size": "12791",
"license": "mpl-2.0",
"hash": -6277316290582365000,
"line_mean": 34.0309859155,
"line_max": 79,
"alpha_frac": 0.5256039403,
"autogenerated": false,
"ratio": 4.5007037297677694,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5526307670067769,
"avg_score": null,
"num_lines": null
} |
"""Administrator interface to resource manager."""
from django.contrib import admin
from apps.managers.challenge_mgr import challenge_mgr
from apps.managers.resource_mgr.models import EnergyUsage, WaterUsage, ResourceSetting, \
ResourceBlackoutDate, WasteUsage
from apps.admin.admin import challenge_designer_site, challenge_manager_site, developer_site
class UsageAdmin(admin.ModelAdmin):
"""Administrator display list: team, date, and energy."""
list_display = ["date", "team", "time", "usage", "updated_at"]
search_fields = ["team__name", ]
list_filter = ['team']
date_hierarchy = "date"
admin.site.register(EnergyUsage, UsageAdmin)
challenge_designer_site.register(EnergyUsage, UsageAdmin)
challenge_manager_site.register(EnergyUsage, UsageAdmin)
developer_site.register(EnergyUsage, UsageAdmin)
admin.site.register(WaterUsage, UsageAdmin)
challenge_designer_site.register(WaterUsage, UsageAdmin)
challenge_manager_site.register(WaterUsage, UsageAdmin)
developer_site.register(WaterUsage, UsageAdmin)
class ResourceSettingsAdmin(admin.ModelAdmin):
"""Administrator display list: team, date, and energy."""
list_display = ["name", "unit", "winning_order", "conversion_rate"]
readonly_fields = ["name"]
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
admin.site.register(ResourceSetting, ResourceSettingsAdmin)
challenge_designer_site.register(ResourceSetting, ResourceSettingsAdmin)
challenge_manager_site.register(ResourceSetting, ResourceSettingsAdmin)
developer_site.register(ResourceSetting, ResourceSettingsAdmin)
class ResourceBlackoutDateAdmin(admin.ModelAdmin):
"""EnergyGoal administrator interface definition."""
list_display = ["date", "description"]
admin.site.register(ResourceBlackoutDate, ResourceBlackoutDateAdmin)
challenge_designer_site.register(ResourceBlackoutDate, ResourceBlackoutDateAdmin)
challenge_manager_site.register(ResourceBlackoutDate, ResourceBlackoutDateAdmin)
developer_site.register(ResourceBlackoutDate, ResourceBlackoutDateAdmin)
challenge_mgr.register_designer_challenge_info_model("Other Settings", 3, ResourceBlackoutDate, 4)
challenge_mgr.register_developer_challenge_info_model("Resources", 5, ResourceSetting, 1)
challenge_mgr.register_developer_challenge_info_model("Resources", 5, ResourceBlackoutDate, 1)
challenge_mgr.register_developer_game_info_model("Energy Game", EnergyUsage)
challenge_mgr.register_developer_game_info_model("Water Game", WaterUsage)
challenge_mgr.register_developer_game_info_model("Waste Game", WasteUsage)
| {
"repo_name": "jtakayama/makahiki-draft",
"path": "makahiki/apps/managers/resource_mgr/admin.py",
"copies": "9",
"size": "2631",
"license": "mit",
"hash": -4199243386923521000,
"line_mean": 44.3620689655,
"line_max": 98,
"alpha_frac": 0.7943747624,
"autogenerated": false,
"ratio": 3.8634361233480177,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9157810885748018,
"avg_score": null,
"num_lines": null
} |
"""Administrator interface to score_mgr."""
from django.contrib import admin
from apps.managers.challenge_mgr import challenge_mgr
from apps.widgets.participation.models import ParticipationSetting, TeamParticipation
from apps.admin.admin import challenge_designer_site, challenge_manager_site, developer_site
class ParticipationSettingAdmin(admin.ModelAdmin):
"""EnergyGoal administrator interface definition."""
list_display = ["name", ]
list_display_links = ["name", ]
page_text = "There must only be one Participation Setting. You can edit the amount" + \
" of points awarded per player for the various levels of team participation."
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
admin.site.register(ParticipationSetting, ParticipationSettingAdmin)
challenge_designer_site.register(ParticipationSetting, ParticipationSettingAdmin)
challenge_manager_site.register(ParticipationSetting, ParticipationSettingAdmin)
developer_site.register(ParticipationSetting, ParticipationSettingAdmin)
challenge_mgr.register_designer_game_info_model("Participation Game", ParticipationSetting)
class TeamParticipationAdmin(admin.ModelAdmin):
"""EnergyGoal administrator interface definition."""
list_display = ["round_name", "team", "participation", "awarded_percent", "updated_at"]
list_filter = ["round_name"]
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
admin.site.register(TeamParticipation, TeamParticipationAdmin)
challenge_designer_site.register(TeamParticipation, TeamParticipationAdmin)
challenge_manager_site.register(TeamParticipation, TeamParticipationAdmin)
developer_site.register(TeamParticipation, TeamParticipationAdmin)
challenge_mgr.register_developer_game_info_model("Participation Game", ParticipationSetting)
challenge_mgr.register_developer_game_info_model("Participation Game", TeamParticipation)
| {
"repo_name": "justinslee/Wai-Not-Makahiki",
"path": "makahiki/apps/widgets/participation/admin.py",
"copies": "9",
"size": "2043",
"license": "mit",
"hash": 5228563970908034000,
"line_mean": 44.4,
"line_max": 92,
"alpha_frac": 0.7909936368,
"autogenerated": false,
"ratio": 3.721311475409836,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0034674006089105646,
"num_lines": 45
} |
"""Administrator interface to score_mgr."""
from django.contrib import admin
from apps.managers.challenge_mgr import challenge_mgr
from apps.managers.score_mgr.models import ScoreSetting, ScoreboardEntry, PointsTransaction, \
ReferralSetting
from apps.admin.admin import challenge_designer_site, challenge_manager_site, developer_site
class PointsTransactionAdmin(admin.ModelAdmin):
"""PointsTransaction administrator interface definition."""
list_display = ["user", "transaction_date", "points", "message"]
search_fields = ["user__username", "message"]
date_hierarchy = "transaction_date"
admin.site.register(PointsTransaction, PointsTransactionAdmin)
challenge_designer_site.register(PointsTransaction, PointsTransactionAdmin)
challenge_manager_site.register(PointsTransaction, PointsTransactionAdmin)
developer_site.register(PointsTransaction, PointsTransactionAdmin)
class ScoreboardEntryAdmin(admin.ModelAdmin):
"""PointsTransaction administrator interface definition."""
list_display = ["round_name", "profile", "points", "last_awarded_submission"]
search_fields = ["profile__name", "profile__user__username"]
list_filter = ["round_name"]
admin.site.register(ScoreboardEntry, ScoreboardEntryAdmin)
challenge_designer_site.register(ScoreboardEntry, ScoreboardEntryAdmin)
challenge_manager_site.register(ScoreboardEntry, ScoreboardEntryAdmin)
developer_site.register(ScoreboardEntry, ScoreboardEntryAdmin)
class ScoreSettingAdmin(admin.ModelAdmin):
"""PointsTransaction administrator interface definition."""
list_display = ["name", ]
list_display_links = ["name", ]
page_text = "There must only be one Score Setting. You can edit the amount" + \
" of points awarded for completing the various actions and how many points are " + \
"needed for a player to be 'active'."
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
admin.site.register(ScoreSetting, ScoreSettingAdmin)
challenge_designer_site.register(ScoreSetting, ScoreSettingAdmin)
challenge_manager_site.register(ScoreSetting, ScoreSettingAdmin)
developer_site.register(ScoreSetting, ScoreSettingAdmin)
class ReferralSettingAdmin(admin.ModelAdmin):
"""PointsTransaction administrator interface definition."""
list_display = ["normal_referral_points", "super_referral_points",
"mega_referral_points", "start_dynamic_bonus", ]
list_display_links = ["normal_referral_points", "super_referral_points",
"mega_referral_points", "start_dynamic_bonus", ]
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
admin.site.register(ReferralSetting, ReferralSettingAdmin)
challenge_designer_site.register(ReferralSetting, ReferralSettingAdmin)
challenge_manager_site.register(ReferralSetting, ReferralSettingAdmin)
developer_site.register(ReferralSetting, ReferralSettingAdmin)
challenge_mgr.register_designer_challenge_info_model("Challenge", 1, ScoreSetting, 3)
challenge_mgr.register_designer_game_info_model("Referral Game Mechanics", ReferralSetting)
challenge_mgr.register_admin_challenge_info_model("Status", 1, PointsTransaction, 4)
challenge_mgr.register_admin_challenge_info_model("Status", 1, ScoreboardEntry, 5)
challenge_mgr.register_developer_challenge_info_model("Challenge", 1, ScoreSetting, 3)
challenge_mgr.register_developer_challenge_info_model("Status", 4, PointsTransaction, 2)
challenge_mgr.register_developer_challenge_info_model("Status", 4, ScoreboardEntry, 3)
challenge_mgr.register_developer_game_info_model("Referral Game Mechanics", ReferralSetting)
| {
"repo_name": "yongwen/makahiki",
"path": "makahiki/apps/managers/score_mgr/admin.py",
"copies": "9",
"size": "3740",
"license": "mit",
"hash": 1453872890488401200,
"line_mean": 45.75,
"line_max": 94,
"alpha_frac": 0.7737967914,
"autogenerated": false,
"ratio": 3.899895724713243,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9173692516113243,
"avg_score": null,
"num_lines": null
} |
"""Administrator interface to teams."""
from django.contrib import admin
from apps.managers.challenge_mgr import challenge_mgr
from apps.managers.team_mgr.models import Group, Team, Post
from apps.admin.admin import challenge_designer_site, challenge_manager_site, developer_site
class GroupAdmin(admin.ModelAdmin):
"""Category Admin"""
list_display = ["name", ]
page_text = "Groups are optional in this challenge."
admin.site.register(Group, GroupAdmin)
challenge_designer_site.register(Group, GroupAdmin)
challenge_manager_site.register(Group, GroupAdmin)
developer_site.register(Group, GroupAdmin)
class TeamAdmin(admin.ModelAdmin):
"""Category Admin"""
list_display = ["name", "size", "group"]
fields = ["name", "size", "group"]
admin.site.register(Team, TeamAdmin)
challenge_designer_site.register(Team, TeamAdmin)
challenge_manager_site.register(Team, TeamAdmin)
developer_site.register(Team, TeamAdmin)
class PostAdmin(admin.ModelAdmin):
"""Post administrator for teams, overrides delete_selected"""
list_filter = ["style_class", "team"]
actions = ["delete_selected"]
def delete_selected(self, request, queryset):
"""delete selected override"""
_ = request
for obj in queryset:
obj.delete()
delete_selected.short_description = "Delete the selected objects."
admin.site.register(Post, PostAdmin)
challenge_designer_site.register(Post, PostAdmin)
challenge_manager_site.register(Post, PostAdmin)
developer_site.register(Post, PostAdmin)
challenge_mgr.register_designer_challenge_info_model("Players", 2, Group, 2)
challenge_mgr.register_designer_challenge_info_model("Players", 2, Team, 2)
challenge_mgr.register_admin_challenge_info_model("Status", 1, Post, 5)
challenge_mgr.register_developer_challenge_info_model("Players", 2, Group, 1)
challenge_mgr.register_developer_challenge_info_model("Players", 2, Team, 2)
challenge_mgr.register_developer_challenge_info_model("Status", 4, Post, 5)
| {
"repo_name": "KendyllD/boukenda-project",
"path": "makahiki/apps/managers/team_mgr/admin.py",
"copies": "5",
"size": "1990",
"license": "mit",
"hash": 4476867076689334300,
"line_mean": 36.5471698113,
"line_max": 92,
"alpha_frac": 0.7442211055,
"autogenerated": false,
"ratio": 3.6580882352941178,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6902309340794118,
"avg_score": null,
"num_lines": null
} |
"""Admin (LDAP) context."""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import logging
from ldap3.core import exceptions as ldap_exceptions
from treadmill import admin
from treadmill import context
_LOGGER = logging.getLogger(__name__)
def connect(url, ldap_suffix, user, password):
"""Connect to from parent context parameters."""
_LOGGER.debug('Connecting to LDAP %s, %s', url, ldap_suffix)
conn = admin.Admin(url, ldap_suffix,
user=user, password=password)
conn.connect()
return conn
def resolve(ctx, attr):
"""Resolve context attribute."""
if attr != 'zk_url':
raise KeyError(attr)
# TODO: in case of invalid cell it will throw ldap exception.
# need to standardize on ContextError raised lazily
# on first connection attempt, and keep resolve
# exception free.
try:
admin_cell = admin.Cell(ctx.ldap.conn)
cell = admin_cell.get(ctx.cell)
zk_hostports = [
'%s:%s' % (master['hostname'], master['zk-client-port'])
for master in cell['masters']
]
return 'zookeeper://%s@%s/treadmill/%s' % (
cell['username'],
','.join(zk_hostports),
ctx.cell
)
except ldap_exceptions.LDAPNoSuchObjectResult:
exception = context.ContextError(
'Cell not defined in LDAP {}'.format(ctx.cell)
)
_LOGGER.debug(str(exception))
raise exception
def init(_ctx):
"""Init context."""
pass
| {
"repo_name": "bretttegart/treadmill",
"path": "lib/python/treadmill/adminctx.py",
"copies": "1",
"size": "1671",
"license": "apache-2.0",
"hash": -213971296936732860,
"line_mean": 25.9516129032,
"line_max": 70,
"alpha_frac": 0.6020347098,
"autogenerated": false,
"ratio": 4.075609756097561,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 62
} |
"""Admin (LDAP) context."""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import logging
import ldap3
from treadmill import admin
from treadmill import context
_LOGGER = logging.getLogger(__name__)
def connect(url, ldap_suffix, user, password):
"""Connect to from parent context parameters."""
_LOGGER.debug('Connecting to LDAP %s, %s', url, ldap_suffix)
conn = admin.Admin(url, ldap_suffix,
user=user, password=password)
conn.connect()
return conn
def resolve(ctx, attr):
"""Resolve context attribute."""
if attr != 'zk_url':
raise KeyError(attr)
# TODO: in case of invalid cell it will throw ldap exception.
# need to standardize on ContextError raised lazily
# on first connection attempt, and keep resolve
# exception free.
try:
admin_cell = admin.Cell(ctx.ldap.conn)
cell = admin_cell.get(ctx.cell)
zk_hostports = [
'%s:%s' % (master['hostname'], master['zk-client-port'])
for master in cell['masters']
]
return 'zookeeper://%s@%s/treadmill/%s' % (
cell['username'],
','.join(zk_hostports),
ctx.cell
)
except ldap3.LDAPNoSuchObjectResult:
exception = context.ContextError(
'Cell not defined in LDAP {}'.format(ctx.cell)
)
_LOGGER.debug(str(exception))
raise exception
def init(_ctx):
"""Init context."""
pass
| {
"repo_name": "captiosus/treadmill",
"path": "treadmill/adminctx.py",
"copies": "1",
"size": "1621",
"license": "apache-2.0",
"hash": 5339521820965970000,
"line_mean": 25.1451612903,
"line_max": 70,
"alpha_frac": 0.5940777298,
"autogenerated": false,
"ratio": 4.042394014962594,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5136471744762594,
"avg_score": null,
"num_lines": null
} |
"""Admin management service."""
from lzproduction.sql.utils import db_session
from lzproduction.sql.tables import Users
class Admins(object):
"""
Admin management Service.
Service for listing and setting current system
administrators.
"""
exposed = True
def __init__(self, template_env):
"""
Initialisation.
Args:
session_factory (sqlalchemy.sessionmaker): The session generation factory
template_env (jinja2.Environment): The jinja2 html templating engine
environment. This contains the html
root dir with the templates below it.
"""
self._template_env = template_env
def GET(self): # pylint: disable=invalid-name
"""
REST GET Method.
Returns:
str: The rendered HTML containing the users admin status as toggles.
"""
with db_session() as session:
return self._template_env.get_template('html/admins.html')\
.render({'users': session.query(Users).all()})
def PUT(self, user_id, admin): # pylint: disable=invalid-name
"""
REST PUT Method.
Args:
user_id (str): The id number of the user to modify
admin (str): The status of the admin flag true/false
(note passed through un-capitalised.)
"""
print "IN PUT(Admins)", user_id, admin
# could use ast.literal_eval(admin.capitalize()) but not sure if I trust it yet
admin = (admin.lower() == 'true')
with db_session() as session:
session.query(Users).filter_by(id=int(user_id)).update({'admin': admin})
| {
"repo_name": "alexanderrichards/LZProduction",
"path": "lzproduction/webapp/services/Admins.py",
"copies": "1",
"size": "1778",
"license": "mit",
"hash": -4346975379592418000,
"line_mean": 33.1923076923,
"line_max": 87,
"alpha_frac": 0.5652418448,
"autogenerated": false,
"ratio": 4.666666666666667,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0018301013039543083,
"num_lines": 52
} |
"""Admin method for logging in as another user."""
from django.conf import settings
from django.contrib.auth import SESSION_KEY
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from apps.managers.auth_mgr.forms import LoginForm
@user_passes_test(lambda u: u.is_staff, login_url="/account/cas/login")
def login_as(request, user_id):
"""Admin method for logging in as another user."""
# ref: http://copiousfreetime.blogspot.com/2006/12/django-su.html
user = get_object_or_404(User, id=user_id)
if user.is_active:
request.session[SESSION_KEY] = user_id
request.session['staff'] = True
# Expire this session when the browser closes.
request.session.set_expiry(0)
return HttpResponseRedirect(reverse("home_index"))
def login(request):
"""Show the login page and process the login form."""
if request.method == "POST":
form = LoginForm(request.POST)
if form.login(request):
return HttpResponseRedirect(reverse("home_index"))
else:
form = LoginForm()
return render_to_response("account/login.html", {"form": form},
context_instance=RequestContext(request))
def logout(request):
"""
simply logout and redirect to landing page
"""
username = request.user.username
from django.contrib import auth
# Sets a logout variable so that we can capture it in the logger.
request.session["logged-out-user"] = username
destination = "landing"
auth.logout(request)
if settings.CAS_SERVER_URL:
return HttpResponseRedirect(reverse("cas_logout") + "?next=" + reverse(destination))
else:
return HttpResponseRedirect(reverse(destination))
| {
"repo_name": "yongwen/makahiki",
"path": "makahiki/apps/managers/auth_mgr/views.py",
"copies": "9",
"size": "1974",
"license": "mit",
"hash": -8308001525236617000,
"line_mean": 33.6315789474,
"line_max": 92,
"alpha_frac": 0.6995947315,
"autogenerated": false,
"ratio": 4.078512396694215,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00018864365214110547,
"num_lines": 57
} |
"""Admin module for Django."""
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from django_q.conf import Conf, croniter
from django_q.models import Failure, OrmQ, Schedule, Success
from django_q.tasks import async_task
class TaskAdmin(admin.ModelAdmin):
"""model admin for success tasks."""
list_display = ("name", "func", "started", "stopped", "time_taken", "group")
def has_add_permission(self, request):
"""Don't allow adds."""
return False
def get_queryset(self, request):
"""Only show successes."""
qs = super(TaskAdmin, self).get_queryset(request)
return qs.filter(success=True)
search_fields = ("name", "func", "group")
readonly_fields = []
list_filter = ("group",)
def get_readonly_fields(self, request, obj=None):
"""Set all fields readonly."""
return list(self.readonly_fields) + [field.name for field in obj._meta.fields]
def retry_failed(FailAdmin, request, queryset):
"""Submit selected tasks back to the queue."""
for task in queryset:
async_task(task.func, *task.args or (), hook=task.hook, **task.kwargs or {})
task.delete()
retry_failed.short_description = _("Resubmit selected tasks to queue")
class FailAdmin(admin.ModelAdmin):
"""model admin for failed tasks."""
list_display = ("name", "func", "started", "stopped", "short_result")
def has_add_permission(self, request):
"""Don't allow adds."""
return False
actions = [retry_failed]
search_fields = ("name", "func")
list_filter = ("group",)
readonly_fields = []
def get_readonly_fields(self, request, obj=None):
"""Set all fields readonly."""
return list(self.readonly_fields) + [field.name for field in obj._meta.fields]
class ScheduleAdmin(admin.ModelAdmin):
"""model admin for schedules"""
list_display = (
"id",
"name",
"func",
"schedule_type",
"repeats",
"cluster",
"next_run",
"last_run",
"success",
)
# optional cron strings
if not croniter:
readonly_fields = ("cron",)
list_filter = ("next_run", "schedule_type", "cluster")
search_fields = ("func",)
list_display_links = ("id", "name")
class QueueAdmin(admin.ModelAdmin):
"""queue admin for ORM broker"""
list_display = ("id", "key", "task_id", "name", "func", "lock")
def save_model(self, request, obj, form, change):
obj.save(using=Conf.ORM)
def delete_model(self, request, obj):
obj.delete(using=Conf.ORM)
def get_queryset(self, request):
return super(QueueAdmin, self).get_queryset(request).using(Conf.ORM)
def has_add_permission(self, request):
"""Don't allow adds."""
return False
list_filter = ("key",)
admin.site.register(Schedule, ScheduleAdmin)
admin.site.register(Success, TaskAdmin)
admin.site.register(Failure, FailAdmin)
if Conf.ORM or Conf.TESTING:
admin.site.register(OrmQ, QueueAdmin)
| {
"repo_name": "Koed00/django-q",
"path": "django_q/admin.py",
"copies": "1",
"size": "3065",
"license": "mit",
"hash": -5505101336982111000,
"line_mean": 26.3660714286,
"line_max": 86,
"alpha_frac": 0.6261011419,
"autogenerated": false,
"ratio": 3.7607361963190185,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48868373382190183,
"avg_score": null,
"num_lines": null
} |
"""Admin module"""
import os
import math
from datetime import datetime
import copy
import discord
from discord.ext import commands
from modules.utils import checks
from modules.utils import utils
def is_owner_or_moderator(ctx):
"""Returns true if the author is the bot's owner or a moderator on the server"""
return ctx.message.author.id == ctx.bot.owner_id \
or ctx.message.author.id == ctx.message.server.owner.id \
or (ctx.message.server.id in ctx.bot.moderators \
and ctx.message.author.id in ctx.bot.moderators[ctx.message.server.id])
COLORS = { \
"Unban": 255 * math.pow(16, 2), \
"Warning": 250 * math.pow(16, 4) + 219 * math.pow(16, 2) + 24, \
"Kick": 243 * math.pow(16, 4) + 111 * math.pow(16, 2) + 40, \
"Ban": 255 * math.pow(16, 4), \
"b1nzy ban": 1 \
}
class Log:
"""A class representing a log element"""
id_counter = 1
def __init__(self, log_type: str, member_id: str, \
responsible_id: str, reason: str, date: str):
"""Init function"""
#pylint: disable=too-many-arguments
self.type = log_type
self.user_id = member_id
self.responsible_id = responsible_id
self.reason = reason
self.date = date
self.log_id = Log.id_counter
Log.id_counter += 1
def get_save(self):
"""Returns a dict representing a log element"""
data = {}
data["type"] = self.type
data["responsible"] = self.responsible_id
data["reason"] = self.reason
data["date"] = self.date
data["id"] = self.log_id
return data
def get_embed(self, bot):
"""Returns an embed corresponding to the log"""
embed = discord.Embed()
user = discord.utils.find(lambda u: u.id == self.user_id, \
bot.get_all_members())
if user:
embed.title = user.name + "#" + user.discriminator + " (" + user.id + ")"
embed.set_thumbnail(url=user.avatar_url)
else:
embed.title = "Unknown member (" + self.user_id + ")"
responsible = discord.utils.find(lambda u: u.id == self.responsible_id, \
bot.get_all_members())
if responsible:
embed.add_field(name="Responsible", \
value=responsible.name + "#" + responsible.discriminator + \
" (" + responsible.id + ")", inline=False)
else:
embed.add_field(name="Responsible", \
value="Uknown responsible (" + self.responsible_id + ")", inline=False)
embed.timestamp = datetime.strptime(self.date, "%d/%m/%Y %H:%M:%S")
embed.colour = discord.Colour(value=COLORS[self.type])
embed.set_author(name="Case #" + str(self.log_id))
embed.add_field(name="Reason", value=self.reason, inline=False)
return embed
class Admin:
"""Admin module"""
#pylint: disable=too-many-public-methods
def load_moderators(self):
"""Loads the moderators"""
if not os.path.exists(self.bot.moderators_file_path):
if not os.path.isdir("data/admin"):
os.makedirs("data/admin")
utils.save_json(self.bot.moderators, self.bot.moderators_file_path)
else:
self.bot.moderators = utils.load_json(self.bot.moderators_file_path)
def save_moderators(self):
"""Saves the moderators"""
utils.save_json(self.bot.moderators, self.bot.moderators_file_path)
def load_servers_config(self):
"""Loads the configuration"""
#pylint: disable=too-many-nested-blocks
if not os.path.exists(self.servers_config_file_path):
if not os.path.isdir("data/admin"):
os.makedirs("data/admin")
self.servers_config["id counter"] = 1
self.servers_config["servers"] = {}
Log.id_counter = 1
utils.save_json(self.servers_config, self.servers_config_file_path)
else:
data = utils.load_json(self.servers_config_file_path)
for server in data["servers"]:
if "log channel" in data["servers"][server]:
data["servers"][server]["log channel"] = discord.utils.find(lambda c, s=server:\
c.id == data["servers"][s]["log channel"], self.bot.get_all_channels())
if "logs" in data["servers"][server]:
logs = {}
known_admins = {}
for user_id in data["servers"][server]["logs"]:
member = discord.utils.find(lambda m, u=user_id: m.id == u, \
self.bot.get_all_members())
logs[user_id] = []
for log in data["servers"][server]["logs"][user_id]:
if log["responsible"] not in known_admins:
responsible = discord.utils.find(lambda r, l=log: \
r.id == l["responsible"], self.bot.get_all_members())
known_admins[log["responsible"]] = responsible
else:
responsible = known_admins[log["responsible"]]
logs[user_id].append(Log(log_type=log["type"],
member_id=member.id if member else "UNKNOWN",
responsible_id=responsible.id,
reason=log["reason"],
date=log["date"]))
data["servers"][server]["logs"] = logs
Log.id_counter = data["id counter"]
self.servers_config = data
def save_servers_config(self):
"""Saves the configuration"""
self.servers_config["id counter"] = Log.id_counter
data = copy.deepcopy(self.servers_config)
for server in data["servers"]:
if "log channel" in data["servers"][server]:
data["servers"][server]["log channel"] = data["servers"][server]["log channel"].id
if "logs" in data["servers"][server]:
logs = {}
for user_id in data["servers"][server]["logs"]:
logs[user_id] = []
for log in data["servers"][server]["logs"][user_id]:
logs[user_id].append(log.get_save())
data["servers"][server]["logs"] = logs
utils.save_json(data, self.servers_config_file_path)
def load_b1nzy_banlist(self):
"""Loads the b1nzy banlist"""
if not os.path.exists(self.b1nzy_banlist_path):
if not os.path.isdir("data/admin"):
os.makedirs("data/admin")
utils.save_json(self.b1nzy_banlist, self.b1nzy_banlist_path)
else:
self.b1nzy_banlist = utils.load_json(self.b1nzy_banlist_path)
def save_b1nzy_banlist(self):
"""Saves the b1nzy banlist"""
utils.save_json(self.b1nzy_banlist, self.b1nzy_banlist_path)
def __init__(self, bot):
"""Init function"""
self.bot = bot
self.servers_config = {}
self.servers_config_file_path = "data/admin/servers_config.json"
self.load_servers_config()
self.bot.moderators = {}
self.bot.moderators_file_path = "data/admin/moderators.json"
self.load_moderators()
self.b1nzy_banlist = {}
self.b1nzy_banlist_path = "data/admin/b1nzy_banlist.json"
self.load_b1nzy_banlist()
async def send_log(self, server: discord.Server, log: Log):
"""Sends a embed corresponding to the log in the log channel of the server"""
if server.id in self.servers_config["servers"]:
if "log channel" in self.servers_config["servers"][server.id]:
embed = log.get_embed(self.bot)
channel = self.servers_config["servers"][server.id]["log channel"]
try:
await self.bot.send_message(destination=channel, embed=embed)
except discord.Forbidden:
await self.bot.send_message(destination=server.owner, content=\
"I'm not allowed to send embeds in the log channel (#" + \
channel.name + "). Please change my permissions.")
except discord.NotFound:
await self.bot.send_message(destination=server.owner, content=\
"I'm not allowed to send embeds in the log channel because " + \
"it doesn't exists anymore. Please set another log channel " + \
"using the `[p]set_log_channel` command.")
except discord.HTTPException:
pass
except discord.InvalidArgument:
pass
@commands.command()
@checks.is_owner()
async def add_blacklist(self, user: discord.Member):
"""Adds an user to the bot's blacklist
Parameters:
user: The user you want to add to the bot's blacklist.
Example: [p]add_blacklist @AVeryMeanUser"""
if user.id not in self.bot.blacklist:
self.bot.blacklist.append(user.id)
utils.save_json(self.bot.blacklist, self.bot.blacklist_file_path)
await self.bot.say("Done.")
else:
await self.bot.say(user.name + "#" + user.discriminator + " (" + \
user.id + ") is already blacklisted.")
@commands.command()
@checks.is_owner()
async def add_blacklist_id(self, user_id: str):
"""Adds an user to the bot's blacklist using his ID
Parameters:
user_id: The ID of the user you want to add to the bot's blacklist.
Example: [p]add_blacklist_id 346654353341546499"""
if user_id not in self.bot.blacklist:
self.bot.blacklist.append(user_id)
utils.save_json(self.bot.blacklist, self.bot.blacklist_file_path)
await self.bot.say("Done.")
else:
await self.bot.say("This ID is already in the blacklist.")
@commands.command()
@checks.is_owner()
async def rem_blacklist(self, user: discord.Member):
"""Removes an user from the bot's blacklist
Parameters:
user: The user you want to remove from the bot's blacklist.
Example: [p]rem_blacklist @AGoodGuyUnfairlyBlacklisted"""
if user.id in self.bot.blacklist:
self.bot.blacklist.remove(user.id)
utils.save_json(self.bot.blacklist, self.bot.blacklist_file_path)
await self.bot.say("Done.")
else:
await self.bot.say("This user wasn't even blacklisted.")
@commands.command()
@checks.is_owner()
async def rem_blacklist_id(self, user_id: str):
"""Removes an user from the bot's blacklist using his ID
Parameters:
user_id: The ID of the user you want to to remove from the bot's blacklist.
Example: [p]rem_blacklist @AGoodGuyUnfairlyBlacklisted"""
if user_id in self.bot.blacklist:
self.bot.blacklist.remove(user_id)
utils.save_json(self.bot.blacklist, self.bot.blacklist_file_path)
await self.bot.say("Done.")
else:
await self.bot.say("This ID wasn't even in the blacklist.")
@commands.command(pass_context=True)
@checks.is_owner_or_server_owner()
async def add_moderator(self, ctx, member: discord.Member):
"""Adds a moderator for the server
Parameters:
member: The member that will become a moderator.
Example: [p]add_moderator @Beafantles"""
if ctx.message.server.id not in self.bot.moderators:
self.bot.moderators[ctx.message.server.id] = [member.id]
else:
if member.id not in self.bot.moderators[ctx.message.server.id]:
self.bot.moderators[ctx.message.server.id].append(member.id)
else:
await self.bot.say(member.name + "#" + member.discriminator + \
" is already a moderator on this server.")
return
self.save_moderators()
await self.bot.say("Done.")
@commands.command(pass_context=True)
@checks.is_owner_or_server_owner()
async def add_moderator_id(self, ctx, member_id: str):
"""Adds a moderator for the server using his ID
Parameters:
member_id: The ID of the member that will become a moderator.
Example: [p]add_moderator_id 151661401411289088"""
member = discord.utils.find(lambda m: m.id == member_id, \
ctx.message.server.members)
if member:
if ctx.message.server.id not in self.bot.moderators:
self.bot.moderators[ctx.message.server.id] = [member.id]
else:
if member.id not in self.bot.moderators[ctx.message.server.id]:
self.bot.moderators[ctx.message.server.id].append(member.id)
else:
await self.bot.say(member.name + "#" + member.discriminator + \
" is already a moderator on this server.")
return
self.save_moderators()
await self.bot.say("Done.")
else:
await self.bot.say("There's no member with such ID on this server.")
@commands.command(pass_context=True)
@checks.is_owner_or_server_owner()
async def rem_moderator(self, ctx, moderator: discord.Member):
"""Removes a moderator
Parameters:
moderator: The moderator you want to revoke.
Example: [p]rem_moderator @Kazutsuki"""
if ctx.message.server.id in self.bot.moderators:
if moderator.id in self.bot.moderators[ctx.message.server.id]:
self.bot.moderators[ctx.message.server.id].remove(moderator.id)
if not self.bot.moderators[ctx.message.server.id]:
del self.bot.moderators[ctx.message.server.id]
self.save_moderators()
await self.bot.say("Done.")
else:
await self.bot.say(moderator.name + "#" + moderator.discriminator + \
" wasn't even a moderator on this server.")
else:
await self.bot.say("There's no moderators on this server.")
@commands.command(pass_context=True)
@checks.is_owner_or_server_owner()
async def rem_moderator_id(self, ctx, moderator_id: str):
"""Removes a moderator
Parameters:
moderator_id: The ID of the moderator you want to revoke.
Example: [p]rem_moderator_id 118473388262948869"""
moderator = discord.utils.find(lambda m: m.id == moderator_id, \
ctx.message.server.members)
if moderator:
if ctx.message.server.id in self.bot.moderators:
if moderator.id in self.bot.moderators[ctx.message.server.id]:
self.bot.moderators[ctx.message.server.id].remove(moderator.id)
if not self.bot.moderators[ctx.message.server.id]:
del self.bot.moderators[ctx.message.server.id]
self.save_moderators()
await self.bot.say("Done.")
else:
await self.bot.say(moderator.name + "#" + moderator.discriminator + \
" wasn't even a moderator on this server.")
else:
await self.bot.say("There's no moderators on this server.")
else:
await self.bot.say("There's no member with such ID on this server.")
@commands.command(pass_context=True)
@checks.is_owner_or_server_owner()
async def list_moderators(self, ctx):
"""Lists all the moderators on this server"""
if ctx.message.server.id in self.bot.moderators:
msg = "```Markdown\nModerators on this server\n========================\n\n"
has_unknown = False
i = 1
for mod_id in self.bot.moderators[ctx.message.server.id]:
msg += str(i) + ". "
moderator = discord.utils.find(lambda m, mod=mod_id: m.id == mod, \
ctx.message.server.members)
if moderator:
msg += moderator.name + "#" + moderator.discriminator + " (" + \
moderator.id + ")"
else:
msg += "Unknown moderator"
has_unknown = True
msg += "\n"
i += 1
msg += "```"
if has_unknown:
msg += "`Unknown` means that this moderator isn't on this server anymore."
await self.bot.say(msg)
else:
await self.bot.say("There's no moderators on this server.")
@commands.command()
@checks.is_owner()
async def list_blacklist(self):
"""Lists all the blacklisted users"""
if self.bot.blacklist:
msg = "```Markdown\nList of blacklisted users:\n=================\n\n"
i = 1
has_unknown = False
for user_id in self.bot.blacklist:
user = discord.utils.find(lambda u, u_id=user_id: u.id == u_id, \
self.bot.get_all_members())
msg += str(i) + ". "
if user:
msg += user.name + "#" + user.discriminator + " (" + user.id + ")\n"
else:
has_unknown = True
msg += "UNKNOWN USER\n"
i += 1
msg += "```"
if has_unknown:
msg += "\n`UNKNOWN USER` means that this user hasn't any server in " + \
"common with the bot."
await self.bot.say(msg)
else:
await self.bot.say("There is no blacklisted users.")
@commands.command(pass_context=True)
@checks.is_owner_or_server_owner()
async def set_log_channel(self, ctx, channel: discord.Channel=None):
"""Set's log channel for warn / mute / kick / ban commands
Parameters:
channel: The channel you want to set for the logs.
Leaving this blank will remove the channel for logs.abs
Example: [p]set_log_channel #logs-channel
[p]set_log_channel"""
bot = discord.utils.find(lambda m: m.id == self.bot.user.id, \
ctx.message.server.members)
if bot:
if channel:
permissions = channel.permissions_for(bot)
if permissions.send_messages:
if ctx.message.server.id in self.servers_config["servers"]:
self.servers_config["servers"][ctx.message.server.id]["log channel"] = channel #pylint: disable=line-too-long
else:
self.servers_config["servers"][ctx.message.server.id] = {"log channel": channel} #pylint: disable=line-too-long
self.save_servers_config()
await self.bot.say("Done. :ok_hand:")
else:
await self.bot.say("I'm not allowed to send messages there.\n" + \
"(Missing permissions)")
else:
if ctx.message.server.id in self.servers_config["servers"]:
del self.servers_config["servers"][ctx.message.server.id]["log channel"]
self.save_servers_config()
await self.bot.say("Done! :ok_hand:")
@commands.command(pass_context=True)
@checks.custom(is_owner_or_moderator)
async def show_log_channel(self, ctx):
"""Shows the log channel of the server"""
if ctx.message.server.id in self.servers_config["servers"] \
and "log channel" in self.servers_config["servers"][ctx.message.server.id]:
channel = self.servers_config["servers"][ctx.message.server.id]["log channel"]
await self.bot.say("Log channel: <#" + channel.id + ">")
else:
await self.bot.say("There's no log channel set on this server.")
@commands.command(pass_context=True)
@checks.custom(is_owner_or_moderator)
async def warn(self, ctx, member: discord.Member, *reason):
"""Warns a member
Parameters:
member: The member you want to warn.
*reason: The reason of the warning.
Example: [p]warn @BagGuy Rude words.
[p]warn @AnotherBadGuy"""
reason = " ".join(reason)
log = Log(log_type="Warning", member_id=member.id, \
responsible_id=ctx.message.author.id, reason=reason, \
date=datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
if ctx.message.server.id not in self.servers_config["servers"]:
self.servers_config["servers"][ctx.message.server.id] = {}
if "logs" not in self.servers_config["servers"][ctx.message.server.id]:
self.servers_config["servers"][ctx.message.server.id]["logs"] = {}
if member.id in self.servers_config["servers"][ctx.message.server.id]["logs"]:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id].append(log)
else:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id] = [log]
self.save_servers_config()
await self.send_log(server=ctx.message.server, log=log)
await self.bot.say("Done.")
@commands.command(pass_context=True)
@checks.custom(is_owner_or_moderator)
async def warn_id(self, ctx, member_id: str, *reason):
"""Warns a member
Parameters:
member_id: The ID of the member you want to warn.
*reason: The reason of the warning.
Example: [p]warn 346654353341546499 Rude words.
[p]warn 346654353341546499"""
member = discord.utils.find(lambda m: m.id == member_id, \
ctx.message.server.members)
if member:
reason = " ".join(reason)
log = Log(log_type="Warning", member_id=member.id, \
responsible_id=ctx.message.author.id, reason=reason, \
date=datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
if not ctx.message.server.id in self.servers_config["servers"]:
self.servers_config["servers"][ctx.message.server.id] = {}
if not "logs" in self.servers_config["servers"][ctx.message.server.id]:
self.servers_config["servers"][ctx.message.server.id]["logs"] = {}
if member.id in self.servers_config["servers"][ctx.message.server.id]["logs"]:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id].append(log)
else:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id] = [log]
self.save_servers_config()
await self.send_log(server=ctx.message.server, log=log)
await self.bot.say("Done.")
else:
await self.bot.say("There's no member with such ID on this server.")
@commands.command(pass_context=True)
@checks.custom(is_owner_or_moderator)
async def kick(self, ctx, member: discord.Member, *reason):
"""Kicks a member
Parameters:
member: The member you want to kick.
*reason: The reason of the kick.
Example: [p]kick @ABadGuy He was too rude.
[p]kick @AnotherBadGuy"""
try:
await self.bot.kick(member)
reason = " ".join(reason)
log = Log(log_type="Kick", member_id=member.id, responsible_id=ctx.message.author.id, \
reason=reason, date=datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
if not ctx.message.server.id in self.servers_config["servers"]:
self.servers_config["servers"][ctx.message.server.id] = {}
if not "logs" in self.servers_config["servers"][ctx.message.server.id]:
self.servers_config["servers"][ctx.message.server.id]["logs"] = {}
if member.id in self.servers_config["servers"][ctx.message.server.id]["logs"]:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id].append(log)
else:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id] = [log]
self.save_servers_config()
await self.send_log(server=ctx.message.server, log=log)
await self.bot.say("Done.")
except discord.Forbidden:
await self.bot.say("I'm not allowed to do that.\n" + \
"(Missing permissions)")
@commands.command(pass_context=True)
@checks.custom(is_owner_or_moderator)
async def kick_id(self, ctx, member_id: str, *reason):
"""Kicks a member using his ID
Parameters:
member_id: The ID of member you want to kick.
*reason: The reason of the kick.
Example: [p]kick_id 346654353341546499 Bad guy.
[p]kick_id 346654353341546499"""
try:
member = discord.utils.find(lambda m: m.id == member_id, \
ctx.message.server.members)
if member:
await self.bot.kick(member)
reason = " ".join(reason)
log = Log(log_type="Kick", member_id=member.id, \
responsible_id=ctx.message.author.id, \
reason=reason, date=datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
if not ctx.message.server.id in self.servers_config["servers"]:
self.servers_config["servers"][ctx.message.server.id] = {}
if not "logs" in self.servers_config["servers"][ctx.message.server.id]:
self.servers_config["servers"][ctx.message.server.id]["logs"] = {}
if member.id in self.servers_config["servers"][ctx.message.server.id]["logs"]:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id].append(log) #pylint: disable=line-too-long
else:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id] = [log]
self.save_servers_config()
await self.send_log(server=ctx.message.server, log=log)
await self.bot.say("Done.")
else:
await self.bot.say("There's no member with such ID " + \
"in this server.")
except discord.Forbidden:
await self.bot.say("I'm not allowed to do that.\n" + \
"(Missing permissions)")
@commands.command(pass_context=True)
@checks.custom(is_owner_or_moderator)
async def ban(self, ctx, member: discord.Member, days="0", *reason):
"""Bans a member
Parameters:
member: The member you want to ban from the server.
days: The number of days worth of messages to delete from the member in the server.
Default value: 0 (which means that no messages from the member will be deleted).
Note: The minimum is 0 and the maximum is 7.
*reason: The reason of the ban.
Example: [p]ban @AMeanMember 3 He was very mean!
[p]ban @AnotherMeanMember 4
[p]ban @AnotherMeanMember Spaming cute cat pics
[p]ban @AnotherMeanMember"""
try:
days = int(days)
to_add = ""
except ValueError:
to_add = days
days = 0
if days >= 0 and days <= 7:
try:
await self.bot.ban(member, days)
reason = to_add + " ".join(reason)
log = Log(log_type="Ban", member_id=member.id, \
responsible_id=ctx.message.author.id, \
reason=reason, date=datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
if not ctx.message.server.id in self.servers_config["servers"]:
self.servers_config["servers"][ctx.message.server.id] = {}
if not "logs" in self.servers_config["servers"][ctx.message.server.id]:
self.servers_config["servers"][ctx.message.server.id]["logs"] = {}
if member.id in self.servers_config["servers"][ctx.message.server.id]["logs"]:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id].append(log) #pylint: disable=line-too-long
else:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id] = [log]
self.save_servers_config()
await self.send_log(server=ctx.message.server, log=log)
await self.bot.say("Done.")
except discord.Forbidden:
await self.bot.say("I'm not allowed to do that.\n" + \
"(Missing permissions)")
else:
await self.bot.say("Incorrect days value.\n" + \
"The minimum is 0 and the maximum is 7.")
@commands.command(pass_context=True)
@checks.custom(is_owner_or_moderator)
async def ban_id(self, ctx, member_id: str, days="0", *reason):
"""Bans a member using his ID
Parameters:
member_id: The ID of the member you want to ban from the server.
days: The number of days worth of messages to delete from the member in the server.
Default value: 0 (which means that no messages from the member will be deleted).
Note: The minimum is 0 and the maximum is 7.
*reason: The reason of the ban.
Example: [p]ban_id 346654353341546499 3 Bad guy.
[p]ban_id 346654353341546499 He shouldn't be here.
[p]ban_id 346654353341546499 4.
[p]ban_id 346654353341546499"""
try:
days = int(days)
to_add = ""
except ValueError:
to_add = days
days = 0
if days >= 0 and days <= 7:
member = discord.utils.find(lambda m: m.id == member_id, \
ctx.message.server.members)
if member:
try:
await self.bot.ban(member, days)
reason = to_add + " ".join(reason)
log = Log(log_type="Ban", member_id=member.id, \
responsible_id=ctx.message.author.id, \
reason=reason, date=datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
if not ctx.message.server.id in self.servers_config["servers"]:
self.servers_config["servers"][ctx.message.server.id] = {}
if not "logs" in self.servers_config["servers"][ctx.message.server.id]:
self.servers_config["servers"][ctx.message.server.id]["logs"] = {}
if member.id in self.servers_config["servers"][ctx.message.server.id]["logs"]:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id].append(log) #pylint: disable=line-too-long
else:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id] = [log] #pylint: disable=line-too-long
self.save_servers_config()
await self.send_log(server=ctx.message.server, log=log)
await self.bot.say("Done.")
except discord.Forbidden:
await self.bot.say("I'm not allowed to do that.\n" + \
"(Missing permissions)")
else:
await self.bot.say("There's no member with such ID on this server.\n" + \
"You may be interested in the `[p]b1nzy_ban` command.")
else:
await self.bot.say("Incorrect days value.\n" + \
"The minimum is 0 and the maximum is 7.")
@commands.command(pass_context=True)
@checks.custom(is_owner_or_moderator)
async def b1nzy_ban(self, ctx, member_id: str, *reason):
"""Bans a member even if he's not on the server, using his ID
Parameters:
member_id: The ID of the member you want to ban.
*reason: The reason of the ban.
Example: [p]b1nzy_ban 346654353341546499 Bad guy.
[p]b1nzy_ban 346654353341546499
Note: How does it works?
If the member left the server to avoid the ban hammer, you
can still use this command on him. He actually wouldn't be
banned but as soon as he would come to the server again, he
would be instantanely banned"""
member = discord.utils.find(lambda m: m.id == member_id, \
ctx.message.server.members)
reason = " ".join(reason)
if member:
try:
await self.bot.ban(member)
except discord.Forbidden:
await self.bot.say("I'm not allowed to do that.\n" + \
"(Missing permissions)")
else:
if not ctx.message.server.id in self.b1nzy_banlist:
self.b1nzy_banlist[ctx.message.server.id] = []
if not member_id in self.b1nzy_banlist[ctx.message.server.id]:
self.b1nzy_banlist[ctx.message.server.id].append(member_id)
self.save_b1nzy_banlist()
else:
await self.bot.say("This user was already in the b1nzy banlist.")
return
log = Log(log_type="b1nzy ban", member_id=member_id, responsible_id=ctx.message.author.id, \
reason=reason, date=datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
if not ctx.message.server.id in self.servers_config["servers"]:
self.servers_config["servers"][ctx.message.server.id] = {}
if not "logs" in self.servers_config["servers"][ctx.message.server.id]:
self.servers_config["servers"][ctx.message.server.id]["logs"] = {}
if member_id in self.servers_config["servers"][ctx.message.server.id]["logs"]:
self.servers_config["servers"][ctx.message.server.id]["logs"][member_id].append(log) #pylint: disable=line-too-long
else:
self.servers_config["servers"][ctx.message.server.id]["logs"][member_id] = [log] #pylint: disable=line-too-long
self.save_servers_config()
await self.send_log(server=ctx.message.server, log=log)
await self.bot.say("Done.")
@commands.command(pass_context=True)
@checks.custom(is_owner_or_moderator)
async def unban(self, ctx, member: str, *reason):
"""Unbans a member
Parameters:
member: The member you want to unban from this server.
The format of this argument is Username#discriminator (see example).
*reason: The reason of the unban.
Example: [p]unban I'm not mean after all#1234
[p]unban AnInnocent#1234 He wasn't that mean."""
member_info = member.split("#")
if len(member_info) == 2:
try:
banned_members = await self.bot.get_bans(ctx.message.server)
for banned in banned_members:
if banned.name == member_info[0] \
and banned.discriminator == member_info[1]:
member = banned
break
if member:
await self.bot.unban(ctx.message.server, member)
reason = " ".join(reason)
log = Log(log_type="Unban", member_id=member.id, \
responsible_id=ctx.message.author.id, \
reason=reason, date=datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
if not ctx.message.server.id in self.servers_config["servers"]:
self.servers_config["servers"][ctx.message.server.id] = {}
if not "logs" in self.servers_config["servers"][ctx.message.server.id]:
self.servers_config["servers"][ctx.message.server.id]["logs"] = {}
if member.id in self.servers_config["servers"][ctx.message.server.id]["logs"]:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id].append(log) #pylint: disable=line-too-long
else:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id] = [log] #pylint: disable=line-too-long
self.save_servers_config()
await self.send_log(server=ctx.message.server, log=log)
await self.bot.say("Done.")
else:
await self.bot.say("This user wasn't even banned here.")
except discord.Forbidden:
await self.bot.say("I'm not allowed to do that.\n" + \
"(Missing permissions")
else:
await self.bot.say("Incorrect format. Please check `[p]help unban`.")
@commands.command(pass_context=True)
@checks.custom(is_owner_or_moderator)
async def unban_id(self, ctx, member_id: str, *reason):
"""Unbans a member using his ID
Parameters:
member_id: The ID of the member you want to unban from this server.
*reason: The reason of the unban.
Example: [p]unban_id 151661401411289088 I shouldn't have banned him, he's too cool.
[p]unban_id 151661401411289088"""
try:
banned = await self.bot.get_bans(ctx.message.server)
member = discord.utils.find(lambda u: u.id == member_id, banned)
if member:
await self.bot.unban(ctx.message.server, member)
reason = " ".join(reason)
log = Log(log_type="Unban", member_id=member.id, \
responsible_id=ctx.message.author.id, \
reason=reason, date=datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
if not ctx.message.server.id in self.servers_config["servers"]:
self.servers_config["servers"][ctx.message.server.id] = {}
if not "logs" in self.servers_config["servers"][ctx.message.server.id]:
self.servers_config["servers"][ctx.message.server.id]["logs"] = {}
if member.id in self.servers_config["servers"][ctx.message.server.id]["logs"]:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id].append(log) #pylint: disable=line-too-long
else:
self.servers_config["servers"][ctx.message.server.id]["logs"][member.id] = [log]
self.save_servers_config()
await self.send_log(server=ctx.message.server, log=log)
await self.bot.say("Done.")
else:
await self.bot.say("This user wasn't even banned here.")
except discord.Forbidden:
await self.bot.say("I'm not allowed to do that.\n" + \
"(Missing permissions")
@commands.command(pass_context=True)
@checks.custom(is_owner_or_moderator)
async def list_logs(self, ctx, member: discord.Member):
"""Lists all the logs for a member of the server
Parameters:
member: The member you want to get the logs from.
Example: [p]list_logs @Beafantles"""
if ctx.message.server.id in self.servers_config["servers"] \
and "logs" in self.servers_config["servers"][ctx.message.server.id] \
and member.id in self.servers_config["servers"][ctx.message.server.id]["logs"]:
msg = "```Markdown\nLogs for " + member.name + "#" + member.discriminator + \
"\n========================\n\n"
i = 1
for log in self.servers_config["servers"][ctx.message.server.id]["logs"][member.id]:
msg += str(i) + ". " + log.type + "\n"
msg += "\tCase#" + str(log.log_id) + "\n"
msg += "\tResponsible: " + log.responsible.name + "#" + log.responsible.discriminator + " (" + log.responsible.id + ")\n" #pylint: disable=line-too-long
msg += "\tReason: " + log.reason + "\n"
msg += "\tDate: " + log.date + "\n\n"
i += 1
msg += "```"
await self.bot.say(msg)
else:
await self.bot.say("No logs found for " + member.name + "#" + \
member.discriminator + " in this server.")
@commands.command(pass_context=True)
@checks.custom(is_owner_or_moderator)
async def list_logs_id(self, ctx, member_id: str):
"""Lists all the logs for a member of the server using his ID
Parameters:
member_id: The ID of the member you want to get the logs from.
Example: [p]list_logs_id 151661401411289088"""
member = discord.utils.find(lambda m: m.id == member_id, \
self.bot.get_all_members())
if member:
if ctx.message.server.id in self.servers_config \
and "logs" in self.servers_config["servers"][ctx.message.server.id] \
and member.id in self.servers_config["servers"][ctx.message.server.id]["logs"]:
msg = "```Markdown\nLogs for " + member.name + "#" + member.discriminator + \
"\n========================\n\n"
i = 1
for log in self.servers_config["servers"][ctx.message.server.id]["logs"][member.id]:
msg += str(i) + ". " + log.type + "\n"
msg += "\tCase#" + str(log.log_id) + "\n"
msg += "\tResponsible: " + log.responsible.name + "#" + log.responsible.discriminator + " (" + log.responsible.id + ")\n" #pylint: disable=line-too-long
msg += "\tReason: " + log.reason + "\n"
msg += "\tDate: " + log.date + "\n\n"
i += 1
msg += "```"
await self.bot.say(msg)
else:
await self.bot.say("No logs found for " + member.name + "#" + \
member.discriminator + " in this server.")
else:
await self.bot.say("There's no member with such ID on this server.")
async def check_new_comers(self, member):
"""Checks if a new comer is in the b1nzy banlist"""
if member.server.id in self.b1nzy_banlist:
if member.id in self.b1nzy_banlist[member.server.id]:
try:
await self.bot.ban(member)
self.b1nzy_banlist[member.server.id].remove(member.id)
if not self.b1nzy_banlist[member.server.id]:
del self.b1nzy_banlist[member.server.id]
self.save_b1nzy_banlist()
except discord.Forbidden:
await self.bot.send_message(member.server.owner, \
"Couldn't ban " + member.name + "#" + member.discriminator + \
" (" + member.id + ") who's in the b1nzy banlist --> missing permissions")
except discord.HTTPException:
pass
def setup(bot):
"""Setup function"""
mod = Admin(bot)
bot.add_listener(mod.check_new_comers, "on_member_join")
bot.add_cog(mod)
| {
"repo_name": "Beafantles/Asurix-bot",
"path": "modules/admin.py",
"copies": "1",
"size": "44135",
"license": "mit",
"hash": 3211854422763155000,
"line_mean": 47.0773420479,
"line_max": 172,
"alpha_frac": 0.543582191,
"autogenerated": false,
"ratio": 3.948380747897656,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9967249507639814,
"avg_score": 0.004942686251568408,
"num_lines": 918
} |
"""Admin module.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
from ldap3.core import exceptions as ldap_exceptions
from . import exc
_LOGGER = logging.getLogger(__name__)
# Note: All the following code is for backward compatibility only.
# Once all usage is updated to the new API, _wrap_excs should be moved
# to _ldap and everything else should be removed.
def Partition(backend):
"""Fake constructor for backward compatiblity.
"""
# pylint: disable=invalid-name
_LOGGER.debug('Using deprecated admin interface.')
return backend.partition()
def Allocation(backend):
"""Fake constructor for backward compatiblity.
"""
# pylint: disable=invalid-name
_LOGGER.debug('Using deprecated admin interface.')
return backend.allocation()
def CellAllocation(backend):
"""Fake constructor for backward compatiblity.
"""
# pylint: disable=invalid-name
_LOGGER.debug('Using deprecated admin interface.')
return backend.cell_allocation()
def Tenant(backend):
"""Fake constructor for backward compatiblity.
"""
# pylint: disable=invalid-name
_LOGGER.debug('Using deprecated admin interface.')
return backend.tenant()
def Cell(backend):
"""Fake constructor for backward compatiblity.
"""
# pylint: disable=invalid-name
_LOGGER.debug('Using deprecated admin interface.')
return backend.cell()
def Server(backend):
"""Fake constructor for backward compatiblity.
"""
# pylint: disable=invalid-name
_LOGGER.debug('Using deprecated admin interface.')
return backend.server()
def Application(backend):
"""Fake constructor for backward compatiblity.
"""
# pylint: disable=invalid-name
_LOGGER.debug('Using deprecated admin interface.')
return backend.application()
def AppGroup(backend):
"""Fake constructor for backward compatiblity.
"""
# pylint: disable=invalid-name
_LOGGER.debug('Using deprecated admin interface.')
return backend.app_group()
def DNS(backend):
"""Fake constructor for backward compatiblity.
"""
# pylint: disable=invalid-name
_LOGGER.debug('Using deprecated admin interface.')
return backend.dns()
def _wrap_excs(func):
"""Decorator to transform LDAP exceptions to Admin exceptions."""
def wrapper(*args, **kwargs):
"""Wrapper that does the exception translation."""
try:
return func(*args, **kwargs)
except ldap_exceptions.LDAPNoSuchObjectResult as err:
raise exc.NoSuchObjectResult(err)
except ldap_exceptions.LDAPEntryAlreadyExistsResult as err:
raise exc.AlreadyExistsResult(err)
except ldap_exceptions.LDAPBindError as err:
raise exc.AdminConnectionError(err)
except ldap_exceptions.LDAPInsufficientAccessRightsResult as err:
raise exc.AdminAuthorizationError(err)
except ldap_exceptions.LDAPOperationResult as err:
raise exc.AdminBackendError(err)
return wrapper
class WrappedAdmin():
"""Wrap the interface methods of _ldap.Admin to raise backend
exceptions.
"""
def __init__(self, conn):
self._conn = conn
def dn(self, ident):
"""Constructs dn."""
# pylint: disable=invalid-name
return self._conn.dn(ident)
@_wrap_excs
def get(self, entry_dn, query, attrs, **kwargs):
"""Gets LDAP object given dn."""
return self._conn.get(entry_dn, query, attrs, **kwargs)
@_wrap_excs
def paged_search(self, search_base, search_filter, **kwargs):
"""Call ldap paged search and return a generator of dn, entry tuples.
"""
return self._conn.paged_search(search_base, search_filter, **kwargs)
@_wrap_excs
def create(self, entry_dn, entry):
"""Creates LDAP record."""
return self._conn.create(entry_dn, entry)
@_wrap_excs
def update(self, entry_dn, entry):
"""Updates LDAP record."""
return self._conn.update(entry_dn, entry)
@_wrap_excs
def remove(self, entry_dn, entry):
"""Removes attributes from the record."""
return self._conn.remove(entry_dn, entry)
@_wrap_excs
def delete(self, entry_dn):
"""Call ldap delete and raise exception on non-success."""
return self._conn.delete(entry_dn)
| {
"repo_name": "Morgan-Stanley/treadmill",
"path": "lib/python/treadmill/admin/__init__.py",
"copies": "2",
"size": "4461",
"license": "apache-2.0",
"hash": -3995137862969721000,
"line_mean": 27.5961538462,
"line_max": 77,
"alpha_frac": 0.6675633266,
"autogenerated": false,
"ratio": 4.192669172932331,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 156
} |
# admin
from django.contrib import admin
admin.autodiscover()
# urls
from django.conf.urls import patterns, include, url
from accounts.views import SignupView, SignupViewAjax, LoginView, LoginViewAjax
urlpatterns = patterns(
'',
url(r'^', include('home.urls')),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
url(r'^photos/', include('photos.urls')),
url(r'^bsdfs/', include('bsdfs.urls')),
url(r'^normals/', include('normals.urls')),
url(r'^shapes/', include('shapes.urls')),
url(r'^mturk/', include('mturk.urls')),
url(r'^analytics/', include('analytics.urls')),
url(r'^intrinsic/', include('intrinsic.urls')),
url(r'^accounts/', include('accounts.urls')),
# django-user-accounts with some custom modifications
url(r'^account/signup/$', SignupView.as_view(), name='account_signup'),
url(r'^account/login/$', LoginView.as_view(), name='account_login'),
url(r'^account/signup-ajax/$', SignupViewAjax.as_view(), name='account_signup_ajax'),
url(r'^account/login-ajax/$', LoginViewAjax.as_view(), name='account_login_ajax'),
url(r'^account/', include('account.urls')),
# captcha
url(r'^captcha/', include('captcha.urls')),
)
# media files
from django.conf.urls.static import static
from django.conf import settings
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# static files
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
# necessary workaround for correclty displaying error 500 pages
# see:
# https://github.com/jezdez/django_compressor/pull/206
# and:
# http://stackoverflow.com/questions/13633508/django-handler500-as-a-class-based-view
from common.views import Handler500
handler500 = Handler500.as_error_view()
| {
"repo_name": "seanbell/opensurfaces",
"path": "server/config/urls.py",
"copies": "1",
"size": "1910",
"license": "mit",
"hash": -4642386893237938000,
"line_mean": 37.9795918367,
"line_max": 89,
"alpha_frac": 0.7041884817,
"autogenerated": false,
"ratio": 3.4790528233151186,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9667896546076069,
"avg_score": 0.0030689517878098203,
"num_lines": 49
} |
# admin
import models
from django.contrib import admin
from django.contrib.auth.decorators import permission_required
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import redirect, render_to_response, render
import logging
logger = logging.getLogger("simcon")
admin.site.disable_action('delete_selected') # remove the default delete site-wide
# Custom model admins
# Note: flat admin may handle our mockups better
# TODO: filter templates, responses, etc by user ownership, so they can only see things they own
class TemplateAdmin(admin.ModelAdmin):
actions = ['edit_template', 'share_template', 'generate_link', 'delete_template']
def edit_template(self, request, queryset):
"Edit the selected template"
if not queryset or queryset.count() != 1: #We can edit only 1 template
self.message_user(request, "Can't edit more than 1 template at a time")
else:
temp = queryset[0]
if not request.user.is_superuser and temp.researcherID != request.user:
self.message_user(request, "Can't edit that, you don't own it")
else:
#self.message_user(request, "Edit template %s with %d items" % (request.user.username, queryset.count()))
#self.message_user(request, "Editing template!")
#TODO pump queryset into session, tag to add a version incrementation, maybe have a template id variable?
#return render(request, 'template-wizard.html', {"template_to_edit": temp.templateID})
return HttpResponseRedirect(reverse('simcon.views.TemplateDelete'), args=1)#(temp.templateID))
edit_template.short_description = "Edit template"
def delete_template(self, request, queryset):
"Edit the selected template"
if not queryset or queryset.count() != 1:
self.message_user(request, "Can't delete more than 1 template at a time")
else:
temp = queryset[0]
if not request.user.is_superuser and temp.researcherID != request.user:
self.message_user(request, "Can't delete that, you don't own it")
else:
#self.message_user(request, "Edit template %s with %d items" % (request.user.username, queryset.count()))
#self.message_user(request, "Editing template!")
#TODO pump queryset into session, tag to add a version incrementation, maybe have a template id variable?
return render(request, 'template-delete.html', {"template_to_delete": temp.templateID})
delete_template.short_description = "Delete template"
def share_template(self, request, queryset):
"Share the selected template(s)"
if not queryset or queryset.count() != 1:
self.message_user(request, "Can't share more than 1 template at a time") #TODO maybe we do?
else:
temp = queryset[0]
if not request.user.is_superuser and temp.researcherID != request.user:
self.message_user(request, "Can't share that, you don't own it")
else:
self.message_user(request, "Not implemented")
share_template.short_description = "Share these templates"
def generate_link(self, request, queryset):
"Generate a link for the selected template(s)"
if not queryset or queryset.count() != 1:
self.message_user(request, "Can't generate more than 1 link at a time") #TODO maybe we do?
else:
temp = queryset[0]
if not request.user.is_superuser and temp.researcherID != request.user:
self.message_user(request, "Can't generate link for that, you don't own it")
else:
self.message_user(request, "Not implemented")
generate_link.short_description = "Generate a link"
# register models and modeladmins
admin.site.register(models.Template, TemplateAdmin)
#temporarily adding all
admin.site.register(models.Conversation)
admin.site.register(models.SharedResponses)
admin.site.register(models.StudentAccess)
admin.site.register(models.PageInstance)
admin.site.register(models.TemplateResponseRel)
admin.site.register(models.TemplateFlowRel)
| {
"repo_name": "djorda9/Simulated-Conversations",
"path": "vagrant/simcon/admin.py",
"copies": "1",
"size": "4415",
"license": "mit",
"hash": 4495000576281495000,
"line_mean": 46.4731182796,
"line_max": 121,
"alpha_frac": 0.6629671574,
"autogenerated": false,
"ratio": 4.253371868978806,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5416339026378806,
"avg_score": null,
"num_lines": null
} |
"""Admin."""
import datetime
from django.contrib import admin
from classes.models import Class
from classes.models import Location
from classes.models import ClassSession
from classes.models import ClassSessionNotification
from rest_framework.authtoken.admin import TokenAdmin
def pad_class_day(item, loop_date):
"""Create session for day."""
new_start = datetime.datetime(
loop_date.year,
loop_date.month,
loop_date.day,
item.start_hours,
item.start_minutes,
0
)
new_end = datetime.datetime(
loop_date.year,
loop_date.month,
loop_date.day,
item.end_hours,
item.end_minutes,
0
)
if ClassSession.objects.filter(parent_class=item, session_start=new_start, session_end=new_end).count() == 0:
new_session = ClassSession()
new_session.parent_class = item
new_session.session_start = new_start
new_session.session_end = new_end
new_session.save()
def pad_class_range(item):
"""Create some sessions for a class."""
date_start = datetime.date.today()
date_end = date_start + datetime.timedelta(days=30)
if not item.recurring:
date_start = item.sessions_start
date_end = item.sessions_end
loop_date = date_start
while loop_date < date_end:
weekday = loop_date.weekday()
if weekday == item.day:
pad_class_day(item, loop_date)
loop_date += datetime.timedelta(days=1)
def create_sessions(modeladmin, request, queryset):
"""Create sessions for a range of classes."""
for item in queryset:
pad_class_range(item)
create_sessions.short_description = 'Create sessions'
class ClassAdmin(admin.ModelAdmin):
"""Admin definition for class."""
actions = [
create_sessions
]
class ClassSessionAdmin(admin.ModelAdmin):
"""Admin definitions for classSession."""
list_display = (
'parent_class',
'session_day',
'start_time',
'end_time',
)
admin.site.register(Class, ClassAdmin)
admin.site.register(ClassSession, ClassSessionAdmin)
admin.site.register(Location)
admin.site.register(ClassSessionNotification)
TokenAdmin.raw_id_fields = ('user',)
| {
"repo_name": "CornerstoneLabs/club-prototype",
"path": "app-server/classes/admin.py",
"copies": "1",
"size": "2257",
"license": "mit",
"hash": -5120793634238570000,
"line_mean": 23.8021978022,
"line_max": 113,
"alpha_frac": 0.6530793088,
"autogenerated": false,
"ratio": 3.8189509306260576,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49720302394260574,
"avg_score": null,
"num_lines": null
} |
"""Admin of Zinnia CMS Plugins"""
from django.contrib import admin
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from cms.plugin_rendering import render_placeholder
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from zinnia.models import Entry
from zinnia.admin.entry import EntryAdmin
from zinnia.settings import ENTRY_BASE_MODEL
class EntryPlaceholderAdmin(PlaceholderAdminMixin, EntryAdmin):
"""
EntryPlaceholder Admin
"""
fieldsets = (
(_('Content'), {'fields': (('title', 'status'), 'image')}),) + \
EntryAdmin.fieldsets[1:]
def save_model(self, request, entry, form, change):
"""
Fill the content field with the interpretation
of the placeholder
"""
context = RequestContext(request)
try:
content = render_placeholder(entry.content_placeholder, context)
entry.content = content or ''
except KeyError:
# https://github.com/django-blog-zinnia/cmsplugin-zinnia/pull/61
entry.content = ''
super(EntryPlaceholderAdmin, self).save_model(
request, entry, form, change)
if ENTRY_BASE_MODEL == 'cmsplugin_zinnia.placeholder.EntryPlaceholder':
admin.site.register(Entry, EntryPlaceholderAdmin)
| {
"repo_name": "bittner/cmsplugin-zinnia",
"path": "cmsplugin_zinnia/admin.py",
"copies": "2",
"size": "1328",
"license": "bsd-3-clause",
"hash": 5740505704663000000,
"line_mean": 33.0512820513,
"line_max": 76,
"alpha_frac": 0.6859939759,
"autogenerated": false,
"ratio": 4.215873015873016,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5901866991773016,
"avg_score": null,
"num_lines": null
} |
""" Admin page configuration for the users app """
# django
from django.contrib import admin
from django.contrib import messages
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _
# models
from users.models import User
# forms
from users.forms import UserCreationForm
from users.forms import UserChangeForm
def force_logout(modeladmin, request, queryset):
for user in queryset:
user.force_logout()
# TODO add log to register this action
messages.add_message(request, messages.SUCCESS,
_("Selected users where logged out"))
force_logout.short_description = _("Logs out the user from all devices")
class UserAdmin(DjangoUserAdmin):
""" Configuration for the User admin page"""
add_form_template = 'admin/users/user/add_form.html'
change_form_template = 'loginas/change_form.html'
add_form = UserCreationForm
list_display = ('email', 'first_name', 'last_name', 'is_staff',
'change_password_link')
form = UserChangeForm
search_fields = ('first_name', 'last_name', 'email')
list_filter = ('last_login',)
fieldsets = (
(None, {'fields': ('email',)}),
(_('Personal info'), {'fields': ('first_name', 'last_name')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'first_name', 'last_name', 'password1',
'password2')}
),
)
ordering = ('email',)
def change_password_link(self, obj):
return format_html(
f'<a href="{obj.id}/password/">{_("change password")}</a>'
)
change_password_link.allow_tags = True
change_password_link.short_description = _("change password")
admin.site.register(User, UserAdmin)
| {
"repo_name": "magnet-cl/django-project-template-py3",
"path": "users/admin.py",
"copies": "1",
"size": "2112",
"license": "mit",
"hash": -6880391626614055000,
"line_mean": 29.6086956522,
"line_max": 79,
"alpha_frac": 0.6136363636,
"autogenerated": false,
"ratio": 3.992438563327032,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5106074926927032,
"avg_score": null,
"num_lines": null
} |
#Admin page finder / Trazilac web stranica. Program napravljen za Hash Craze.
#Program napravio gh0stf0x.
import httplib
import socket
import sys
try:
print "\t||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
print "\t /*******Admin Page Finder*******\ "
print "\t||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
print "\t Hash Craze - Anonymous Balkan "
print "\t||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
print "\t||Program napravio - gh0stf0x|||||||||||||||||||||||||||||||||||"
var1=0
var2=0
php = ['admin/','administrator/','admin1/','admin2/','admin3/','admin4/','admin5/','usuarios/','usuario/','administrator/','moderator/','webadmin/','adminarea/','bb-admin/','adminLogin/','admin_area/','panel-administracion/','instadmin/',
'memberadmin/','administratorlogin/','adm/','admin/account.php','admin/index.php','admin/login.php','admin/admin.php','admin/account.php',
'admin_area/admin.php','admin_area/login.php','siteadmin/login.php','siteadmin/index.php','siteadmin/login.html','admin/account.html','admin/index.html','admin/login.html','admin/admin.html',
'admin_area/index.php','bb-admin/index.php','bb-admin/login.php','bb-admin/admin.php','admin/home.php','admin_area/login.html','admin_area/index.html',
'admin/controlpanel.php','admin.php','admincp/index.asp','admincp/login.asp','admincp/index.html','admin/account.html','adminpanel.html','webadmin.html',
'webadmin/index.html','webadmin/admin.html','webadmin/login.html','admin/admin_login.html','admin_login.html','panel-administracion/login.html',
'admin/cp.php','cp.php','administrator/index.php','administrator/login.php','nsw/admin/login.php','webadmin/login.php','admin/admin_login.php','admin_login.php',
'administrator/account.php','administrator.php','admin_area/admin.html','pages/admin/admin-login.php','admin/admin-login.php','admin-login.php',
'bb-admin/index.html','bb-admin/login.html','acceso.php','bb-admin/admin.html','admin/home.html','login.php','modelsearch/login.php','moderator.php','moderator/login.php',
'moderator/admin.php','account.php','pages/admin/admin-login.html','admin/admin-login.html','admin-login.html','controlpanel.php','admincontrol.php',
'admin/adminLogin.html','adminLogin.html','admin/adminLogin.html','home.html','rcjakar/admin/login.php','adminarea/index.html','adminarea/admin.html',
'webadmin.php','webadmin/index.php','webadmin/admin.php','admin/controlpanel.html','admin.html','admin/cp.html','cp.html','adminpanel.php','moderator.html',
'administrator/index.html','administrator/login.html','user.html','administrator/account.html','administrator.html','login.html','modelsearch/login.html',
'moderator/login.html','adminarea/login.html','panel-administracion/index.html','panel-administracion/admin.html','modelsearch/index.html','modelsearch/admin.html',
'admincontrol/login.html','adm/index.html','adm.html','moderator/admin.html','user.php','account.html','controlpanel.html','admincontrol.html',
'panel-administracion/login.php','wp-login.php','adminLogin.php','admin/adminLogin.php','home.php','admin.php','adminarea/index.php',
'adminarea/admin.php','adminarea/login.php','panel-administracion/index.php','panel-administracion/admin.php','modelsearch/index.php',
'modelsearch/admin.php','admincontrol/login.php','adm/admloginuser.php','admloginuser.php','admin2.php','admin2/login.php','admin2/index.php','usuarios/login.php',
'adm/index.php','adm.php','affiliate.php','adm_auth.php','memberadmin.php','administratorlogin.php']
asp = ['admin/','administrator/','admin1/','admin2/','admin3/','admin4/','admin5/','moderator/','webadmin/','adminarea/','bb-admin/','adminLogin/','admin_area/','panel-administracion/','instadmin/',
'memberadmin/','administratorlogin/','adm/','account.asp','admin/account.asp','admin/index.asp','admin/login.asp','admin/admin.asp',
'admin_area/admin.asp','admin_area/login.asp','admin/account.html','admin/index.html','admin/login.html','admin/admin.html',
'admin_area/admin.html','admin_area/login.html','admin_area/index.html','admin_area/index.asp','bb-admin/index.asp','bb-admin/login.asp','bb-admin/admin.asp',
'bb-admin/index.html','bb-admin/login.html','bb-admin/admin.html','admin/home.html','admin/controlpanel.html','admin.html','admin/cp.html','cp.html',
'administrator/index.html','administrator/login.html','administrator/account.html','administrator.html','login.html','modelsearch/login.html','moderator.html',
'moderator/login.html','moderator/admin.html','account.html','controlpanel.html','admincontrol.html','admin_login.html','panel-administracion/login.html',
'admin/home.asp','admin/controlpanel.asp','admin.asp','pages/admin/admin-login.asp','admin/admin-login.asp','admin-login.asp','admin/cp.asp','cp.asp',
'administrator/account.asp','administrator.asp','acceso.asp','login.asp','modelsearch/login.asp','moderator.asp','moderator/login.asp','administrator/login.asp',
'moderator/admin.asp','controlpanel.asp','admin/account.html','adminpanel.html','webadmin.html','pages/admin/admin-login.html','admin/admin-login.html',
'webadmin/index.html','webadmin/admin.html','webadmin/login.html','user.asp','user.html','admincp/index.asp','admincp/login.asp','admincp/index.html',
'admin/adminLogin.html','adminLogin.html','admin/adminLogin.html','home.html','adminarea/index.html','adminarea/admin.html','adminarea/login.html',
'panel-administracion/index.html','panel-administracion/admin.html','modelsearch/index.html','modelsearch/admin.html','admin/admin_login.html',
'admincontrol/login.html','adm/index.html','adm.html','admincontrol.asp','admin/account.asp','adminpanel.asp','webadmin.asp','webadmin/index.asp',
'webadmin/admin.asp','webadmin/login.asp','admin/admin_login.asp','admin_login.asp','panel-administracion/login.asp','adminLogin.asp',
'admin/adminLogin.asp','home.asp','admin.asp','adminarea/index.asp','adminarea/admin.asp','adminarea/login.asp','admin-login.html',
'panel-administracion/index.asp','panel-administracion/admin.asp','modelsearch/index.asp','modelsearch/admin.asp','administrator/index.asp',
'admincontrol/login.asp','adm/admloginuser.asp','admloginuser.asp','admin2.asp','admin2/login.asp','admin2/index.asp','adm/index.asp',
'adm.asp','affiliate.asp','adm_auth.asp','memberadmin.asp','administratorlogin.asp','siteadmin/login.asp','siteadmin/index.asp','siteadmin/login.html']
cfm = ['admin/','administrator/','admin1/','admin2/','admin3/','admin4/','admin5/','usuarios/','usuario/','administrator/','moderator/','webadmin/','adminarea/','bb-admin/','adminLogin/','admin_area/','panel-administracion/','instadmin/',
'memberadmin/','administratorlogin/','adm/','admin/account.cfm','admin/index.cfm','admin/login.cfm','admin/admin.cfm','admin/account.cfm',
'admin_area/admin.cfm','admin_area/login.cfm','siteadmin/login.cfm','siteadmin/index.cfm','siteadmin/login.html','admin/account.html','admin/index.html','admin/login.html','admin/admin.html',
'admin_area/index.cfm','bb-admin/index.cfm','bb-admin/login.cfm','bb-admin/admin.cfm','admin/home.cfm','admin_area/login.html','admin_area/index.html',
'admin/controlpanel.cfm','admin.cfm','admincp/index.asp','admincp/login.asp','admincp/index.html','admin/account.html','adminpanel.html','webadmin.html',
'webadmin/index.html','webadmin/admin.html','webadmin/login.html','admin/admin_login.html','admin_login.html','panel-administracion/login.html',
'admin/cp.cfm','cp.cfm','administrator/index.cfm','administrator/login.cfm','nsw/admin/login.cfm','webadmin/login.cfm','admin/admin_login.cfm','admin_login.cfm',
'administrator/account.cfm','administrator.cfm','admin_area/admin.html','pages/admin/admin-login.cfm','admin/admin-login.cfm','admin-login.cfm',
'bb-admin/index.html','bb-admin/login.html','bb-admin/admin.html','admin/home.html','login.cfm','modelsearch/login.cfm','moderator.cfm','moderator/login.cfm',
'moderator/admin.cfm','account.cfm','pages/admin/admin-login.html','admin/admin-login.html','admin-login.html','controlpanel.cfm','admincontrol.cfm',
'admin/adminLogin.html','acceso.cfm','adminLogin.html','admin/adminLogin.html','home.html','rcjakar/admin/login.cfm','adminarea/index.html','adminarea/admin.html',
'webadmin.cfm','webadmin/index.cfm','webadmin/admin.cfm','admin/controlpanel.html','admin.html','admin/cp.html','cp.html','adminpanel.cfm','moderator.html',
'administrator/index.html','administrator/login.html','user.html','administrator/account.html','administrator.html','login.html','modelsearch/login.html',
'moderator/login.html','adminarea/login.html','panel-administracion/index.html','panel-administracion/admin.html','modelsearch/index.html','modelsearch/admin.html',
'admincontrol/login.html','adm/index.html','adm.html','moderator/admin.html','user.cfm','account.html','controlpanel.html','admincontrol.html',
'panel-administracion/login.cfm','wp-login.cfm','adminLogin.cfm','admin/adminLogin.cfm','home.cfm','admin.cfm','adminarea/index.cfm',
'adminarea/admin.cfm','adminarea/login.cfm','panel-administracion/index.cfm','panel-administracion/admin.cfm','modelsearch/index.cfm',
'modelsearch/admin.cfm','admincontrol/login.cfm','adm/admloginuser.cfm','admloginuser.cfm','admin2.cfm','admin2/login.cfm','admin2/index.cfm','usuarios/login.cfm',
'adm/index.cfm','adm.cfm','affiliate.cfm','adm_auth.cfm','memberadmin.cfm','administratorlogin.cfm']
js = ['admin/','administrator/','admin1/','admin2/','admin3/','admin4/','admin5/','usuarios/','usuario/','administrator/','moderator/','webadmin/','adminarea/','bb-admin/','adminLogin/','admin_area/','panel-administracion/','instadmin/',
'memberadmin/','administratorlogin/','adm/','admin/account.js','admin/index.js','admin/login.js','admin/admin.js','admin/account.js',
'admin_area/admin.js','admin_area/login.js','siteadmin/login.js','siteadmin/index.js','siteadmin/login.html','admin/account.html','admin/index.html','admin/login.html','admin/admin.html',
'admin_area/index.js','bb-admin/index.js','bb-admin/login.js','bb-admin/admin.js','admin/home.js','admin_area/login.html','admin_area/index.html',
'admin/controlpanel.js','admin.js','admincp/index.asp','admincp/login.asp','admincp/index.html','admin/account.html','adminpanel.html','webadmin.html',
'webadmin/index.html','webadmin/admin.html','webadmin/login.html','admin/admin_login.html','admin_login.html','panel-administracion/login.html',
'admin/cp.js','cp.js','administrator/index.js','administrator/login.js','nsw/admin/login.js','webadmin/login.js','admin/admin_login.js','admin_login.js',
'administrator/account.js','administrator.js','admin_area/admin.html','pages/admin/admin-login.js','admin/admin-login.js','admin-login.js',
'bb-admin/index.html','bb-admin/login.html','bb-admin/admin.html','admin/home.html','login.js','modelsearch/login.js','moderator.js','moderator/login.js',
'moderator/admin.js','account.js','pages/admin/admin-login.html','admin/admin-login.html','admin-login.html','controlpanel.js','admincontrol.js',
'admin/adminLogin.html','adminLogin.html','admin/adminLogin.html','home.html','rcjakar/admin/login.js','adminarea/index.html','adminarea/admin.html',
'webadmin.js','webadmin/index.js','acceso.js','webadmin/admin.js','admin/controlpanel.html','admin.html','admin/cp.html','cp.html','adminpanel.js','moderator.html',
'administrator/index.html','administrator/login.html','user.html','administrator/account.html','administrator.html','login.html','modelsearch/login.html',
'moderator/login.html','adminarea/login.html','panel-administracion/index.html','panel-administracion/admin.html','modelsearch/index.html','modelsearch/admin.html',
'admincontrol/login.html','adm/index.html','adm.html','moderator/admin.html','user.js','account.html','controlpanel.html','admincontrol.html',
'panel-administracion/login.js','wp-login.js','adminLogin.js','admin/adminLogin.js','home.js','admin.js','adminarea/index.js',
'adminarea/admin.js','adminarea/login.js','panel-administracion/index.js','panel-administracion/admin.js','modelsearch/index.js',
'modelsearch/admin.js','admincontrol/login.js','adm/admloginuser.js','admloginuser.js','admin2.js','admin2/login.js','admin2/index.js','usuarios/login.js',
'adm/index.js','adm.js','affiliate.js','adm_auth.js','memberadmin.js','administratorlogin.js']
cgi = ['admin/','administrator/','admin1/','admin2/','admin3/','admin4/','admin5/','usuarios/','usuario/','administrator/','moderator/','webadmin/','adminarea/','bb-admin/','adminLogin/','admin_area/','panel-administracion/','instadmin/',
'memberadmin/','administratorlogin/','adm/','admin/account.cgi','admin/index.cgi','admin/login.cgi','admin/admin.cgi','admin/account.cgi',
'admin_area/admin.cgi','admin_area/login.cgi','siteadmin/login.cgi','siteadmin/index.cgi','siteadmin/login.html','admin/account.html','admin/index.html','admin/login.html','admin/admin.html',
'admin_area/index.cgi','bb-admin/index.cgi','bb-admin/login.cgi','bb-admin/admin.cgi','admin/home.cgi','admin_area/login.html','admin_area/index.html',
'admin/controlpanel.cgi','admin.cgi','admincp/index.asp','admincp/login.asp','admincp/index.html','admin/account.html','adminpanel.html','webadmin.html',
'webadmin/index.html','webadmin/admin.html','webadmin/login.html','admin/admin_login.html','admin_login.html','panel-administracion/login.html',
'admin/cp.cgi','cp.cgi','administrator/index.cgi','administrator/login.cgi','nsw/admin/login.cgi','webadmin/login.cgi','admin/admin_login.cgi','admin_login.cgi',
'administrator/account.cgi','administrator.cgi','admin_area/admin.html','pages/admin/admin-login.cgi','admin/admin-login.cgi','admin-login.cgi',
'bb-admin/index.html','bb-admin/login.html','bb-admin/admin.html','admin/home.html','login.cgi','modelsearch/login.cgi','moderator.cgi','moderator/login.cgi',
'moderator/admin.cgi','account.cgi','pages/admin/admin-login.html','admin/admin-login.html','admin-login.html','controlpanel.cgi','admincontrol.cgi',
'admin/adminLogin.html','adminLogin.html','admin/adminLogin.html','home.html','rcjakar/admin/login.cgi','adminarea/index.html','adminarea/admin.html',
'webadmin.cgi','webadmin/index.cgi','acceso.cgi','webadmin/admin.cgi','admin/controlpanel.html','admin.html','admin/cp.html','cp.html','adminpanel.cgi','moderator.html',
'administrator/index.html','administrator/login.html','user.html','administrator/account.html','administrator.html','login.html','modelsearch/login.html',
'moderator/login.html','adminarea/login.html','panel-administracion/index.html','panel-administracion/admin.html','modelsearch/index.html','modelsearch/admin.html',
'admincontrol/login.html','adm/index.html','adm.html','moderator/admin.html','user.cgi','account.html','controlpanel.html','admincontrol.html',
'panel-administracion/login.cgi','wp-login.cgi','adminLogin.cgi','admin/adminLogin.cgi','home.cgi','admin.cgi','adminarea/index.cgi',
'adminarea/admin.cgi','adminarea/login.cgi','panel-administracion/index.cgi','panel-administracion/admin.cgi','modelsearch/index.cgi',
'modelsearch/admin.cgi','admincontrol/login.cgi','adm/admloginuser.cgi','admloginuser.cgi','admin2.cgi','admin2/login.cgi','admin2/index.cgi','usuarios/login.cgi',
'adm/index.cgi','adm.cgi','affiliate.cgi','adm_auth.cgi','memberadmin.cgi','administratorlogin.cgi']
brf = ['admin/','administrator/','admin1/','admin2/','admin3/','admin4/','admin5/','usuarios/','usuario/','administrator/','moderator/','webadmin/','adminarea/','bb-admin/','adminLogin/','admin_area/','panel-administracion/','instadmin/',
'memberadmin/','administratorlogin/','adm/','admin/account.brf','admin/index.brf','admin/login.brf','admin/admin.brf','admin/account.brf',
'admin_area/admin.brf','admin_area/login.brf','siteadmin/login.brf','siteadmin/index.brf','siteadmin/login.html','admin/account.html','admin/index.html','admin/login.html','admin/admin.html',
'admin_area/index.brf','bb-admin/index.brf','bb-admin/login.brf','bb-admin/admin.brf','admin/home.brf','admin_area/login.html','admin_area/index.html',
'admin/controlpanel.brf','admin.brf','admincp/index.asp','admincp/login.asp','admincp/index.html','admin/account.html','adminpanel.html','webadmin.html',
'webadmin/index.html','webadmin/admin.html','webadmin/login.html','admin/admin_login.html','admin_login.html','panel-administracion/login.html',
'admin/cp.brf','cp.brf','administrator/index.brf','administrator/login.brf','nsw/admin/login.brf','webadmin/login.brfbrf','admin/admin_login.brf','admin_login.brf',
'administrator/account.brf','administrator.brf','acceso.brf','admin_area/admin.html','pages/admin/admin-login.brf','admin/admin-login.brf','admin-login.brf',
'bb-admin/index.html','bb-admin/login.html','bb-admin/admin.html','admin/home.html','login.brf','modelsearch/login.brf','moderator.brf','moderator/login.brf',
'moderator/admin.brf','account.brf','pages/admin/admin-login.html','admin/admin-login.html','admin-login.html','controlpanel.brf','admincontrol.brf',
'admin/adminLogin.html','adminLogin.html','admin/adminLogin.html','home.html','rcjakar/admin/login.brf','adminarea/index.html','adminarea/admin.html',
'webadmin.brf','webadmin/index.brf','webadmin/admin.brf','admin/controlpanel.html','admin.html','admin/cp.html','cp.html','adminpanel.brf','moderator.html',
'administrator/index.html','administrator/login.html','user.html','administrator/account.html','administrator.html','login.html','modelsearch/login.html',
'moderator/login.html','adminarea/login.html','panel-administracion/index.html','panel-administracion/admin.html','modelsearch/index.html','modelsearch/admin.html',
'admincontrol/login.html','adm/index.html','adm.html','moderator/admin.html','user.brf','account.html','controlpanel.html','admincontrol.html',
'panel-administracion/login.brf','wp-login.brf','adminLogin.brf','admin/adminLogin.brf','home.brf','admin.brf','adminarea/index.brf',
'adminarea/admin.brf','adminarea/login.brf','panel-administracion/index.brf','panel-administracion/admin.brf','modelsearch/index.brf',
'modelsearch/admin.brf','admincontrol/login.brf','adm/admloginuser.brf','admloginuser.brf','admin2.brf','admin2/login.brf','admin2/index.brf','usuarios/login.brf',
'adm/index.brf','adm.brf','affiliate.brf','adm_auth.brf','memberadmin.brf','administratorlogin.brf']
try:
site = raw_input("Upisite URL stranice koju zelite pretraziti: ")
site = site.replace("http://","")
print ("\tPretraga website-a " + site + "...")
conn = httplib.HTTPConnection(site)
conn.connect()
print "\t[OK] Status servera - online."
except (httplib.HTTPResponse, socket.error) as Exit:
raw_input("\t [ERROR] Server je offline ili ste ukucali nepostojeci URL.")
exit()
print "Odaberite jezik u kome je stranica napravljena:"
print "1 PHP"
print "2 ASP"
print "3 CFM"
print "4 JS"
print "5 CGI"
print "6 BRF"
print "\nPritisnite 1,2,3,4,5 ili 6 i 'Enter'\n"
code=input("> ")
if code==1:
print("\t [...] Pretraga " + site + "...\n\n")
for admin in php:
admin = admin.replace("\n","")
admin = "/" + admin
host = site + admin
print ("\t [...] Provjera " + host + "...")
connection = httplib.HTTPConnection(site)
connection.request("GET",admin)
response = connection.getresponse()
var2 = var2 + 1
if response.status == 200:
var1 = var1 + 1
print "%s %s" % ( "\n\n>>>" + host, "[OK] Uspjesno pronadjena Admin stranica!")
raw_input("Pritisnite enter da nastavite sa skeniranjem.\n")
elif response.status == 404:
var2 = var2
elif response.status == 302:
print "%s %s" % ("\n>>>" + host, "Moguca Admin stranica (302 - Redirect)")
else:
print "%s %s %s" % (host, "Zanimljiv odaziv:", response.status)
connection.close()
print("\n\nGotovo \n")
print var1, " Nadjene Admin stranice"
print var2, " ukupan broj skeniranih stranica"
raw_input("Pritisni Enter da izadjes")
if code==2:
print("\t [...] Pretraga " + site + "...\n\n")
for admin in asp:
admin = admin.replace("\n","")
admin = "/" + admin
host = site + admin
print ("\t [...] Provjera " + host + "...")
connection = httplib.HTTPConnection(site)
connection.request("GET",admin)
response = connection.getresponse()
var2 = var2 + 1
if response.status == 200:
var1 = var1 + 1
print "%s %s" % ( "\n\n>>>" + host, "[OK] Uspjesno pronadjena Admin stranica!")
raw_input("Pritisnite enter da nastavite sa skeniranjem.\n")
elif response.status == 404:
var2 = var2
elif response.status == 302:
print "%s %s" % ("\n>>>" + host, "Moguca Admin stranica (302 - Redirect)")
else:
print "%s %s %s" % (host, " Zanimljiv odaziv:", response.status)
connection.close()
print("\n\nGotovo \n")
print var1, " Nadjene Admin stranice"
print var2, " ukupan broj skeniranih stranica"
raw_input("Pritisni Enter da izadjes")
if code==3:
print("\t [...] Pretraga " + site + "...\n\n")
for admin in cfm:
admin = admin.replace("\n","")
admin = "/" + admin
host = site + admin
print ("\t [...] Provjera " + host + "...")
connection = httplib.HTTPConnection(site)
connection.request("GET",admin)
response = connection.getresponse()
var2 = var2 + 1
if response.status == 200:
var1 = var1 + 1
print "%s %s" % ( "\n\n>>>" + host, "[OK] Uspjesno pronadjena Admin stranica!")
raw_input("Pritisnite enter da nastavite sa skeniranjem.\n")
elif response.status == 404:
var2 = var2
elif response.status == 302:
print "%s %s" % ("\n>>>" + host, "Moguca Admin stranica (302 - Redirect)")
else:
print "%s %s %s" % (host, " Zanimljiv odaziv:", response.status)
connection.close()
print("\n\nGotovo \n")
print var1, " Nadjene Admin stranice"
print var2, " ukupan broj skeniranih stranica"
raw_input("Pritisni Enter da izadjes")
if code==4:
print("\t [...] Pretraga " + site + "...\n\n")
for admin in js:
admin = admin.replace("\n","")
admin = "/" + admin
host = site + admin
print ("\t [...] Provjera " + host + "...")
connection = httplib.HTTPConnection(site)
connection.request("GET",admin)
response = connection.getresponse()
var2 = var2 + 1
if response.status == 200:
var1 = var1 + 1
print "%s %s" % ( "\n\n>>>" + host, "[OK] Uspjesno pronadjena Admin stranica!")
raw_input("Pritisnite enter da nastavite sa skeniranjem.\n")
elif response.status == 404:
var2 = var2
elif response.status == 302:
print "%s %s" % ("\n>>>" + host, "Moguca Admin stranica (302 - Redirect)")
else:
print "%s %s %s" % (host, " Zanimljiv odaziv:", response.status)
connection.close()
print("\n\nGotovo \n")
print var1, " Nadjene Admin stranice"
print var2, " ukupan broj skeniranih stranica"
raw_input("Pritisni Enter da izadjes")
if code==5:
print("\t [...] Pretraga " + site + "...\n\n")
for admin in cgi:
admin = admin.replace("\n","")
admin = "/" + admin
host = site + admin
print ("\t [...] Provjera " + host + "...")
connection = httplib.HTTPConnection(site)
connection.request("GET",admin)
response = connection.getresponse()
var2 = var2 + 1
if response.status == 200:
var1 = var1 + 1
print "%s %s" % ( "\n\n>>>" + host, "[OK] Uspjesno pronadjena Admin stranica!")
raw_input("Pritisnite enter da nastavite sa skeniranjem.\n")
elif response.status == 404:
var2 = var2
elif response.status == 302:
print "%s %s" % ("\n>>>" + host, "Moguca Admin stranica (302 - Redirect)")
else:
print "%s %s %s" % (host, " Zanimljiv odaziv:", response.status)
connection.close()
print("\n\nGotovo \n")
print var1, " Nadjene Admin stranice"
print var2, " ukupan broj skeniranih stranica"
raw_input("Pritisni Enter da izadjes")
if code==6:
print("\t [...] Pretraga " + site + "...\n\n")
for admin in brf:
admin = admin.replace("\n","")
admin = "/" + admin
host = site + admin
print ("\t [...] Provjera " + host + "...")
connection = httplib.HTTPConnection(site)
connection.request("GET",admin)
response = connection.getresponse()
var2 = var2 + 1
if response.status == 200:
var1 = var1 + 1
print "%s %s" % ( "\n\n>>>" + host, "[OK] Uspjesno pronadjena Admin stranica!")
raw_input("Pritisnite enter da nastavite sa skeniranjem.\n")
elif response.status == 404:
var2 = var2
elif response.status == 302:
print "%s %s" % ("\n>>>" + host, "Moguca Admin stranica (302 - Redirect)")
else:
print "%s %s %s" % (host, " Zanimljiv odaziv:", response.status)
connection.close()
print("\n\nGotovo \n")
print var1, " Nadjene Admin stranice"
print var2, " ukupan broj skeniranih stranica"
raw_input("Pritisni Enter da izadjes")
except (httplib.HTTPResponse, socket.error):
print "\n\t[ERROR] Program prekinut; Nastao je error, provjeri postavke interneta"
except (KeyboardInterrupt, SystemExit):
print "\n\t!Program Prekinut"
| {
"repo_name": "hashcraze/adminpagefinder",
"path": "admin.py",
"copies": "1",
"size": "26219",
"license": "mit",
"hash": -7710928547656950000,
"line_mean": 79.9228395062,
"line_max": 242,
"alpha_frac": 0.6635264503,
"autogenerated": false,
"ratio": 3.119452706722189,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9156813713316849,
"avg_score": 0.02523308874106786,
"num_lines": 324
} |
"Admin pages."
import logging
import re
import tornado.web
import orderportal
from orderportal import constants
from orderportal import saver
from orderportal import settings
from orderportal import utils
from orderportal.requesthandler import RequestHandler
class GlobalModes(RequestHandler):
"Page for display and change of global modes."
@tornado.web.authenticated
def get(self):
self.check_admin()
self.render('global_modes.html')
def post(self):
self.check_admin()
try:
mode = self.get_argument('mode')
if mode not in self.global_modes: raise ValueError
self.global_modes[mode] = utils.to_bool(self.get_argument('value'))
except (tornado.web.MissingArgumentError, ValueError, TypeError):
pass
else:
# Create global_modes meta document if it does not exist.
if '_id' not in self.global_modes:
self.global_modes['_id'] = 'global_modes'
self.global_modes[constants.DOCTYPE] = constants.META
self.db.save(self.global_modes)
self.see_other('global_modes')
class Settings(RequestHandler):
"Page displaying settings info."
@tornado.web.authenticated
def get(self):
self.check_admin()
mod_settings = settings.copy()
# Don't show the password in the CouchDB URL
url = settings['DATABASE_SERVER']
match = re.search(r':([^/].+)@', url)
if match:
url = list(url)
url[match.start(1):match.end(1)] = 'password'
mod_settings['DATABASE_SERVER'] = ''.join(url)
params = ['ROOT_DIR', 'SETTINGS_FILEPATH',
'BASE_URL', 'BASE_URL_PATH_PREFIX',
'SITE_NAME', 'SITE_SUPPORT_EMAIL',
'DATABASE_SERVER', 'DATABASE_NAME', 'DATABASE_ACCOUNT',
'TORNADO_DEBUG', 'LOGGING_FILEPATH', 'LOGGING_DEBUG',
'BACKUP_DIR', 'LOGIN_MAX_AGE_DAYS', 'LOGIN_MAX_FAILURES',
'SITE_DIR', 'ACCOUNT_MESSAGES_FILEPATH',
'ORDER_STATUSES_FILEPATH', 'ORDER_TRANSITIONS_FILEPATH',
'ORDER_MESSAGES_FILEPATH', 'ORDER_USER_TAGS',
'ORDERS_SEARCH_FIELDS', 'ORDERS_LIST_FIELDS',
'ORDERS_LIST_STATUSES', 'ORDER_AUTOPOPULATE',
'UNIVERSITIES_FILEPATH', 'COUNTRY_CODES_FILEPATH',
'SUBJECT_TERMS_FILEPATH']
self.render('settings.html', params=params, settings=mod_settings)
class TextSaver(saver.Saver):
doctype = constants.TEXT
class Text(RequestHandler):
"Edit page for information text."
@tornado.web.authenticated
def get(self, name):
self.check_admin()
try:
text = self.get_entity_view('text/name', name)
except tornado.web.HTTPError:
text = dict(name=name)
origin = self.get_argument('origin',self.absolute_reverse_url('texts'))
self.render('text.html', text=text, origin=origin)
@tornado.web.authenticated
def post(self, name):
self.check_admin()
try:
text = self.get_entity_view('text/name', name)
except tornado.web.HTTPError:
text = dict(name=name)
with TextSaver(doc=text, rqh=self) as saver:
saver['text'] = self.get_argument('text')
url = self.get_argument('origin', self.absolute_reverse_url('texts'))
self.redirect(url, status=303)
class Texts(RequestHandler):
"Page listing texts used in the web site."
@tornado.web.authenticated
def get(self):
self.check_admin()
self.render('texts.html', texts=sorted(constants.TEXTS.items()))
class OrderStatuses(RequestHandler):
"Page displaying currently defined order statuses and transitions."
@tornado.web.authenticated
def get(self):
self.check_admin()
view = self.db.view('order/status',
group_level=1,
startkey=[''],
endkey=[constants.CEILING])
counts = dict([(r.key[0], r.value) for r in view])
self.render('admin_order_statuses.html', counts=counts)
class AdminOrderMessages(RequestHandler):
"Page for displaying order messages configuration."
@tornado.web.authenticated
def get(self):
self.check_admin()
self.render('admin_order_messages.html')
class AdminAccountMessages(RequestHandler):
"Page for displaying account messages configuration."
@tornado.web.authenticated
def get(self):
self.check_admin()
self.render('admin_account_messages.html')
| {
"repo_name": "pekrau/OrderPortal",
"path": "orderportal/admin.py",
"copies": "1",
"size": "4678",
"license": "mit",
"hash": -8756625865411150000,
"line_mean": 32.1773049645,
"line_max": 79,
"alpha_frac": 0.6103035485,
"autogenerated": false,
"ratio": 4.053726169844021,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007831510491084959,
"num_lines": 141
} |
# admin.py - ExampleService Django Admin
from core.admin import ReadOnlyAwareAdmin, SliceInline
from core.middleware import get_request
from core.models import User
from django import forms
from django.contrib import admin
from services.exampleservice.models import *
class ExampleServiceForm(forms.ModelForm):
class Meta:
model = ExampleService
def __init__(self, *args, **kwargs):
super(ExampleServiceForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['service_message'].initial = self.instance.service_message
def save(self, commit=True):
self.instance.service_message = self.cleaned_data.get('service_message')
return super(ExampleServiceForm, self).save(commit=commit)
class ExampleServiceAdmin(ReadOnlyAwareAdmin):
model = ExampleService
verbose_name = SERVICE_NAME_VERBOSE
verbose_name_plural = SERVICE_NAME_VERBOSE_PLURAL
form = ExampleServiceForm
inlines = [SliceInline]
list_display = ('backend_status_icon', 'name', 'service_message', 'enabled')
list_display_links = ('backend_status_icon', 'name', 'service_message' )
fieldsets = [(None, {
'fields': ['backend_status_text', 'name', 'enabled', 'versionNumber', 'service_message', 'description',],
'classes':['suit-tab suit-tab-general',],
})]
readonly_fields = ('backend_status_text', )
user_readonly_fields = ['name', 'enabled', 'versionNumber', 'description',]
extracontext_registered_admins = True
suit_form_tabs = (
('general', 'Example Service Details', ),
('slices', 'Slices',),
)
suit_form_includes = ((
'top',
'administration'),
)
def queryset(self, request):
return ExampleService.get_service_objects_by_user(request.user)
admin.site.register(ExampleService, ExampleServiceAdmin)
class ExampleTenantForm(forms.ModelForm):
class Meta:
model = ExampleTenant
creator = forms.ModelChoiceField(queryset=User.objects.all())
def __init__(self, *args, **kwargs):
super(ExampleTenantForm, self).__init__(*args, **kwargs)
self.fields['kind'].widget.attrs['readonly'] = True
self.fields['kind'].initial = SERVICE_NAME
self.fields['provider_service'].queryset = ExampleService.get_service_objects().all()
if self.instance:
self.fields['creator'].initial = self.instance.creator
self.fields['tenant_message'].initial = self.instance.tenant_message
if (not self.instance) or (not self.instance.pk):
self.fields['creator'].initial = get_request().user
if ExampleService.get_service_objects().exists():
self.fields['provider_service'].initial = ExampleService.get_service_objects().all()[0]
def save(self, commit=True):
self.instance.creator = self.cleaned_data.get('creator')
self.instance.tenant_message = self.cleaned_data.get('tenant_message')
return super(ExampleTenantForm, self).save(commit=commit)
class ExampleTenantAdmin(ReadOnlyAwareAdmin):
verbose_name = TENANT_NAME_VERBOSE
verbose_name_plural = TENANT_NAME_VERBOSE_PLURAL
list_display = ('id', 'backend_status_icon', 'instance', 'tenant_message')
list_display_links = ('backend_status_icon', 'instance', 'tenant_message', 'id')
fieldsets = [(None, {
'fields': ['backend_status_text', 'kind', 'provider_service', 'instance', 'creator', 'tenant_message'],
'classes': ['suit-tab suit-tab-general'],
})]
readonly_fields = ('backend_status_text', 'instance',)
form = ExampleTenantForm
suit_form_tabs = (('general', 'Details'),)
def queryset(self, request):
return ExampleTenant.get_tenant_objects_by_user(request.user)
admin.site.register(ExampleTenant, ExampleTenantAdmin)
| {
"repo_name": "jermowery/xos",
"path": "xos/services/exampleservice/admin.py",
"copies": "2",
"size": "3870",
"license": "apache-2.0",
"hash": -1308695085036223000,
"line_mean": 32.3620689655,
"line_max": 113,
"alpha_frac": 0.6645994832,
"autogenerated": false,
"ratio": 3.944954128440367,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.010837333392944315,
"num_lines": 116
} |
#admin.py
from django.contrib import admin
from shopping_cart.models import Store, Item, Order, Transaction
class ItemInline(admin.TabularInline):
model = Item
extra = 3
class StoreAdmin(admin.ModelAdmin):
list_display = ('name','bio')
inlines = (ItemInline, )
class ItemAdmin(admin.ModelAdmin):
list_display = ('name','price', 'quantity', 'description', 'store')
search_fields = ['name', 'price', 'quantity', 'store__name']
list_filter = ('store__name','store__owner', 'date_added')
#filter returned item list by owner, so merchants only see thier items
def queryset(self, request):
qs = super(ItemAdmin, self).queryset(request)
return qs.filter(store__owner=request.user)
class OrderAdmin(admin.ModelAdmin):
list_display = ()
search_fields = ['name', 'price', 'quantity', 'store__name']
list_filter = ('store__name','store__owner', 'date_added')
# register admin models to admin
admin.site.register(Store, StoreAdmin)
admin.site.register(Item, ItemAdmin)
admin.site.register(Order)
admin.site.register(Transaction) | {
"repo_name": "agconti/shopping_cart",
"path": "shopping_cart_project/shopping_cart/admin.py",
"copies": "1",
"size": "1044",
"license": "mit",
"hash": -8982804190356653000,
"line_mean": 31.65625,
"line_max": 71,
"alpha_frac": 0.7222222222,
"autogenerated": false,
"ratio": 3.3248407643312103,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45470629865312107,
"avg_score": null,
"num_lines": null
} |
"""admin.py"""
from django.contrib.sites.models import Site
from django.contrib.contenttypes.admin import GenericTabularInline
from django.contrib import admin
from .models import (
Post, Category, Tag, Comment, ReComment,
Link, Analytics, Ads, SiteDetail, PopularPost, Image, File
)
class SiteDetailInline(admin.StackedInline):
"""サイト詳細情報のインライン"""
model = SiteDetail
class SiteAdmin(admin.ModelAdmin):
"""Siteモデルを、管理画面でSiteDetailもインラインで表示できるように"""
inlines = [SiteDetailInline]
class ImageInline(admin.TabularInline):
"""記事内画像のインライン"""
model = Image
extra = 3
class FileInline(GenericTabularInline):
"""記事内添付ファイルのインライン"""
model = File
extra = 3
class PostAdmin(admin.ModelAdmin):
"""記事を、管理画面で画像とファイルIもインラインで埋め込む"""
inlines = [ImageInline, FileInline]
admin.autodiscover() # Siteアプリのadmin.pyを頑張って探す
admin.site.unregister(Site) # インラインにするため一度解除
admin.site.register(Site, SiteAdmin) # インライン
admin.site.register(Post, PostAdmin) # インライン
admin.site.register(Category)
admin.site.register(Tag)
admin.site.register(Link)
admin.site.register(Comment)
admin.site.register(ReComment)
admin.site.register(Analytics)
admin.site.register(Ads)
admin.site.register(PopularPost)
admin.site.register(File) | {
"repo_name": "naritotakizawa/django-torina-blog",
"path": "blog/admin.py",
"copies": "1",
"size": "1512",
"license": "mit",
"hash": -381816480050372160,
"line_mean": 24.22,
"line_max": 66,
"alpha_frac": 0.753968254,
"autogenerated": false,
"ratio": 2.441860465116279,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8691828719116279,
"avg_score": 0.0008,
"num_lines": 50
} |
""" admin.py """
from .extensions import db
from .models import Todo, User, Role
from flask.ext.superadmin import Admin, model, BaseView, AdminIndexView
from flask_security.core import current_user
class AuthMixin(object):
def is_accessible(self):
return (current_user.is_authenticated()
and current_user.has_role('Admin'))
class AdminIndexView(AuthMixin, AdminIndexView):
pass
class DefaultModelAdmin(AuthMixin, model.ModelAdmin):
session = db.session
class UserModelAdmin(DefaultModelAdmin):
exclude = ['password', ]
def register_admin(app):
admin = Admin(
app,
name="Todo MVC Administration",
index_view=AdminIndexView()
)
admin.register(Todo, DefaultModelAdmin)
admin.register(User, UserModelAdmin)
admin.register(Role, DefaultModelAdmin)
#admin.add_view(ProtectedModelView(Todo, db.session))
#admin.add_view(ProtectedModelView(User, db.session, category='Users'))
#admin.add_view(ProtectedModelView(Role, db.session, category='Users'))
| {
"repo_name": "bikegriffith/flask-todomvc",
"path": "flask_todomvc/admin.py",
"copies": "1",
"size": "1048",
"license": "mit",
"hash": 7091067041943893000,
"line_mean": 29.8235294118,
"line_max": 75,
"alpha_frac": 0.7108778626,
"autogenerated": false,
"ratio": 3.7697841726618706,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4980662035261871,
"avg_score": null,
"num_lines": null
} |
# admin.py
# This file controls the look and feel of the models within the Admin App
# They appear in the admin app once they are registered at the bottom of
# this code (same goes for the databrowse app)
from django.conf import settings # needed if we use the GOOGLE_MAPS_API_KEY from settings
# Import the admin site reference from django.contrib.admin
from django.contrib import admin
# Grab the Admin Manager that automaticall initializes an OpenLayers map
# for any geometry field using the in Google Mercator projection with OpenStreetMap basedata
from django.contrib.gis.admin import OSMGeoAdmin, GeoModelAdmin
# Note, another simplier manager that does not reproject the data on OpenStreetMap is available
# with from `django.contrib.gis.admin import GeoModelAdmin`
# Finally, import our model from the working project
# the geographic_admin folder must be on your python path
# for this import to work correctly
from world.models import WorldBorders
# Import the Databrowse app so we can register our models to display via the Databrowse
from django.contrib import databrowse
databrowse.site.register(WorldBorders)
USE_GOOGLE_TERRAIN_TILES = False
class WorldBordersAdmin(OSMGeoAdmin):
"""
The class that determines the display of the WorldBorders model
within the Admin App.
This class uses some sample options and provides a bunch more in commented
form below to show the various options GeoDjango provides to customize OpenLayers.
For a look at all the GeoDjango options dive into the source code available at:
http://code.djangoproject.com/browser/django/trunk/django/contrib/gis/admin/options.py
"""
# Standard Django Admin Options
list_display = ('name','pop2005','region','subregion','geometry',)
list_editable = ('geometry',)
search_fields = ('name',)
list_per_page = 4
ordering = ('name',)
list_filter = ('region','subregion',)
save_as = True
search_fields = ['name','iso2','iso3','subregion','region']
list_select_related = True
fieldsets = (
('Country Attributes', {'fields': (('name','pop2005')), 'classes': ('show','extrapretty')}),
('Country Codes', {'fields': ('region','subregion','iso2','iso3','un',), 'classes': ('collapse',)}),
('Area and Coordinates', {'fields': ('area','lat','lon',), 'classes': ('collapse', 'wide')}),
('Editable Map View', {'fields': ('geometry',), 'classes': ('show', 'wide')}),
)
if USE_GOOGLE_TERRAIN_TILES:
map_template = 'gis/admin/google.html'
extra_js = ['http://openstreetmap.org/openlayers/OpenStreetMap.js', 'http://maps.google.com/maps?file=api&v=2&key=%s' % settings.GOOGLE_MAPS_API_KEY]
else:
pass # defaults to OSMGeoAdmin presets of OpenStreetMap tiles
# Default GeoDjango OpenLayers map options
# Uncomment and modify as desired
# To learn more about this jargon visit:
# www.openlayers.org
#default_lon = 0
#default_lat = 0
#default_zoom = 4
#display_wkt = False
#display_srid = False
#extra_js = []
#num_zoom = 18
#max_zoom = False
#min_zoom = False
#units = False
#max_resolution = False
#max_extent = False
#modifiable = True
#mouse_position = True
#scale_text = True
#layerswitcher = True
scrollable = False
#admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
map_width = 400
map_height = 325
#map_srid = 4326
#map_template = 'gis/admin/openlayers.html'
#openlayers_url = 'http://openlayers.org/api/2.6/OpenLayers.js'
#wms_url = 'http://labs.metacarta.com/wms/vmap0'
#wms_layer = 'basic'
#wms_name = 'OpenLayers WMS'
#debug = False
#widget = OpenLayersWidget
# Finally, with these options set now register the model
# associating the Options with the actual model
admin.site.register(WorldBorders,WorldBordersAdmin) | {
"repo_name": "springmeyer/djmapnik",
"path": "examples/geoadmin/world/admin.py",
"copies": "1",
"size": "3892",
"license": "bsd-3-clause",
"hash": -7617284287412886000,
"line_mean": 36.7961165049,
"line_max": 163,
"alpha_frac": 0.6932168551,
"autogenerated": false,
"ratio": 3.724401913875598,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4917618768975598,
"avg_score": null,
"num_lines": null
} |
# Released subject to the BSD License
# Please see http://www.voidspace.org.uk/documents/BSD-LICENSE.txt
# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
# Comments, suggestions and bug reports welcome.
# For information about bugfixes, updates and support, please join the Pythonutils mailing list.
# http://voidspace.org.uk/mailman/listinfo/pythonutils_voidspace.org.uk
# Comments, suggestions and bug reports welcome.
import sys
import os
from modules.logintools.xmlsqlite import SQL
from modules.configobj import ConfigObj
from modules.pathutils import *
from modules.cgiutils import *
from loginutils import *
###################################################
def cSort(inlist, minisort=True):
"""A case insensitive sort. If minisort is True then elements of the list for which element1.lower() == element2.lower() will also be sorted.
(See the examples/test stuff."""
sortlist = []
newlist = []
sortdict = {}
for entry in inlist:
try:
lentry = entry.lower()
except AttributeError:
sortlist.append(lentry)
else:
try:
sortdict[lentry].append(entry)
except KeyError:
sortdict[lentry] = [entry]
sortlist.append(lentry)
sortlist.sort()
for entry in sortlist:
try:
thislist = sortdict[entry]
if minisort: thislist.sort()
newlist = newlist + thislist
except KeyError:
newlist.append(entry)
return newlist
####################################################
# Various default values etc
adminpage_file = 'admin_page.html'
adminmenu_file = 'admin_menu.txt'
adminconfig_file = 'admin_config.txt' # the template used for the 'edit config' option.
admininvite_file = 'admin_invite.txt' # the template to invite/create new users
adminuser_file = 'admin_eduser.txt' # template for edit/delete user
MAXADMINLEV = 3 # the maximum admin level it's possible for a user to have
MINMAXAGE = 600 # the minimum value for cookie max-age
pass_msg = '\nYour login name is "%s", your password is "%s".\nYou can change this once you have logged in.\n'
SCRIPTLOC = 'http://' + os.environ.get('HTTP_HOST', '') # XXXX do we trust this in all cases ? (i.e. not always http - https)
numonpage = 5 # number of users shown on a page at a time
# table elements used to display the accounts in edit users
edit_table_s = '<table width="90%" cellspacing="15" bgcolor="#3377bb" class="table">'
table_e = '</table>'
elem_h = '<tr><td align="center"><table border="4" width="100%" bgcolor="#dddddd">'
elem_f = '</table></td></tr>'
form_s = '''<form method="post" action="%s"><input type="hidden" name="login" value="admin">
<input type="hidden" name="action" value="%s"><input type="hidden" name="admin" value="%s">
<input type="hidden" name="start" value="%s"><input type="hidden" name="username" value="%s">
'''
form_e = '</form>'
account_table = form_s + '''<tr>
<td align="center"><strong>Login Name : </strong></td><td align="center"><input type="text" name="loginname" value="%s"></td>
<td align="center"><strong>Real Name : </strong></td><td align="center"><input type="text" name="realname" value="%s"></td></tr><tr>
<td align="center"><strong>Email : </strong></td><td align="center"><input type="text" name="email" value="%s"></td>
<td align="center"><strong>Admin Level</strong></td><td align="center"><input type="text" name="adminlev" value="%s"></td></tr><tr>
<td align="center"><strong>New Password : </strong></td><td align="center"><input type="text" name="pass1"></td>
<td align="center"><strong>Cookie max-age : </strong></td><td align="center"><input type="text" name="maxage" value="%s"></td></tr><tr>
<td align="center"><strong>Confirm Password : </strong></td><td align="center"><input type="text" name="pass2"></td>
<td align="center"><strong>Editable : </strong></td><td align="center"><input type="checkbox" name="editable" %s ></td></tr><tr><td align="center">
<input type="reset"></td><td> </td><td> </td><td align="center"><input type="submit" value="Submit Changes"></td></tr><tr>''' + form_e + form_s + '''
<td> </td><td> </td><td> </td><td> </td></tr><tr>
<td> </td><td align="center"><input type="checkbox" name="confirm">Confirm Delete</td><td align="center"><input type="submit" value="Delete User">
</td><td> </td></tr>''' + form_e
####################################################
# main menu - offering
# edit config
# edit users (including delete)
# invite/create new users
# display edit config (including values from the default user)
# edit config
# display invite/create
# invite new users
# create new user file
# edit user - can't edit or delete yourself or the 'main admin' (saves having to change newcookie)
# choose a user to edit or delete
# display edit user for that account
# or delete user (confirm ?)
# edit user -
# change password
# rename (change login name - ?)
# change display name
# change email address
def admin(theform, userdir, thisscript, userconfig, action, newcookie):
"""Decide what admin action to perform. """
adminaction = theform.getfirst('admin', '')
if adminaction.startswith('editconfig'):
editconfig(theform, userdir, thisscript, userconfig, action, newcookie)
elif adminaction.startswith('invite'):
invite(theform, userdir, thisscript, userconfig, action, newcookie)
elif adminaction.startswith('edituser'):
edituser(theform, userdir, thisscript, userconfig, action, newcookie)
elif adminaction.startswith('doeditconfig'):
doeditconfig(theform, userdir, thisscript, userconfig, action, newcookie)
elif adminaction.startswith('doinvite'):
doinvite(theform, userdir, thisscript, userconfig, action, newcookie)
elif adminaction.startswith('edituser'):
edituser(theform, userdir, thisscript, userconfig, action, newcookie)
elif adminaction.startswith('doedituser'):
doedituser(theform, userdir, thisscript, userconfig, action, newcookie)
elif adminaction.startswith('deluser'):
deluser(theform, userdir, thisscript, userconfig, action, newcookie)
else:
displaymenu(theform, userdir, thisscript, userconfig, action, newcookie)
def displaymenu(theform, userdir, thisscript, userconfig, action, newcookie):
"""Display the admin menu page."""
config = ConfigObj(userdir + 'config.ini')
templatedir = config['templatedir']
adminpage = readfile(templatedir+adminpage_file)
adminpage = adminpage.replace('**this script**', thisscript + '?action=' + action)
url = '?login=admin&admin=%s&action=' + action
adminmenu = readfile(templatedir+adminmenu_file)
adminmenu = adminmenu.replace('**edit config**', thisscript+url % 'editconfig')
adminmenu = adminmenu.replace('**edit users**', thisscript+url % 'edituser')
adminmenu = adminmenu.replace('**invite**', thisscript+url % 'invite')
adminpage = adminpage.replace('**admin**', adminmenu)
adminpage = adminpage.replace('**admin menu**', thisscript+'?login=admin'+'&action='+action)
print(newcookie)
print(serverline)
print("")
print(adminpage)
sys.exit()
def editconfig(theform, userdir, thisscript, userconfig, action, newcookie, msg=None, success=None):
"""Display the screen to edit the main config file.
This includes the default user."""
config = ConfigObj(userdir + 'config.ini')
default = ConfigObj(userdir + 'default.ini')
templatedir = config['templatedir']
adminpage = readfile(templatedir+adminpage_file)
adminpage = adminpage.replace('**this script**', thisscript + '?action=' + action)
adminpage = adminpage.replace('**admin menu**', thisscript+'?login=admin'+'&action='+action)
# The values of this that are editable from config.ini are :
# newloginlink, adminmail, email_subject, email_message
#
# The values of this that are editable from default.ini are :
# max-age, editable
if msg:
adminpage = adminpage.replace('<br><!- message --> ', '<h2>'+msg+'</h2>')
if msg and not success:
loginlink = theform.getfirst('loginlink', '')
if loginlink:
loginlink = 'checked'
adminmail = theform.getfirst('adminmail', '')
emailsubj = theform.getfirst('emailsubject', '')
emailmsg = theform.getfirst('emailmsg', '')
maxage = theform.getfirst('maxage', '')
editable = theform.getfirst('editable', '')
if editable:
editable = 'checked'
else:
loginlink = config['newloginlink'].lower()
if loginlink == 'yes':
loginlink = 'checked'
else:
loginlink = ''
adminmail = config['adminmail']
emailsubj = config['email_subject']
emailmsg = config['email_message']
maxage = default['max-age']
editable = default['editable'].lower()
if editable == 'yes':
editable = 'checked'
else:
editable = ''
configmenu = readfile(templatedir+adminconfig_file)
configmenu = configmenu.replace('**loginlink**', loginlink)
configmenu = configmenu.replace('**adminmail**', adminmail)
configmenu = configmenu.replace('**email subject**', emailsubj)
configmenu = configmenu.replace('**email message**',emailmsg)
configmenu = configmenu.replace('**maxage**', maxage)
configmenu = configmenu.replace('**editable**', editable)
configmenu = configmenu.replace('**thisscript**', thisscript)
configmenu = configmenu.replace('**action**', action)
adminpage = adminpage.replace('**admin**', configmenu)
print newcookie
print serverline
print
print adminpage
sys.exit()
def invite(theform, userdir, thisscript, userconfig, action, newcookie, msg=None, success=None):
"""Display the screen to create or invite a new user."""
config = ConfigObj(userdir + 'config.ini')
templatedir = config['templatedir']
adminpage = readfile(templatedir+adminpage_file)
adminpage = adminpage.replace('**this script**', thisscript + '?action=' + action)
adminpage = adminpage.replace('**admin menu**', thisscript+'?login=admin'+'&action='+action)
# Values to be filled in are :
# **create1** and **create2** - the one switched on should be 'checked', the other should be ''
if msg:
adminpage = adminpage.replace('<br><!- message --> ', '<h2>'+msg+'</h2>')
if msg and not success:
create = theform.getfirst('create', '')
if create == 'create':
create1 = 'checked'
create2 = ''
else:
create2 = 'checked'
create1 = ''
realname = theform.getfirst('realname', '')
username = theform.getfirst('username', '')
email = theform.getfirst('email', '')
pass1 = theform.getfirst('pass1', '')
pass2 = theform.getfirst('pass2', '')
adminlev = theform.getfirst('adminlev', '')
else:
create2 = 'checked'
create1 = ''
realname = ''
username = ''
email = ''
pass1 = randomstring(8)
pass2 = pass1
adminlev = '0'
invitemenu = readfile(templatedir+admininvite_file)
invitemenu = invitemenu.replace('**create1**', create1)
invitemenu = invitemenu.replace('**create2**', create2)
invitemenu = invitemenu.replace('**realname**', realname)
invitemenu = invitemenu.replace('**username**', username)
invitemenu = invitemenu.replace('**email**', email)
invitemenu = invitemenu.replace('**pass1**', pass1)
invitemenu = invitemenu.replace('**pass2**', pass2)
invitemenu = invitemenu.replace('**adminlev**', adminlev)
invitemenu = invitemenu.replace('**thisscript**', thisscript)
invitemenu = invitemenu.replace('**action**', action)
adminpage = adminpage.replace('**admin**', invitemenu)
print(newcookie)
print(serverline)
print("")
print(adminpage)
sys.exit()
def edituser(theform, userdir, thisscript, userconfig, action, newcookie, msg=None, success=None):
"""Display the screen to edit or delete users.."""
config = ConfigObj(userdir + 'config.ini')
templatedir = config['templatedir']
realadminlev = int(userconfig['admin'])
adminpage = readfile(templatedir+adminpage_file)
adminpage = adminpage.replace('**this script**', thisscript + '?action=' + action)
adminpage = adminpage.replace('**admin menu**', thisscript+'?login=admin'+'&action='+action)
userlist = [entry[:-4] for entry in os.listdir(userdir) if os.path.isfile(userdir+entry) and entry[:-4] not in RESERVEDNAMES ]
mainadmin = config['adminuser']
username = userconfig['username']
if mainadmin in userlist:
userlist.remove(mainadmin)
if username in userlist:
userlist.remove(username)
userlist = cSort(userlist)
start = int(theform.getfirst('start', '1'))
length = len(userlist)
if start*numonpage > length:
start = length//numonpage + 1
url = '<a href="' + thisscript + '?start=%s&login=admin&admin=edituser&action=' + action + '">%s</a>'
indexline = '<div style="text-align:center;">%s</div>' % makeindexline(url, start, length, numonpage)
# need to be able to edit -
# username, realname, new password, confirm password, adminlev, email, max-age, editable
index = (start-1)*numonpage + 1
last = min(length+1, index+numonpage)
usermenu = indexline + '<br>' + edit_table_s
while index < last: # go through all the users
thisuser = userlist[index-1]
index += 1
thisuserc = ConfigObj(userdir+thisuser+'.ini')
adminlev = thisuserc['admin']
if realadminlev <= int(adminlev):
continue
loginname = thisuser
realname = thisuserc['realname']
email = thisuserc['email']
maxage = thisuserc['max-age']
editable = ''
if istrue(thisuserc['editable']):
editable = 'checked'
if theform.getfirst('username')==loginname and msg and not success:
realname = theform.getfirst('realname', '')
realname = theform.getfirst('realname', '')
email = theform.getfirst('email', '')
adminlev = theform.getfirst('adminlev', '')
maxage = theform.getfirst('maxage', '')
editable = theform.getfirst('editable', '')
if editable:
editable = 'checked'
thevals = (thisscript, action, 'doedituser', start, loginname,
loginname, realname, email, adminlev, maxage, editable,
thisscript, action, 'deluser', start, loginname)
usermenu += elem_h + (account_table % thevals) + elem_f
# kim's stuff!!!!!
project=action.split("_")[-1]
sql=SQL(project)
uid=sql.userid(thisuser, realname)
#print "Content-Type: text/html\n" # blank line: end of headers
#print "kim<br>", project,thisuser,uid
# kim's stuff ends....
usermenu += table_e + '<br>' + indexline
eduserpage = readfile(templatedir+adminuser_file)
eduserpage = eduserpage.replace('**account table**', usermenu)
if msg:
adminpage = adminpage.replace('<br><!- message --> ', '<h2>%s</h2>' % msg)
adminpage = adminpage.replace('**admin**', eduserpage)
print(newcookie)
print(serverline)
print("")
print(adminpage)
sys.exit()
##########################################################
def doeditconfig(theform, userdir, thisscript, userconfig, action, newcookie):
"""Receives the submission from the edit config page."""
config = ConfigObj(userdir + 'config.ini')
default = ConfigObj(userdir + 'default.ini')
loginlink = theform.getfirst('loginlink', '')
adminmail = theform.getfirst('adminmail', '')
emailsubj = theform.getfirst('emailsubject', '')
emailmsg = theform.getfirst('emailmsg', '')
maxage = theform.getfirst('maxage', '')
editable = theform.getfirst('editable', '')
if adminmail and not validemail(adminmail):
editconfig(theform, userdir, thisscript, userconfig, action, newcookie, "The adminmail doesn't appear to be a valid address.")
if not maxage.isdigit():
editconfig(theform, userdir, thisscript, userconfig, action, newcookie, "maxage must be a number.")
if int(maxage) and int(maxage) < MINMAXAGE:
editconfig(theform, userdir, thisscript, userconfig, action, newcookie, "maxage must be greater than %s." % MINMAXAGE)
if loginlink:
config['newloginlink'] = 'Yes'
else:
config['newloginlink'] = 'No'
config['adminmail'] = adminmail
config['email_subject'] = emailsubj
config['email_message'] = emailmsg
config.write()
default['max-age'] = maxage
if editable:
default['editable'] = 'Yes'
else:
default['editable'] = 'No'
default.write()
displaymenu(theform, userdir, thisscript, userconfig, action, newcookie) # XXXX should we send a msg here 'COnfig File Edited' ?
#####################################################################
def doinvite(theform, userdir, thisscript, userconfig, action, newcookie):
"""Receives the submission from the invite/create new user page."""
config = ConfigObj(userdir + 'config.ini')
default = ConfigObj(userdir + 'default.ini')
create = theform.getfirst('create', '')
realname = theform.getfirst('realname', '')
username = theform.getfirst('username', '')
email = validemail(theform.getfirst('email', ''))
pass1 = theform.getfirst('pass1', '')
pass2 = theform.getfirst('pass2', '')
adminlev = theform.getfirst('adminlev', '')
maxadminlev = min(int(userconfig['admin']), MAXADMINLEV)
if not email:
invite(theform, userdir, thisscript, userconfig, action, newcookie, 'The email address appears to be invalid.')
if pass1 != pass2:
invite(theform, userdir, thisscript, userconfig, action, newcookie, "The two passwords don't match.")
if len(pass1) < 5:
invite(theform, userdir, thisscript, userconfig, action, newcookie, "The password must be at least five characters long.")
if not realname:
invite(theform, userdir, thisscript, userconfig, action, newcookie, 'You must supply a realname.')
if not username:
invite(theform, userdir, thisscript, userconfig, action, newcookie, 'You must supply a username.')
if not adminlev.isdigit():
invite(theform, userdir, thisscript, userconfig, action, newcookie, 'Admin level must be a number.')
if int(adminlev) > maxadminlev:
invite(theform, userdir, thisscript, userconfig, action, newcookie, 'Admin level is greater than the maximum allowed (%s).' % maxadminlev)
# now we need to check if the username already exists
tempstore = ConfigObj(userdir + 'temp.ini')
pendinglist = tempstore.get('pending', [])
if os.path.isfile(userdir+username+'.ini') or username in pendinglist or username.lower() in RESERVEDNAMES:
invite(theform, userdir, thisscript, userconfig, action, newcookie, 'username already exists.')
for char in username.lower():
if not char in validchars:
invite(theform, userdir, thisscript, userconfig, action, newcookie, 'username contains invalid characters.')
# now we have verified the values - we *either* need to create a new username *or* send an invitiation
if create == 'create':
createuser(userdir, realname, username, email, pass1, adminlev)
msg = 'New User Created'
else:
inviteuser(userdir, realname, username, email, pass1, thisscript, adminlev)
msg = 'New User Invited'
invite(theform, userdir, thisscript, userconfig, action, newcookie, msg, True)
####################################################################
def doedituser(theform, userdir, thisscript, userconfig, action, newcookie):
"""Receives form submissions from the 'edit user' page."""
# parameters to get :
# username, realname, email, adminlev, pass1, pass2
username = theform.getfirst('username') # the user we are editing
loginname = theform.getfirst('loginname') # the new user name (won't usually change I guess)
realname = theform.getfirst('realname')
email = theform.getfirst('email')
adminlev = theform.getfirst('adminlev')
pass1 = theform.getfirst('pass1')
pass2 = theform.getfirst('pass2')
maxage = theform.getfirst('maxage')
editable = theform.getfirst('editable')
maxadminlev = min(int(userconfig['admin']), MAXADMINLEV)
# check all the account values
# this could be turned into a generic 'account checker' function if we wanted.
email = validemail(email)
if not email:
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'The Email Address Appears to Be Invalid.')
if not loginname:
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'You Must Supply a Login Name.')
for char in loginname.lower():
if not char in validchars:
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'Login Name Contains Invalid Characters')
if not realname:
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'You Must Supply a Real Name')
if (pass1 or pass2) and not (pass1 and pass2):
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'To Change the Password - Enter it Twice')
if pass1 != pass2:
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'The Two Passwords Are Different')
if pass1 and len(pass1) < 5:
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'Password Must Be at Least Five Characters')
if not adminlev.isdigit():
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'The Admin Level Must Be a Number')
if int(adminlev) > maxadminlev:
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'Admin Level is Higher than the Max (%s).' % maxadminlev)
if not maxage.isdigit():
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'Cookie "max-age" Must Be a Number')
if int(maxage) and int(maxage) < MINMAXAGE:
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'Cookie "max-age" Must Be Greater Than %s' % MINMAXAGE)
if editable:
editable = 'Yes'
else:
editable = 'No'
# let's just check if the username has changed
thisuser = ConfigObj(userdir+username+'.ini')
if loginname != username:
pendinglist = ConfigObj(userdir + 'temp.ini').get('pending', [])
if os.path.isfile(userdir+loginname+'.ini') or loginname in pendinglist or loginname.lower() in RESERVEDNAMES:
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'Login Name Chosen Already Exists')
thisuser.filename = userdir+loginname+'.ini' # change to new name
os.remove(userdir+username+'.ini') # free up the old name
if pass1:
from dataenc import pass_enc
thisuser['password'] = pass_enc(pass1, daynumber=True, timestamp=True)
#
thisuser['realname'] = realname
thisuser['email'] = email
thisuser['admin'] = adminlev
thisuser['max-age'] = maxage
thisuser['editable'] = editable
thisuser.write()
# edituser(theform, userdir, thisscript, userconfig, action, newcookie, '')
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'Changes Made Successfully', True)
def deluser(theform, userdir, thisscript, userconfig, action, newcookie):
"""Receives form submissions from when 'delete user' is hit."""
# parameters to get :
# username, realname, email, adminlev, pass1, pass2
username = theform.getfirst('username')
confirm = theform.getfirst('confirm')
if not confirm:
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'Confirm Was Not Selected - Delete Not Done', True)
# XXXX we ought to check that the user being deleted isn't the main admin user and hasn't got a higher admin level
os.remove(userdir+username+'.ini') # is it really that easy
edituser(theform, userdir, thisscript, userconfig, action, newcookie, 'Delete Done Successfully', True)
###############################################
# createuser is in loginutils - but this uses a couple of values defined in this module
def inviteuser(userdir, realname, username, email, password, thisscript, adminlev):
"""Invite a new user."""
from newlogin import savedetails
from configobj import ConfigObj
formdict = {'username' : username, 'pass1' : password, 'admin' : adminlev,
'realname' : realname, 'email' : email, 'action' : '' }
thekey = savedetails(userdir, formdict)
config = ConfigObj(userdir + 'config.ini')
msg = config['email_message'] + '\n'
msg = msg + SCRIPTLOC + thisscript + '?login=confirm&id=' + thekey + (pass_msg % (username, password))
writefile('log.txt', msg)
sendmailme(email, msg, config['email_subject'], email, html=False)
"""
CHANGELOG
=========
2005/10/30
----------
Fixed the email function... oops.
2005/09/16
----------
Removed dependency on caseless module (added ``cSort``).
2005/09/09
----------
Changes to work with pythonutils 0.2.1
"""
| {
"repo_name": "amir-zeldes/rstWeb",
"path": "modules/logintools/admin.py",
"copies": "1",
"size": "26008",
"license": "mit",
"hash": -2118733315002739500,
"line_mean": 43.4581196581,
"line_max": 159,
"alpha_frac": 0.6415333743,
"autogenerated": false,
"ratio": 3.7670915411355734,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4908624915435573,
"avg_score": null,
"num_lines": null
} |
''' admin.py
Administration module
Copyright 2008 Corey Tabaka
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
# put this here to handle circular import from bot and other modules
def trusted(*args):
if len(args) > 1 or isinstance(args[0], str):
def delegate(func):
def check(context):
admin = _administrators.get(context.sender.nick) or _aliases.get(context.sender.nick)
if admin and admin.trusted(context.sender):
if admin.checkAccess(*args):
func(context)
else:
context.reply("%s: I don't trust you that much" % context.sender)
else:
context.reply('%s: You are not trusted' % context.sender)
check.__module__ = func.__module__
check.__name__ = func.__name__
check.__doc__ = func.__doc__
return check
return delegate
else:
func = args[0]
def check(context):
admin = _administrators.get(context.sender.nick) or _aliases.get(context.sender.nick)
if admin and admin.trusted(context.sender):
func(context)
else:
context.reply('%s: You are not trusted' % context.sender)
check.__module__ = func.__module__
check.__name__ = func.__name__
check.__doc__ = func.__doc__
return check
def isAdmin(context):
admin = _administrators.get(context.sender.nick) or _aliases.get(context.sender.nick)
return bool(admin and admin.trusted(context.sender))
from irclib import ProtocolHandler
from bot import BotCommandHandler
import channel
import re, anydbm, sys, atexit
_reNick = re.compile('^[a-zA-Z_][\w_\-\[\]\\`^{}]*$')
_reTrust = re.compile('\s*([a-zA-Z_][\w_\-\[\]\\`^{}]*)(?:\s+([^\s,]+(?:[\s,]+[^\s,]+)*))?')
_reAccessList = re.compile('\s*list\s+([^\s]+)')
_reAccessAdd = re.compile('\s*add\s+([^\s]+)\s+([^\s,]+(?:[\s,]+[^\s,]+)*)')
_reAccessRemove = re.compile('\s*remove\s+([^\s]+)\s+([^\s,]+(?:[\s,]+[^\s,]+)*)')
_reAccessArgs = re.compile('[\s,]+')
def _filterNick(nick):
nick = (nick or '').strip()
m = _reNick.match(nick)
if m:
return nick
else:
return ''
class AdminUser(object):
def __init__(self, nick, access=''):
self.nick = nick
self.user = ''
self.host = ''
self.identified = False
self.alias = ''
self.events = dict()
if isinstance(access, (str, type(None))):
self.access = set(_reAccessArgs.split(access or ''))
else:
self.access = set(access)
def trusted(self, sender):
return self.identified and sender.user == self.user and sender.host == self.host
def checkAccess(self, *flags):
return set(flags).issubset(self.access)
def addAccess(self, *flags):
flags = set(flags)
flags -= set([''])
self.access |= flags
self.dbAdd()
def removeAccess(self, *flags):
self.access -= set(flags)
self.dbAdd()
def invalidate(self):
self.host = ''
self.user = ''
self.identified = False
def runEvent(self, name):
response = self.events.get(name)
if response:
del self.events[name]
response()
def setEvent(self, name, handler):
self.events[name] = handler
def dbRemove(self):
del _db[self.nick]
_db.sync()
def dbAdd(self):
_db[self.nick] = ','.join(self.access)
_db.sync()
# load/create the admin db
_db = anydbm.open('administrators.db', 'c')
atexit.register(_db.close)
# create a default user using the master nick in pyy
if not len(_db):
import pyy
try:
_db[pyy.MASTER] = 'admin'
except:
print 'Failed to create default admin user:', str(sys.exc_value)
# work around missing iter method
def dbiteritems(db):
if hasattr(db, 'iteritems'):
return db.iteritems()
else:
return ((key, db.get(key)) for key in db.keys())
_administrators = dict([(nick, AdminUser(nick, access)) for nick, access in dbiteritems(_db)])
_aliases = dict()
@BotCommandHandler('auth')
def _auth(context):
'''Usage: auth\nRequests the bot to verify the sender's admin status'''
admin = _administrators.get(context.sender.nick) or _aliases.get(context.sender.nick)
if admin:
if admin.identified:
context.reply('%s is already trusted' % context.sender.nick)
else:
context.reply('Checking services...')
def event():
context.reply('%s is identified by services' % context.sender.nick)
admin.setEvent('auth_whois', event)
context.proc.whois(context.sender.nick)
else:
context.reply('%s is not an admin' % context.sender.nick)
@BotCommandHandler('trust')
@trusted
def _trust(context):
'''Usage: trust <nick> [flag [, flag]...]\nAdds nick to the list of admins with the specified access flags'''
m = _reTrust.match(context.args)
if m:
nick, access = m.groups()
if nick in _aliases:
context.reply('%s (%s) is already trusted; use access to modify' % (nick, _aliases[nick].nick))
elif nick in _administrators:
context.reply('%s is already trusted; use access to modify' % nick)
else:
if access:
admin = _administrators.get(context.sender.nick) or _aliases.get(context.sender.nick)
if admin.checkAccess('admin'):
user = AdminUser(nick, access)
_administrators[nick] = user
user.dbAdd()
context.reply('%s is now trusted with access: %s' % (nick, ','.join(sorted(user.access))))
context.proc.whois(nick)
else:
context.reply("%s: you don't have the right to grant access" % context.sender.nick)
else:
user = AdminUser(nick)
_administrators[nick] = user
user.dbAdd()
context.reply('%s is now trusted' % nick)
context.proc.whois(nick)
else:
context.reply('Usage: trust <nick>')
@BotCommandHandler('untrust')
@trusted
def _untrust(context):
'''Usage: untrust <nick>\nRemoves nick from the list of admins'''
nick = _filterNick(context.args)
if nick:
admin = _administrators.get(nick) or _aliases.get(nick)
if admin:
if admin.nick == context.getSetting('master'):
context.reply('%s: Nigga, please!' % context.sender.nick)
else:
del _administrators[admin.nick]
admin.dbRemove()
if nick in _aliases:
del _aliases[nick]
if nick == admin.nick:
context.reply('%s is no longer trusted' % nick)
else:
context.reply('%s (%s) is no longer trusted' % (nick, admin.nick))
else:
context.reply('%s is already not trusted' % nick)
else:
context.reply('Usage: untrust <nick>')
@BotCommandHandler('access')
@trusted('admin')
def _access(context):
'''Usage: access <list|add|remove> <nick> [flag [, flag]...]\nLists, adds, or removes access flags from nick'''
m = _reAccessList.match(context.args)
if m:
nick, = m.groups()
admin = _administrators.get(nick) or _aliases.get(nick)
if admin:
context.reply('%s has access: %s' % (nick, ', '.join(sorted(admin.access))))
else:
context.reply('%s is not trusted' % nick)
return
m = _reAccessAdd.match(context.args)
if m:
nick, access = m.groups()
admin = _administrators.get(nick) or _aliases.get(nick)
if admin:
access = _reAccessArgs.split(access)
admin.addAccess(*access)
else:
context.reply('%s is not trusted' % nick)
return
m = _reAccessRemove.match(context.args)
if m:
nick, access = m.groups()
admin = _administrators.get(nick) or _aliases.get(nick)
if admin:
access = _reAccessArgs.split(access)
admin.removeAccess(*access)
else:
context.reply('%s is not trusted' % nick)
return
context.reply('Usage: access <list|add|remove> <nick> [name [, name]...]')
@ProtocolHandler('NICK')
def _nick(context):
nick = context.params.lstrip(':')
admin = _administrators.get(context.sender.nick) or _aliases.get(context.sender.nick)
if admin:
if admin.alias:
del _aliases[admin.alias]
if nick not in _administrators:
_aliases[nick] = admin
admin.alias = nick
elif admin != _administrators[nick]:
admin.alias = ''
_administrators[nick].invalidate()
context.proc.whois(nick)
else:
admin.alias = ''
@ProtocolHandler('JOIN')
def _join(context):
admin = _administrators.get(context.sender.nick)
if admin:
context.proc.whois(context.sender.nick)
@ProtocolHandler('PART')
def _part(context):
admin = _administrators.get(context.sender.nick) or _aliases.get(context.sender.nick)
if admin:
channels = channel.getChannelsForNick(context.sender.nick)
if not channels and context.sender.nick in _aliases:
del _aliases[context.sender.nick]
@ProtocolHandler('311')
def _311(context):
m = re.match('([^\s]+)\s+([^\s]+)\s+(?:([in])=)?([^@ ]+)\s+([^\s]+)\s*(.*)', context.params)
if m:
me, nick, in_, user, host, other = m.groups()
admin = _administrators.get(nick)
if admin:
admin.user = user
admin.host = host
@ProtocolHandler('320')
def _320(context):
m = re.match('([^\s]+)\s+([^\s]+)\s+:(.*)', context.params)
if m:
me, nick, message = m.groups()
admin = _administrators.get(nick)
if admin and 'is identified to services' in message:
admin.identified = True
admin.runEvent('auth_whois')
@ProtocolHandler('307')
def _307(context):
m = re.match('([^\s]+)\s+([^\s]+)\s+:(.*)', context.params)
if m:
me, nick, message = m.groups()
admin = _administrators.get(nick)
if admin and 'is a registered nick' in message:
admin.identified = True
admin.runEvent('auth_whois')
| {
"repo_name": "eieio/pyy",
"path": "modules/admin.py",
"copies": "1",
"size": "9895",
"license": "apache-2.0",
"hash": 1441116231814057200,
"line_mean": 27.3620178042,
"line_max": 112,
"alpha_frac": 0.63628095,
"autogenerated": false,
"ratio": 3.0921875,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8778032148461812,
"avg_score": 0.09008726030763745,
"num_lines": 337
} |
"""Admin registrations for Sites."""
from django.contrib import admin
from django.forms import ModelForm, ModelMultipleChoiceField
from .models import Site, Language, BlacklistedURL
class SiteAdminForm(ModelForm):
languages = ModelMultipleChoiceField(queryset=Language.objects.order_by('name'))
class Meta:
model = Site
fields = '__all__'
class LanguageAdmin(admin.ModelAdmin):
list_display = ('name', 'code', 'language_code', 'country_code', 'display_country')
class SiteAdmin(admin.ModelAdmin):
list_display = ('title', 'clickable_url', 'author', 'visible', 'featured')
form = SiteAdminForm
def make_visible(modeladmin, request, queryset):
queryset.update(visible=True)
make_visible.short_description = "Show selected sites"
def make_invisible(modeladmin, request, queryset):
queryset.update(visible=False)
make_invisible.short_description = "Hide selected sites"
actions = [make_visible, make_invisible]
class BlacklistedURLAdmin(admin.ModelAdmin):
list_display = ('url', 'exact')
admin.site.register(Site, SiteAdmin)
admin.site.register(Language, LanguageAdmin)
admin.site.register(BlacklistedURL, BlacklistedURLAdmin)
| {
"repo_name": "getnikola/nikola-users",
"path": "sites/admin.py",
"copies": "1",
"size": "1211",
"license": "mit",
"hash": -1706818499682113300,
"line_mean": 30.8684210526,
"line_max": 87,
"alpha_frac": 0.7291494633,
"autogenerated": false,
"ratio": 3.9318181818181817,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5160967645118182,
"avg_score": null,
"num_lines": null
} |
"""Admins API Version 1.0.
This API client was generated using a template. Make sure this code is valid before using it.
"""
import logging
from datetime import date, datetime
from .base import BaseCanvasAPI
from .base import BaseModel
class AdminsAPI(BaseCanvasAPI):
"""Admins API Version 1.0."""
def __init__(self, *args, **kwargs):
"""Init method for AdminsAPI."""
super(AdminsAPI, self).__init__(*args, **kwargs)
self.logger = logging.getLogger("py3canvas.AdminsAPI")
def make_account_admin(self, user_id, account_id, role=None, role_id=None, send_confirmation=None):
"""
Make an account admin.
Flag an existing user as an admin within the account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - user_id
"""The id of the user to promote."""
data["user_id"] = user_id
# OPTIONAL - role
"""(deprecated)
The user's admin relationship with the account will be created with the
given role. Defaults to 'AccountAdmin'."""
if role is not None:
data["role"] = role
# OPTIONAL - role_id
"""The user's admin relationship with the account will be created with the
given role. Defaults to the built-in role for 'AccountAdmin'."""
if role_id is not None:
data["role_id"] = role_id
# OPTIONAL - send_confirmation
"""Send a notification email to
the new admin if true. Default is true."""
if send_confirmation is not None:
data["send_confirmation"] = send_confirmation
self.logger.debug("POST /api/v1/accounts/{account_id}/admins with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/admins".format(**path), data=data, params=params, single_item=True)
def remove_account_admin(self, user_id, account_id, role=None, role_id=None):
"""
Remove account admin.
Remove the rights associated with an account admin role from a user.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# OPTIONAL - role
"""(Deprecated)
Account role to remove from the user. Defaults to 'AccountAdmin'. Any
other account role must be specified explicitly."""
if role is not None:
params["role"] = role
# OPTIONAL - role_id
"""The user's admin relationship with the account will be created with the
given role. Defaults to the built-in role for 'AccountAdmin'."""
if role_id is not None:
params["role_id"] = role_id
self.logger.debug("DELETE /api/v1/accounts/{account_id}/admins/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/accounts/{account_id}/admins/{user_id}".format(**path), data=data, params=params, single_item=True)
def list_account_admins(self, account_id, user_id=None):
"""
List account admins.
List the admins in the account
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# OPTIONAL - user_id
"""Scope the results to those with user IDs equal to any of the IDs specified here."""
if user_id is not None:
params["user_id"] = user_id
self.logger.debug("GET /api/v1/accounts/{account_id}/admins with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/admins".format(**path), data=data, params=params, all_pages=True)
class Admin(BaseModel):
"""Admin Model."""
def __init__(self, id, workflow_state=None, role=None, user=None):
"""Init method for Admin class."""
self._workflow_state = workflow_state
self._role = role
self._id = id
self._user = user
self.logger = logging.getLogger('py3canvas.Admin')
@property
def workflow_state(self):
"""The status of the account role/user assignment."""
return self._workflow_state
@workflow_state.setter
def workflow_state(self, value):
"""Setter for workflow_state property."""
self.logger.warn("Setting values on workflow_state will NOT update the remote Canvas instance.")
self._workflow_state = value
@property
def role(self):
"""The account role assigned. This can be 'AccountAdmin' or a user-defined role created by the Roles API."""
return self._role
@role.setter
def role(self, value):
"""Setter for role property."""
self.logger.warn("Setting values on role will NOT update the remote Canvas instance.")
self._role = value
@property
def id(self):
"""The unique identifier for the account role/user assignment."""
return self._id
@id.setter
def id(self, value):
"""Setter for id property."""
self.logger.warn("Setting values on id will NOT update the remote Canvas instance.")
self._id = value
@property
def user(self):
"""The user the role is assigned to. See the Users API for details."""
return self._user
@user.setter
def user(self, value):
"""Setter for user property."""
self.logger.warn("Setting values on user will NOT update the remote Canvas instance.")
self._user = value
| {
"repo_name": "tylerclair/py3canvas",
"path": "py3canvas/apis/admins.py",
"copies": "1",
"size": "5937",
"license": "mit",
"hash": -4171545840500712400,
"line_mean": 33.7192982456,
"line_max": 173,
"alpha_frac": 0.6043456291,
"autogenerated": false,
"ratio": 4.160476524176595,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5264822153276595,
"avg_score": null,
"num_lines": null
} |
"""Admins API Version 1.0.
This API client was generated using a template. Make sure this code is valid before using it.
"""
import logging
from datetime import date, datetime
from base import BaseCanvasAPI
from base import BaseModel
class AdminsAPI(BaseCanvasAPI):
"""Admins API Version 1.0."""
def __init__(self, *args, **kwargs):
"""Init method for AdminsAPI."""
super(AdminsAPI, self).__init__(*args, **kwargs)
self.logger = logging.getLogger("pycanvas.AdminsAPI")
def make_account_admin(self, user_id, account_id, role=None, role_id=None, send_confirmation=None):
"""
Make an account admin.
Flag an existing user as an admin within the account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - user_id
"""The id of the user to promote."""
data["user_id"] = user_id
# OPTIONAL - role
"""(deprecated)
The user's admin relationship with the account will be created with the
given role. Defaults to 'AccountAdmin'."""
if role is not None:
data["role"] = role
# OPTIONAL - role_id
"""The user's admin relationship with the account will be created with the
given role. Defaults to the built-in role for 'AccountAdmin'."""
if role_id is not None:
data["role_id"] = role_id
# OPTIONAL - send_confirmation
"""Send a notification email to
the new admin if true. Default is true."""
if send_confirmation is not None:
data["send_confirmation"] = send_confirmation
self.logger.debug("POST /api/v1/accounts/{account_id}/admins with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/admins".format(**path), data=data, params=params, single_item=True)
def remove_account_admin(self, user_id, account_id, role=None, role_id=None):
"""
Remove account admin.
Remove the rights associated with an account admin role from a user.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# OPTIONAL - role
"""(Deprecated)
Account role to remove from the user. Defaults to 'AccountAdmin'. Any
other account role must be specified explicitly."""
if role is not None:
params["role"] = role
# OPTIONAL - role_id
"""The user's admin relationship with the account will be created with the
given role. Defaults to the built-in role for 'AccountAdmin'."""
if role_id is not None:
params["role_id"] = role_id
self.logger.debug("DELETE /api/v1/accounts/{account_id}/admins/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/accounts/{account_id}/admins/{user_id}".format(**path), data=data, params=params, single_item=True)
def list_account_admins(self, account_id, user_id=None):
"""
List account admins.
List the admins in the account
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# OPTIONAL - user_id
"""Scope the results to those with user IDs equal to any of the IDs specified here."""
if user_id is not None:
params["user_id"] = user_id
self.logger.debug("GET /api/v1/accounts/{account_id}/admins with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/admins".format(**path), data=data, params=params, all_pages=True)
class Admin(BaseModel):
"""Admin Model."""
def __init__(self, id, status=None, role=None, user=None):
"""Init method for Admin class."""
self._status = status
self._role = role
self._id = id
self._user = user
self.logger = logging.getLogger('pycanvas.Admin')
@property
def status(self):
"""The status of the account role/user assignment."""
return self._status
@status.setter
def status(self, value):
"""Setter for status property."""
self.logger.warn("Setting values on status will NOT update the remote Canvas instance.")
self._status = value
@property
def role(self):
"""The account role assigned. This can be 'AccountAdmin' or a user-defined role created by the Roles API."""
return self._role
@role.setter
def role(self, value):
"""Setter for role property."""
self.logger.warn("Setting values on role will NOT update the remote Canvas instance.")
self._role = value
@property
def id(self):
"""The unique identifier for the account role/user assignment."""
return self._id
@id.setter
def id(self, value):
"""Setter for id property."""
self.logger.warn("Setting values on id will NOT update the remote Canvas instance.")
self._id = value
@property
def user(self):
"""The user the role is assigned to. See the Users API for details."""
return self._user
@user.setter
def user(self, value):
"""Setter for user property."""
self.logger.warn("Setting values on user will NOT update the remote Canvas instance.")
self._user = value
| {
"repo_name": "PGower/PyCanvas",
"path": "pycanvas/apis/admins.py",
"copies": "1",
"size": "6024",
"license": "mit",
"hash": -6182337733159904000,
"line_mean": 33.2280701754,
"line_max": 173,
"alpha_frac": 0.5836653386,
"autogenerated": false,
"ratio": 4.278409090909091,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.536207442950909,
"avg_score": null,
"num_lines": null
} |
"""Admin serializers."""
from django.core.exceptions import ValidationError
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _
from rest_framework import serializers
from passwords import validators
from modoboa.admin import models as admin_models
from modoboa.core import constants as core_constants
from modoboa.core import models as core_models
from modoboa.core import signals as core_signals
from modoboa.lib import exceptions as lib_exceptions
from modoboa.lib import permissions, email_utils, fields as lib_fields
from . import models
class DomainSerializer(serializers.ModelSerializer):
"""Base Domain serializer."""
class Meta:
model = models.Domain
fields = ("pk", "name", "quota", "enabled", "type", )
def create(self, validated_data):
"""Set permissions."""
domain = models.Domain(**validated_data)
domain.save(creator=self.context["request"].user)
return domain
class DomainAliasSerializer(serializers.ModelSerializer):
"""Base DomainAlias serializer."""
class Meta:
model = admin_models.DomainAlias
fields = ("pk", "name", "target", "enabled", )
def validate_target(self, value):
"""Check target domain."""
if not self.context["request"].user.can_access(value):
raise serializers.ValidationError(_("Permission denied."))
return value
def create(self, validated_data):
"""Custom creation."""
domain_alias = models.DomainAlias(**validated_data)
creator = self.context["request"].user
try:
core_signals.can_create_object.send(
sender=self.__class__, context=creator,
object_type="domain_aliases")
core_signals.can_create_object.send(
sender=self.__class__, context=domain_alias.target,
object_type="domain_aliases")
except lib_exceptions.ModoboaException as inst:
raise serializers.ValidationError({
"domain": unicode(inst)})
domain_alias.save(creator=creator)
return domain_alias
class MailboxSerializer(serializers.ModelSerializer):
"""Base mailbox serializer."""
full_address = lib_fields.DRFEmailFieldUTF8()
class Meta:
model = models.Mailbox
fields = ("full_address", "use_domain_quota", "quota", )
class AccountSerializer(serializers.ModelSerializer):
"""Base account serializer."""
role = serializers.SerializerMethodField()
mailbox = MailboxSerializer(required=False)
domains = serializers.SerializerMethodField(
help_text=_(
"List of administered domains (resellers and domain "
"administrators only)."))
class Meta:
model = core_models.User
fields = (
"pk", "username", "first_name", "last_name", "is_active",
"master_user", "mailbox", "role", "language", "phone_number",
"secondary_email", "domains",
)
def __init__(self, *args, **kwargs):
"""Adapt fields to current user."""
super(AccountSerializer, self).__init__(*args, **kwargs)
request = self.context.get("request")
if not request:
return
user = self.context["request"].user
if not user.is_superuser:
del self.fields["master_user"]
def get_role(self, account):
"""Return role."""
return account.role
def get_domains(self, account):
"""Return domains administered by this account."""
if account.role not in ["DomainAdmins", "Resellers"]:
return []
return admin_models.Domain.objects.get_for_admin(account).values_list(
"name", flat=True)
class AccountExistsSerializer(serializers.Serializer):
"""Simple serializer used with existence checks."""
exists = serializers.BooleanField()
class AccountPasswordSerializer(serializers.ModelSerializer):
"""A serializer used to change a user password."""
new_password = serializers.CharField()
class Meta:
model = core_models.User
fields = (
"password", "new_password", )
def validate_password(self, value):
"""Check password."""
if not self.instance.check_password(value):
raise serializers.ValidationError("Password not correct")
return value
def validate_new_password(self, value):
"""Check new password."""
try:
validators.validate_length(value)
validators.complexity(value)
except ValidationError as exc:
raise serializers.ValidationError(exc.messages[0])
return value
def update(self, instance, validated_data):
"""Set new password."""
instance.set_password(validated_data["new_password"])
instance.save()
return instance
class WritableAccountSerializer(AccountSerializer):
"""Serializer to create account."""
role = serializers.ChoiceField(choices=core_constants.ROLES)
class Meta(AccountSerializer.Meta):
fields = AccountSerializer.Meta.fields + (
"password", )
def __init__(self, *args, **kwargs):
"""Adapt fields to current user."""
super(WritableAccountSerializer, self).__init__(*args, **kwargs)
request = self.context.get("request")
if not request:
return
user = self.context["request"].user
self.fields["role"] = serializers.ChoiceField(
choices=permissions.get_account_roles(user))
self.fields["domains"] = serializers.ListField(
child=serializers.CharField(), allow_empty=False, required=False)
if request.method == "PUT":
self.fields["password"].required = False
def validate_password(self, value):
"""Check password constraints."""
try:
validators.validate_length(value)
validators.complexity(value)
except ValidationError as exc:
raise serializers.ValidationError(exc.messages[0])
return value
def validate(self, data):
"""Check constraints."""
master_user = data.get("master_user", False)
role = data.get("role")
if master_user and role != "SuperAdmins":
raise serializers.ValidationError({
"master_user": _("Not allowed for this role.")
})
if role == "SimpleUsers":
mailbox = data.get("mailbox")
if mailbox is None:
data["mailbox"] = {
"full_address": data["username"], "use_domain_quota": True
}
elif mailbox["full_address"] != data["username"]:
raise serializers.ValidationError({
"username": _("Must be equal to mailbox full_address")
})
domain_names = data.get("domains")
if not domain_names:
return data
domains = []
for name in domain_names:
domain = admin_models.Domain.objects.filter(name=name).first()
if domain:
domains.append(domain)
continue
raise serializers.ValidationError({
"domains": _("Local domain {} does not exist").format(name)
})
data["domains"] = domains
return data
def _create_mailbox(self, creator, account, data):
"""Create a new Mailbox instance."""
full_address = data.pop("full_address")
address, domain_name = email_utils.split_mailbox(full_address)
domain = get_object_or_404(
admin_models.Domain, name=domain_name)
if not creator.can_access(domain):
raise serializers.ValidationError({
"domain": _("Permission denied.")})
try:
core_signals.can_create_object.send(
sender=self.__class__, context=creator,
object_type="mailboxes")
core_signals.can_create_object.send(
sender=self.__class__, context=domain,
object_type="mailboxes")
except lib_exceptions.ModoboaException as inst:
raise serializers.ValidationError({
"domain": unicode(inst)})
mb = admin_models.Mailbox(
user=account, address=address, domain=domain, **data)
mb.set_quota(
data.get("quota"), creator.has_perm("admin.add_domain")
)
mb.save(creator=creator)
account.email = full_address
return mb
def set_permissions(self, account, domains):
"""Assign permissions on domain(s)."""
if account.role not in ["DomainAdmins", "Resellers"]:
return
current_domains = admin_models.Domain.objects.get_for_admin(account)
for domain in current_domains:
if domain not in domains:
domain.remove_admin(account)
else:
domains.remove(domain)
for domain in domains:
domain.add_admin(account)
def create(self, validated_data):
"""Create appropriate objects."""
creator = self.context["request"].user
mailbox_data = validated_data.pop("mailbox", None)
role = validated_data.pop("role")
domains = validated_data.pop("domains", [])
user = core_models.User(**validated_data)
user.set_password(validated_data["password"])
user.save(creator=creator)
if mailbox_data:
self._create_mailbox(creator, user, mailbox_data)
user.role = role
self.set_permissions(user, domains)
return user
def update(self, instance, validated_data):
"""Update account and associated objects."""
mailbox_data = validated_data.pop("mailbox")
password = validated_data.pop("password", None)
domains = validated_data.pop("domains", [])
for key, value in validated_data.items():
setattr(instance, key, value)
if password:
instance.set_password(password)
instance.save()
if mailbox_data:
creator = self.context["request"].user
if instance.mailbox:
# FIXME: compat, to remove ASAP.
mailbox_data["email"] = mailbox_data["full_address"]
instance.mailbox.update_from_dict(creator, mailbox_data)
else:
self._create_mailbox(creator, instance, mailbox_data)
self.set_permissions(instance, domains)
return instance
class AliasSerializer(serializers.ModelSerializer):
"""Base Alias serializer."""
address = lib_fields.DRFEmailFieldUTF8AndEmptyUser()
recipients = serializers.ListField(
child=lib_fields.DRFEmailFieldUTF8AndEmptyUser(),
allow_empty=False)
class Meta:
model = admin_models.Alias
fields = ("pk", "address", "enabled", "internal", "recipients")
def validate_address(self, value):
"""Check domain."""
local_part, domain = email_utils.split_mailbox(value)
self.domain = admin_models.Domain.objects.filter(name=domain).first()
if self.domain is None:
raise serializers.ValidationError(_("Domain not found."))
if not self.context["request"].user.can_access(self.domain):
raise serializers.ValidationError(_("Permission denied."))
return value
def create(self, validated_data):
"""Create appropriate objects."""
creator = self.context["request"].user
try:
core_signals.can_create_object.send(
sender=self.__class__, context=creator,
object_type="mailbox_aliases")
core_signals.can_create_object.send(
sender=self.__class__, context=self.domain,
object_type="mailbox_aliases")
except lib_exceptions.ModoboaException as inst:
raise serializers.ValidationError(unicode(inst))
recipients = validated_data.pop("recipients", None)
alias = admin_models.Alias(domain=self.domain, **validated_data)
alias.save(creator=creator)
alias.set_recipients(recipients)
return alias
def update(self, instance, validated_data):
"""Update objects."""
recipients = validated_data.pop("recipients", None)
for key, value in validated_data.items():
setattr(instance, key, value)
instance.save()
instance.set_recipients(recipients)
return instance
| {
"repo_name": "carragom/modoboa",
"path": "modoboa/admin/serializers.py",
"copies": "1",
"size": "12578",
"license": "isc",
"hash": -118421208126427870,
"line_mean": 35.4579710145,
"line_max": 78,
"alpha_frac": 0.6094768644,
"autogenerated": false,
"ratio": 4.545717383447777,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5655194247847778,
"avg_score": null,
"num_lines": null
} |
"""Admin serializers."""
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _, ugettext_lazy
from django.utils.encoding import force_text
from rest_framework import serializers
from passwords import validators
from modoboa.admin import models as admin_models
from modoboa.core import constants as core_constants
from modoboa.core import models as core_models
from modoboa.core import signals as core_signals
from modoboa.lib import exceptions as lib_exceptions
from modoboa.lib import permissions, email_utils, fields as lib_fields
from . import models
class DomainSerializer(serializers.ModelSerializer):
"""Base Domain serializer."""
class Meta:
model = models.Domain
fields = (
"pk", "name", "quota", "default_mailbox_quota", "enabled", "type",
)
def validate(self, data):
"""Check quota values."""
quota = data.get("quota", 0)
default_mailbox_quota = data.get("default_mailbox_quota", 0)
if quota != 0 and default_mailbox_quota > quota:
raise serializers.ValidationError({
"default_mailbox_quota":
_("Cannot be greater than domain quota")
})
return data
def create(self, validated_data):
"""Set permissions."""
domain = models.Domain(**validated_data)
creator = self.context["request"].user
core_signals.can_create_object.send(
sender=self.__class__, context=creator,
klass=models.Domain, instance=domain)
domain.save(creator=creator)
return domain
class DomainAliasSerializer(serializers.ModelSerializer):
"""Base DomainAlias serializer."""
class Meta:
model = admin_models.DomainAlias
fields = ("pk", "name", "target", "enabled", )
def validate_target(self, value):
"""Check target domain."""
if not self.context["request"].user.can_access(value):
raise serializers.ValidationError(_("Permission denied."))
return value
def create(self, validated_data):
"""Custom creation."""
domain_alias = models.DomainAlias(**validated_data)
creator = self.context["request"].user
try:
core_signals.can_create_object.send(
sender=self.__class__, context=creator,
klass=models.DomainAlias)
core_signals.can_create_object.send(
sender=self.__class__, context=domain_alias.target,
object_type="domain_aliases")
except lib_exceptions.ModoboaException as inst:
raise serializers.ValidationError({
"domain": force_text(inst)})
domain_alias.save(creator=creator)
return domain_alias
class MailboxSerializer(serializers.ModelSerializer):
"""Base mailbox serializer."""
full_address = lib_fields.DRFEmailFieldUTF8()
class Meta:
model = models.Mailbox
fields = ("full_address", "use_domain_quota", "quota", )
class AccountSerializer(serializers.ModelSerializer):
"""Base account serializer."""
role = serializers.SerializerMethodField()
mailbox = MailboxSerializer(required=False)
domains = serializers.SerializerMethodField(
help_text=_(
"List of administered domains (resellers and domain "
"administrators only)."))
class Meta:
model = core_models.User
fields = (
"pk", "username", "first_name", "last_name", "is_active",
"master_user", "mailbox", "role", "language", "phone_number",
"secondary_email", "domains",
)
def __init__(self, *args, **kwargs):
"""Adapt fields to current user."""
super(AccountSerializer, self).__init__(*args, **kwargs)
request = self.context.get("request")
if not request:
return
user = self.context["request"].user
if not user.is_superuser:
del self.fields["master_user"]
def get_role(self, account):
"""Return role."""
return account.role
def get_domains(self, account):
"""Return domains administered by this account."""
if account.role not in ["DomainAdmins", "Resellers"]:
return []
return admin_models.Domain.objects.get_for_admin(account).values_list(
"name", flat=True)
class AccountExistsSerializer(serializers.Serializer):
"""Simple serializer used with existence checks."""
exists = serializers.BooleanField()
class AccountPasswordSerializer(serializers.ModelSerializer):
"""A serializer used to change a user password."""
new_password = serializers.CharField()
class Meta:
model = core_models.User
fields = (
"password", "new_password", )
def validate_password(self, value):
"""Check password."""
if not self.instance.check_password(value):
raise serializers.ValidationError("Password not correct")
return value
def validate_new_password(self, value):
"""Check new password."""
try:
validators.validate_length(value)
validators.complexity(value)
except ValidationError as exc:
raise serializers.ValidationError(exc.messages[0])
return value
def update(self, instance, validated_data):
"""Set new password."""
instance.set_password(validated_data["new_password"])
instance.save()
return instance
class WritableAccountSerializer(AccountSerializer):
"""Serializer to create account."""
role = serializers.ChoiceField(choices=core_constants.ROLES)
class Meta(AccountSerializer.Meta):
fields = AccountSerializer.Meta.fields + (
"password", )
def __init__(self, *args, **kwargs):
"""Adapt fields to current user."""
super(WritableAccountSerializer, self).__init__(*args, **kwargs)
request = self.context.get("request")
if not request:
return
user = self.context["request"].user
self.fields["role"] = serializers.ChoiceField(
choices=permissions.get_account_roles(user))
self.fields["domains"] = serializers.ListField(
child=serializers.CharField(), allow_empty=False, required=False)
if request.method == "PUT":
self.fields["password"].required = False
def validate_password(self, value):
"""Check password constraints."""
try:
validators.validate_length(value)
validators.complexity(value)
except ValidationError as exc:
raise serializers.ValidationError(exc.messages[0])
return value
def validate(self, data):
"""Check constraints."""
master_user = data.get("master_user", False)
role = data.get("role")
if master_user and role != "SuperAdmins":
raise serializers.ValidationError({
"master_user": _("Not allowed for this role.")
})
if role == "SimpleUsers":
mailbox = data.get("mailbox")
if mailbox is None:
data["mailbox"] = {
"full_address": data["username"], "use_domain_quota": True
}
elif mailbox["full_address"] != data["username"]:
raise serializers.ValidationError({
"username": _("Must be equal to mailbox full_address")
})
domain_names = data.get("domains")
if not domain_names:
return data
domains = []
for name in domain_names:
domain = admin_models.Domain.objects.filter(name=name).first()
if domain:
domains.append(domain)
continue
raise serializers.ValidationError({
"domains": _("Local domain {} does not exist").format(name)
})
data["domains"] = domains
return data
def _create_mailbox(self, creator, account, data):
"""Create a new Mailbox instance."""
full_address = data.pop("full_address")
address, domain_name = email_utils.split_mailbox(full_address)
domain = get_object_or_404(
admin_models.Domain, name=domain_name)
if not creator.can_access(domain):
raise serializers.ValidationError({
"domain": _("Permission denied.")})
try:
core_signals.can_create_object.send(
sender=self.__class__, context=creator,
klass=admin_models.Mailbox)
core_signals.can_create_object.send(
sender=self.__class__, context=domain,
object_type="mailboxes")
except lib_exceptions.ModoboaException as inst:
raise serializers.ValidationError({
"domain": force_text(inst)})
quota = data.pop("quota", None)
mb = admin_models.Mailbox(
user=account, address=address, domain=domain, **data)
mb.set_quota(quota, creator.has_perm("admin.add_domain"))
mb.save(creator=creator)
account.email = full_address
return mb
def set_permissions(self, account, domains):
"""Assign permissions on domain(s)."""
if account.role not in ["DomainAdmins", "Resellers"]:
return
current_domains = admin_models.Domain.objects.get_for_admin(account)
for domain in current_domains:
if domain not in domains:
domain.remove_admin(account)
else:
domains.remove(domain)
for domain in domains:
domain.add_admin(account)
def create(self, validated_data):
"""Create appropriate objects."""
creator = self.context["request"].user
mailbox_data = validated_data.pop("mailbox", None)
role = validated_data.pop("role")
domains = validated_data.pop("domains", [])
user = core_models.User(**validated_data)
user.set_password(validated_data["password"])
user.save(creator=creator)
if mailbox_data:
self._create_mailbox(creator, user, mailbox_data)
user.role = role
self.set_permissions(user, domains)
return user
def update(self, instance, validated_data):
"""Update account and associated objects."""
mailbox_data = validated_data.pop("mailbox")
password = validated_data.pop("password", None)
domains = validated_data.pop("domains", [])
for key, value in validated_data.items():
setattr(instance, key, value)
if password:
instance.set_password(password)
instance.save()
if mailbox_data:
creator = self.context["request"].user
if instance.mailbox:
# FIXME: compat, to remove ASAP.
mailbox_data["email"] = mailbox_data["full_address"]
instance.mailbox.update_from_dict(creator, mailbox_data)
else:
self._create_mailbox(creator, instance, mailbox_data)
self.set_permissions(instance, domains)
return instance
class AliasSerializer(serializers.ModelSerializer):
"""Base Alias serializer."""
address = lib_fields.DRFEmailFieldUTF8AndEmptyUser()
recipients = serializers.ListField(
child=lib_fields.DRFEmailFieldUTF8AndEmptyUser(),
allow_empty=False,
help_text=ugettext_lazy("A list of recipient"))
class Meta:
model = admin_models.Alias
fields = ("pk", "address", "enabled", "internal", "recipients")
def validate_address(self, value):
"""Check domain."""
local_part, domain = email_utils.split_mailbox(value)
self.domain = admin_models.Domain.objects.filter(name=domain).first()
if self.domain is None:
raise serializers.ValidationError(_("Domain not found."))
if not self.context["request"].user.can_access(self.domain):
raise serializers.ValidationError(_("Permission denied."))
return value
def create(self, validated_data):
"""Create appropriate objects."""
creator = self.context["request"].user
try:
core_signals.can_create_object.send(
sender=self.__class__, context=creator,
klass=admin_models.Alias)
core_signals.can_create_object.send(
sender=self.__class__, context=self.domain,
object_type="mailbox_aliases")
except lib_exceptions.ModoboaException as inst:
raise serializers.ValidationError(force_text(inst))
recipients = validated_data.pop("recipients", None)
alias = admin_models.Alias(domain=self.domain, **validated_data)
alias.save(creator=creator)
alias.set_recipients(recipients)
return alias
def update(self, instance, validated_data):
"""Update objects."""
recipients = validated_data.pop("recipients", None)
for key, value in validated_data.items():
setattr(instance, key, value)
instance.save()
instance.set_recipients(recipients)
return instance
| {
"repo_name": "bearstech/modoboa",
"path": "modoboa/admin/serializers.py",
"copies": "1",
"size": "13380",
"license": "isc",
"hash": 8070165151926118000,
"line_mean": 35.6575342466,
"line_max": 78,
"alpha_frac": 0.6091180867,
"autogenerated": false,
"ratio": 4.534056252117926,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5643174338817927,
"avg_score": null,
"num_lines": null
} |
"""Admin serializers."""
from typing import List
from django.conf import settings
from django.contrib.auth import password_validation
from django.core.exceptions import ValidationError
from django.shortcuts import get_object_or_404
from django.utils.encoding import force_text
from django.utils.translation import ugettext as _, ugettext_lazy
from rest_flex_fields import FlexFieldsModelSerializer
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from modoboa.admin import models as admin_models
from modoboa.core import (
constants as core_constants, models as core_models, signals as core_signals
)
from modoboa.lib import (
email_utils, exceptions as lib_exceptions, fields as lib_fields,
permissions, validators, web_utils
)
from modoboa.parameters import tools as param_tools
from ... import lib, models
class DomainSerializer(serializers.ModelSerializer):
"""Base Domain serializer."""
quota = serializers.CharField(
required=False,
help_text=ugettext_lazy(
"Quota shared between mailboxes. Can be expressed in KB, "
"MB (default) or GB. A value of 0 means no quota."
)
)
default_mailbox_quota = serializers.CharField(
required=False,
help_text=ugettext_lazy(
"Default quota in MB applied to mailboxes. A value of 0 means "
"no quota."
)
)
class Meta:
model = models.Domain
fields = (
"pk", "name", "quota", "default_mailbox_quota", "enabled", "type",
"enable_dkim", "dkim_key_selector", "dkim_key_length",
"dkim_public_key", "dkim_private_key_path",
"mailbox_count", "mbalias_count", "domainalias_count",
"dns_global_status", "message_limit", "creation",
"last_modification"
)
read_only_fields = (
"pk", "dkim_public_key", "dns_global_status", "allocated_quota_in_percent"
"mailbox_count", "mbalias_count", "domainalias_count",
"enable_dns_checks", "creation", "last_modification"
)
def validate_name(self, value):
"""Check name constraints."""
domains_must_have_authorized_mx = (
param_tools.get_global_parameter("domains_must_have_authorized_mx")
)
user = self.context["request"].user
value = value.lower()
if domains_must_have_authorized_mx and not user.is_superuser:
if not lib.domain_has_authorized_mx(value):
raise serializers.ValidationError(
_("No authorized MX record found for this domain"))
return value
def validate_quota(self, value):
"""Convert quota to MB."""
return web_utils.size2integer(value, output_unit="MB")
def validate_default_mailbox_quota(self, value):
"""Convert quota to MB."""
return web_utils.size2integer(value, output_unit="MB")
def validate(self, data):
"""Check quota values."""
quota = data.get("quota", 0)
default_mailbox_quota = data.get("default_mailbox_quota", 0)
if quota != 0 and default_mailbox_quota > quota:
raise serializers.ValidationError({
"default_mailbox_quota":
_("Cannot be greater than domain quota")
})
return data
def create(self, validated_data):
"""Set permissions."""
params = dict(param_tools.get_global_parameters("admin"))
domain = models.Domain(**validated_data)
condition = (
params["default_domain_message_limit"] is not None and
"message_limit" not in validated_data
)
if condition:
domain.message_limit = params["default_domain_message_limit"]
creator = self.context["request"].user
core_signals.can_create_object.send(
sender=self.__class__, context=creator,
klass=models.Domain, instance=domain)
domain.save(creator=creator)
return domain
class DomainAliasSerializer(FlexFieldsModelSerializer):
"""Base DomainAlias serializer."""
class Meta:
model = admin_models.DomainAlias
fields = ("pk", "name", "target", "enabled", )
expandable_fields = {
"target": DomainSerializer
}
def validate_target(self, value):
"""Check target domain."""
if not self.context["request"].user.can_access(value):
raise serializers.ValidationError(_("Permission denied."))
return value
def validate_name(self, value):
"""Lower case name."""
return value.lower()
def create(self, validated_data):
"""Custom creation."""
domain_alias = models.DomainAlias(**validated_data)
creator = self.context["request"].user
try:
core_signals.can_create_object.send(
sender=self.__class__, context=creator,
klass=models.DomainAlias)
core_signals.can_create_object.send(
sender=self.__class__, context=domain_alias.target,
object_type="domain_aliases")
except lib_exceptions.ModoboaException as inst:
raise serializers.ValidationError({
"domain": force_text(inst)})
domain_alias.save(creator=creator)
return domain_alias
class MailboxSerializer(serializers.ModelSerializer):
"""Base mailbox serializer."""
full_address = lib_fields.DRFEmailFieldUTF8()
quota = serializers.CharField(required=False)
class Meta:
model = models.Mailbox
fields = (
"pk", "full_address", "use_domain_quota", "quota", "message_limit"
)
def validate_full_address(self, value):
"""Lower case address."""
return value.lower()
def validate_quota(self, value):
"""Convert quota to MB."""
return web_utils.size2integer(value, output_unit="MB")
def validate(self, data):
"""Check if quota is required."""
method = self.context["request"].method
if not data.get("use_domain_quota", False):
if "quota" not in data and method != "PATCH":
raise serializers.ValidationError({
"quota": _("This field is required")
})
return data
class AccountSerializer(serializers.ModelSerializer):
"""Base account serializer."""
role = serializers.SerializerMethodField()
mailbox = MailboxSerializer(required=False)
domains = serializers.SerializerMethodField(
help_text=_(
"List of administered domains (resellers and domain "
"administrators only)."))
class Meta:
model = core_models.User
fields = (
"pk", "username", "first_name", "last_name", "is_active",
"master_user", "mailbox", "role", "language", "phone_number",
"secondary_email", "domains"
)
def __init__(self, *args, **kwargs):
"""Adapt fields to current user."""
super(AccountSerializer, self).__init__(*args, **kwargs)
request = self.context.get("request")
if not request:
return
user = self.context["request"].user
if not user.is_superuser:
del self.fields["master_user"]
@extend_schema_field(OpenApiTypes.STR)
def get_role(self, account):
"""Return role."""
return account.role
def get_domains(self, account) -> List[str]:
"""Return domains administered by this account."""
if account.role not in ["DomainAdmins", "Resellers"]:
return []
return admin_models.Domain.objects.get_for_admin(account).values_list(
"name", flat=True)
class AccountExistsSerializer(serializers.Serializer):
"""Simple serializer used with existence checks."""
exists = serializers.BooleanField()
class AccountPasswordSerializer(serializers.ModelSerializer):
"""A serializer used to change a user password."""
new_password = serializers.CharField()
class Meta:
model = core_models.User
fields = (
"password", "new_password", )
def validate_password(self, value):
"""Check password."""
if not self.instance.check_password(value):
raise serializers.ValidationError("Password not correct")
return value
def validate_new_password(self, value):
"""Check new password."""
try:
password_validation.validate_password(value, self.instance)
except ValidationError as exc:
raise serializers.ValidationError(exc.messages[0])
return value
def update(self, instance, validated_data):
"""Set new password."""
instance.set_password(validated_data["new_password"])
instance.save()
return instance
class WritableAccountSerializer(AccountSerializer):
"""Serializer to create account."""
random_password = serializers.BooleanField(default=False)
role = serializers.ChoiceField(choices=core_constants.ROLES)
password = serializers.CharField(required=False)
class Meta(AccountSerializer.Meta):
fields = AccountSerializer.Meta.fields + (
"password", "random_password")
def __init__(self, *args, **kwargs):
"""Adapt fields to current user."""
super().__init__(*args, **kwargs)
request = self.context.get("request")
if not request:
return
user = self.context["request"].user
self.fields["role"] = serializers.ChoiceField(
choices=permissions.get_account_roles(user))
self.fields["domains"] = serializers.ListField(
child=serializers.CharField(), allow_empty=False, required=False)
def validate_username(self, value):
"""Lower case username."""
return value.lower()
def validate(self, data):
"""Check constraints."""
master_user = data.get("master_user", False)
role = data.get("role")
if master_user and role != "SuperAdmins":
raise serializers.ValidationError({
"master_user": _("Not allowed for this role.")
})
if role == "SimpleUsers":
username = data.get("username")
if username:
try:
validators.UTF8EmailValidator()(username)
except ValidationError as err:
raise ValidationError({"username": err.message})
mailbox = data.get("mailbox")
if mailbox is None:
if not self.instance:
data["mailbox"] = {
"full_address": username,
"use_domain_quota": True
}
elif "full_address" in mailbox and mailbox["full_address"] != username:
raise serializers.ValidationError({
"username": _("Must be equal to mailbox full_address")
})
condition = (
not data.get("random_password") and (
data.get("password") or
not self.partial
)
)
if condition:
password = data.get("password")
if password:
try:
password_validation.validate_password(
data["password"], self.instance)
except ValidationError as exc:
raise serializers.ValidationError({
"password": exc.messages[0]})
elif not self.instance:
raise serializers.ValidationError({
"password": _("This field is required.")
})
domain_names = data.get("domains")
if not domain_names:
return data
domains = []
for name in domain_names:
domain = admin_models.Domain.objects.filter(name=name).first()
if domain:
domains.append(domain)
continue
raise serializers.ValidationError({
"domains": _("Local domain {} does not exist").format(name)
})
data["domains"] = domains
return data
def _create_mailbox(self, creator, account, data):
"""Create a new Mailbox instance."""
full_address = data.pop("full_address")
address, domain_name = email_utils.split_mailbox(full_address)
domain = get_object_or_404(
admin_models.Domain, name=domain_name)
if not creator.can_access(domain):
raise serializers.ValidationError({
"domain": _("Permission denied.")})
try:
core_signals.can_create_object.send(
sender=self.__class__, context=creator,
klass=admin_models.Mailbox)
core_signals.can_create_object.send(
sender=self.__class__, context=domain,
object_type="mailboxes")
except lib_exceptions.ModoboaException as inst:
raise serializers.ValidationError({
"domain": force_text(inst)})
quota = data.pop("quota", None)
mb = admin_models.Mailbox(
user=account, address=address, domain=domain, **data)
mb.set_quota(quota, creator.has_perm("admin.add_domain"))
default_msg_limit = param_tools.get_global_parameter(
"default_mailbox_message_limit")
if default_msg_limit is not None:
mb.message_limit = default_msg_limit
mb.save(creator=creator)
account.email = full_address
return mb
def set_permissions(self, account, domains):
"""Assign permissions on domain(s)."""
if account.role not in ["DomainAdmins", "Resellers"]:
return
current_domains = admin_models.Domain.objects.get_for_admin(account)
for domain in current_domains:
if domain not in domains:
domain.remove_admin(account)
else:
domains.remove(domain)
for domain in domains:
domain.add_admin(account)
def create(self, validated_data):
"""Create appropriate objects."""
creator = self.context["request"].user
mailbox_data = validated_data.pop("mailbox", None)
role = validated_data.pop("role")
domains = validated_data.pop("domains", [])
random_password = validated_data.pop("random_password", False)
user = core_models.User(**validated_data)
if random_password:
password = lib.make_password()
else:
password = validated_data.pop("password")
user.set_password(password)
if "language" not in validated_data:
user.language = settings.LANGUAGE_CODE
user.save(creator=creator)
if mailbox_data:
self._create_mailbox(creator, user, mailbox_data)
user.role = role
self.set_permissions(user, domains)
return user
def update(self, instance, validated_data):
"""Update account and associated objects."""
mailbox_data = validated_data.pop("mailbox", None)
password = validated_data.pop("password", None)
domains = validated_data.pop("domains", [])
for key, value in validated_data.items():
setattr(instance, key, value)
if password:
instance.set_password(password)
if mailbox_data:
creator = self.context["request"].user
if instance.mailbox:
if "full_address" in mailbox_data:
# FIXME: compat, to remove ASAP.
mailbox_data["email"] = mailbox_data["full_address"]
instance.email = mailbox_data["full_address"]
instance.mailbox.update_from_dict(creator, mailbox_data)
else:
self._create_mailbox(creator, instance, mailbox_data)
instance.save()
self.set_permissions(instance, domains)
return instance
class AliasSerializer(serializers.ModelSerializer):
"""Alias serializer."""
address = lib_fields.DRFEmailFieldUTF8AndEmptyUser()
recipients = serializers.ListField(
child=lib_fields.DRFEmailFieldUTF8AndEmptyUser(),
allow_empty=False,
help_text=ugettext_lazy("A list of recipient")
)
class Meta:
model = admin_models.Alias
fields = (
"pk", "address", "enabled", "internal", "recipients"
)
def validate_address(self, value):
"""Check domain."""
local_part, self.domain = admin_models.validate_alias_address(
value, self.context["request"].user, instance=self.instance)
return value
def create(self, validated_data):
"""Create appropriate objects."""
creator = self.context["request"].user
return admin_models.Alias.objects.create(
creator=creator, domain=self.domain, **validated_data)
def update(self, instance, validated_data):
"""Update objects."""
recipients = validated_data.pop("recipients", None)
for key, value in validated_data.items():
setattr(instance, key, value)
instance.save()
instance.set_recipients(recipients)
return instance
class SenderAddressSerializer(serializers.ModelSerializer):
"""Base Alias serializer."""
address = lib_fields.DRFEmailFieldUTF8AndEmptyUser()
class Meta:
model = admin_models.SenderAddress
fields = ("pk", "address", "mailbox")
def validate_address(self, value):
"""Check domain."""
local_part, domain = email_utils.split_mailbox(value)
domain = admin_models.Domain.objects.filter(name=domain).first()
user = self.context["request"].user
if domain and not user.can_access(domain):
raise serializers.ValidationError(
_("You don't have access to this domain."))
return value
def validate_mailbox(self, value):
"""Check permission."""
user = self.context["request"].user
if not user.can_access(value):
raise serializers.ValidationError(
_("You don't have access to this mailbox."))
return value
class ResetPasswordSerializer(serializers.Serializer):
"""Serializer by the reset password endpoint."""
email = lib_fields.DRFEmailFieldUTF8()
| {
"repo_name": "modoboa/modoboa",
"path": "modoboa/admin/api/v1/serializers.py",
"copies": "1",
"size": "18548",
"license": "isc",
"hash": -3012546252885730300,
"line_mean": 35.5118110236,
"line_max": 86,
"alpha_frac": 0.5981777011,
"autogenerated": false,
"ratio": 4.513993672426381,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00004606105271323843,
"num_lines": 508
} |
"admin server-side commands"
from nectar.utils import logger
from nectar import index
from json import dumps, loads
from cerberus import Validator, ValidationError
class BadJsonMessage(Exception):
pass
class BadRequest(Exception):
pass
class BadSchema(Exception):
pass
validator = Validator()
def index_add(handler, values, index_name='seeded'):
logger.debug('index add_msg {}'.format(values))
# check in the handler already has an index_writer
if handler.index_writer:
handler.index_writer.add_document(**values)
else:
handler.index_writer = index.get_writer(index_name)
handler.index_writer.add_document(**values)
def seed_msg(*args):
index_add(*args)
seed_msg_schema = {'checksum': {'type': 'string',
'minlength': 64,
'maxlength': 64,
'required': True},
'tree_path': {'type': 'string',
'required': True},
'tree': {'type': 'string',
'required': True},
'path': {'type': 'string',
'required': True},
'size': {'type': 'number'},
'mtime': {'type': 'number'},
}
def plant_msg(*args):
index_add(*args, index='planted')
def ping_msg(handler, values):
return dumps(['pong'])
def route(self, handler, msg):
logger.debug('routing: {}'.format(msg))
try:
msg = loads(msg.decode())
except ValueError:
# Any ValueError means a bad json message
logger.debug('raising BadJsonMessage')
handler.send_data('["bad_json"]')
raise BadJsonMessage()
admin_commands = {'ping': (ping_msg, {}),
'seed': (seed_msg, seed_msg_schema),
'planted': (plant_msg, {})
}
try:
# split header from values
# default cmd_values is {}
try:
cmd_header = msg[0]
cmd_values = msg[1]
except IndexError:
cmd_values = {} # default
# grab func, schema and validate
func, schema = admin_commands[cmd_header]
try:
if not validator.validate(cmd_values, schema):
logger.info('msg not valid')
raise BadSchema()
except ValidationError:
logger.info('validation error')
raise BadSchema()
# run func
cmd_reply = func(handler, cmd_values)
if cmd_reply:
logger.debug('sending: {}'.format(cmd_reply))
handler.send_data(cmd_reply)
else:
# Ack if cmd_reply is empty
logger.debug('sending: {}'.format(dumps(['ack'])))
handler.send_data(dumps(['ack']))
except KeyError:
# Any KeyError means a bad request
handler.send_data(dumps(['bad_request']))
except BadSchema:
# Any KeyError means a bad request
handler.send_data(dumps(['bad_schema']))
except BadJsonMessage:
# Any KeyError means a bad request
handler.send_data(dumps(['bad_json']))
| {
"repo_name": "ramaro/pomares",
"path": "nectar/admin.py",
"copies": "1",
"size": "3215",
"license": "mit",
"hash": -6435075331049744000,
"line_mean": 28.495412844,
"line_max": 62,
"alpha_frac": 0.53281493,
"autogenerated": false,
"ratio": 4.321236559139785,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5354051489139785,
"avg_score": null,
"num_lines": null
} |
"""Admin settings for the CMS news app."""
from cms.admin import OnlineBaseAdmin, PageBaseAdmin
from django.conf import settings
from django.contrib import admin
from reversion.admin import VersionAdmin
from .models import STATUS_CHOICES, Article, Category, get_default_news_feed
@admin.register(Category)
class CategoryAdmin(PageBaseAdmin):
fieldsets = (
PageBaseAdmin.TITLE_FIELDS,
('Content', {
'fields': ['content_primary']
}),
PageBaseAdmin.PUBLICATION_FIELDS,
PageBaseAdmin.NAVIGATION_FIELDS,
PageBaseAdmin.SEO_FIELDS,
)
list_display = ['__str__']
class ArticleAdmin(PageBaseAdmin, VersionAdmin):
date_hierarchy = 'date'
search_fields = PageBaseAdmin.search_fields + ('content', 'summary',)
list_display = ['title', 'date', 'is_online']
list_filter = ['is_online', 'categories', 'status']
fieldsets = [
(None, {
'fields': ['title', 'slug', 'news_feed', 'date', 'status']
}),
('Content', {
'fields': ['image', 'content', 'summary']
}),
('Publication', {
'fields': ['categories', 'is_online'],
'classes': ['collapse']
}),
]
fieldsets.extend(PageBaseAdmin.fieldsets)
fieldsets.remove(PageBaseAdmin.TITLE_FIELDS)
fieldsets.remove(OnlineBaseAdmin.PUBLICATION_FIELDS)
raw_id_fields = ['image']
filter_horizontal = ['categories']
def get_fieldsets(self, request, obj=None):
fieldsets = super(ArticleAdmin, self).get_fieldsets(request, obj)
if not getattr(settings, 'NEWS_APPROVAL_SYSTEM', False):
for fieldset in fieldsets:
fieldset[1]['fields'] = tuple(x for x in fieldset[1]['fields'] if x != 'status')
return fieldsets
def get_form(self, request, obj=None, **kwargs):
form = super(ArticleAdmin, self).get_form(request, obj, **kwargs)
form.base_fields['news_feed'].initial = get_default_news_feed()
return form
def formfield_for_choice_field(self, db_field, request=None, **kwargs):
"""
Give people who have the permission to approve articles an extra
option to change the status of an Article to approved
"""
if request:
choices_list = STATUS_CHOICES
if getattr(settings, 'NEWS_APPROVAL_SYSTEM', False) and not request.user.has_perm('news.can_approve_articles'):
choices_list = [x for x in STATUS_CHOICES if x[0] != 'approved']
if db_field.name == 'status':
kwargs['choices'] = choices_list
return super(ArticleAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)
admin.site.register(Article, ArticleAdmin)
| {
"repo_name": "onespacemedia/cms-news",
"path": "apps/news/admin.py",
"copies": "1",
"size": "2763",
"license": "mit",
"hash": -4960140881318245000,
"line_mean": 31.5058823529,
"line_max": 123,
"alpha_frac": 0.6221498371,
"autogenerated": false,
"ratio": 3.9191489361702128,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5041298773270213,
"avg_score": null,
"num_lines": null
} |
"""Admin settings for the CMS news app."""
from django.conf import settings
from django.contrib import admin
from cms import externals
from cms.admin import PageBaseAdmin
from cms.apps.news.models import Category, Article, STATUS_CHOICES, \
get_default_news_feed
class CategoryAdmin(PageBaseAdmin):
"""Admin settings for the Category model."""
fieldsets = (
PageBaseAdmin.TITLE_FIELDS,
("Content", {
"fields": ("content_primary",),
}),
PageBaseAdmin.PUBLICATION_FIELDS,
PageBaseAdmin.NAVIGATION_FIELDS,
PageBaseAdmin.SEO_FIELDS,
)
admin.site.register(Category, CategoryAdmin)
class ArticleAdminBase(PageBaseAdmin):
"""Admin settings for the Article model."""
date_hierarchy = "date"
search_fields = PageBaseAdmin.search_fields + ("content", "summary",)
list_display = ("title", "date", "is_online",)
list_filter = ("is_online", "categories", "status",)
fieldsets = [
(None, {
"fields": ("title", "slug", "news_feed", "date", "status",),
}),
("Content", {
"fields": ("image", "content", "summary",),
}),
("Publication", {
"fields": ("categories", "authors", "is_online",),
"classes": ("collapse",),
}),
]
fieldsets.extend(PageBaseAdmin.fieldsets)
fieldsets.remove(PageBaseAdmin.TITLE_FIELDS)
raw_id_fields = ("image",)
filter_horizontal = ("categories", "authors",)
def save_related(self, request, form, formsets, change):
"""Saves the author of the article."""
super(ArticleAdminBase, self).save_related(request, form, formsets, change)
# For new articles, add in the current author.
if not change and not form.cleaned_data["authors"]:
form.instance.authors.add(request.user)
def get_fieldsets(self, request, obj=None):
fieldsets = super(ArticleAdminBase, self).get_fieldsets(request, obj)
if not getattr(settings, "NEWS_APPROVAL_SYSTEM", False):
for fieldset in fieldsets:
fieldset[1]['fields'] = tuple(x for x in fieldset[1]['fields'] if x != 'status')
return fieldsets
def get_form(self, request, obj=None, **kwargs):
form = super(ArticleAdminBase, self).get_form(request, obj, **kwargs)
form.base_fields['news_feed'].initial = get_default_news_feed()
return form
def formfield_for_choice_field(self, db_field, request, **kwargs):
"""
Give people who have the permission to approve articles an extra
option to change the status of an Article to approved
"""
choices_list = STATUS_CHOICES
if getattr(settings, "NEWS_APPROVAL_SYSTEM", False) and not request.user.has_perm('news.can_approve_articles'):
choices_list = [x for x in STATUS_CHOICES if not x[0] == 'approved']
if db_field.name == "status":
kwargs['choices'] = choices_list
return super(ArticleAdminBase, self).formfield_for_choice_field(db_field, request, **kwargs)
if externals.reversion:
class ArticleAdmin(ArticleAdminBase, externals.reversion["admin.VersionMetaAdmin"]):
list_display = ArticleAdminBase.list_display + ("get_date_modified",)
else:
class ArticleAdmin(ArticleAdminBase):
pass
admin.site.register(Article, ArticleAdmin)
| {
"repo_name": "lewiscollard/cms",
"path": "cms/apps/news/admin.py",
"copies": "1",
"size": "3395",
"license": "bsd-3-clause",
"hash": 1097291394800191700,
"line_mean": 30.7289719626,
"line_max": 119,
"alpha_frac": 0.6335787923,
"autogenerated": false,
"ratio": 3.956876456876457,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005984111939826734,
"num_lines": 107
} |
"""Admin settings for the CMS news app."""
from django.contrib import admin
from cms.admin import PageBaseAdmin
from cms.apps.news.models import Category, Article
class CategoryAdmin(PageBaseAdmin):
"""Admin settings for the Category model."""
fieldsets = (
PageBaseAdmin.TITLE_FIELDS,
("Content", {
"fields": ("content_primary",),
}),
PageBaseAdmin.PUBLICATION_FIELDS,
PageBaseAdmin.NAVIGATION_FIELDS,
PageBaseAdmin.SEO_FIELDS,
)
admin.site.register(Category, CategoryAdmin)
class ArticleAdmin(PageBaseAdmin):
"""Admin settings for the Article model."""
date_hierarchy = "date"
search_fields = PageBaseAdmin.search_fields + ("content", "summary",)
list_display = ("title", "date", "is_online", "get_date_modified",)
list_filter = ("is_online", "categories",)
fieldsets = (
(None, {
"fields": ("title", "url_title", "news_feed", "date",),
}),
("Content", {
"fields": ("image", "content", "summary",),
}),
("Publication", {
"fields": ("categories", "authors", "is_online",),
"classes": ("collapse",),
}),
PageBaseAdmin.NAVIGATION_FIELDS,
PageBaseAdmin.SEO_FIELDS,
)
raw_id_fields = ("image",)
filter_horizontal = ("categories", "authors",)
def save_related(self, request, form, formsets, change):
"""Saves the author of the article."""
super(ArticleAdmin, self).save_related(request, form, formsets, change)
# For new articles, add in the current author.
if not change and not form.cleaned_data["authors"]:
form.instance.authors.add(request.user)
admin.site.register(Article, ArticleAdmin) | {
"repo_name": "etianen/cms",
"path": "src/cms/apps/news/admin.py",
"copies": "2",
"size": "1829",
"license": "bsd-3-clause",
"hash": 2961693105342083000,
"line_mean": 26.7272727273,
"line_max": 79,
"alpha_frac": 0.5872061236,
"autogenerated": false,
"ratio": 4.11936936936937,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.039754689754689765,
"num_lines": 66
} |
"""Admin settings for the static media management application."""
from __future__ import unicode_literals
import os
from functools import partial
from django.core.files import File as DjangoFile
from django.core.files.temp import NamedTemporaryFile
from django.core.paginator import Paginator
from django.conf.urls import patterns, url
from django.contrib import admin, messages
from django.contrib.admin.views.main import IS_POPUP_VAR
from django.contrib.staticfiles.storage import staticfiles_storage
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseNotAllowed, Http404
from django.shortcuts import render, get_object_or_404
from django.template.defaultfilters import filesizeformat
from django.utils.text import Truncator
from sorl.thumbnail import get_thumbnail
from cms import permalinks, externals
from cms.apps.media.models import Label, File, Video
import requests
import json
class LabelAdmin(admin.ModelAdmin):
"""Admin settings for Label models."""
list_display = ("name",)
search_fields = ("name",)
admin.site.register(Label, LabelAdmin)
class VideoAdmin(admin.ModelAdmin):
def to_field_allowed(self, request, to_field):
"""
This is a workaround for issue #552 which will raise a security
exception in the media select popup with django 1.6.6.
According to the release notes, this should be fixed by the
yet (2014-09-22) unreleased 1.6.8, 1.5.11, 1.7.1.
Details: https://code.djangoproject.com/ticket/23329#comment:11
"""
if to_field == 'id':
return True
return super(VideoAdmin, self).to_field_allowed(request, to_field)
admin.site.register(Video, VideoAdmin)
# Different types of file.
AUDIO_FILE_ICON = static("media/img/audio-x-generic.png")
DOCUMENT_FILE_ICON = static("media/img/x-office-document.png")
SPREADSHEET_FILE_ICON = static("media/img/x-office-spreadsheet.png")
TEXT_FILE_ICON = static("media/img/text-x-generic.png")
IMAGE_FILE_ICON = static("media/img/image-x-generic.png")
MOVIE_FILE_ICON = static("media/img/video-x-generic.png")
UNKNOWN_FILE_ICON = static("media/img/text-x-generic-template.png")
# Different types of recognised file extensions.
FILE_ICONS = {
"mp3": AUDIO_FILE_ICON,
"m4a": AUDIO_FILE_ICON,
"wav": AUDIO_FILE_ICON,
"doc": DOCUMENT_FILE_ICON,
"odt": DOCUMENT_FILE_ICON,
"pdf": DOCUMENT_FILE_ICON,
"xls": SPREADSHEET_FILE_ICON,
"txt": TEXT_FILE_ICON,
"png": IMAGE_FILE_ICON,
"gif": IMAGE_FILE_ICON,
"jpg": IMAGE_FILE_ICON,
"jpeg": IMAGE_FILE_ICON,
"swf": MOVIE_FILE_ICON,
"flv": MOVIE_FILE_ICON,
"mp4": MOVIE_FILE_ICON,
"mov": MOVIE_FILE_ICON,
"wmv": MOVIE_FILE_ICON,
'webm': MOVIE_FILE_ICON,
'm4v': MOVIE_FILE_ICON,
}
class FileAdminBase(admin.ModelAdmin):
"""Admin settings for File models."""
change_list_template = 'admin/media/file/change_list.html'
fieldsets = [
(None, {
'fields': ["title", "file"],
}),
('Media management', {
'fields': ['attribution', 'copyright', 'alt_text', 'labels'],
}),
]
filter_horizontal = ['labels']
list_display = ['get_preview', 'get_title', 'get_size']
list_filter = ['labels']
search_fields = ['title']
def to_field_allowed(self, request, to_field):
"""
This is a workaround for issue #552 which will raise a security
exception in the media select popup with django 1.6.6.
According to the release notes, this should be fixed by the
yet (2014-09-22) unreleased 1.6.8, 1.5.11, 1.7.1.
Details: https://code.djangoproject.com/ticket/23329#comment:11
"""
if to_field == 'id':
return True
return super(FileAdminBase, self).to_field_allowed(request, to_field)
# Custom actions.
def add_label_action(self, request, queryset, label):
"""Adds the label on the given queryset."""
for file in queryset:
file.labels.add(label)
def remove_label_action(self, request, queryset, label):
"""Removes the label on the given queryset."""
for file in queryset:
file.labels.remove(label)
def get_actions(self, request):
"""Generates the actions for assigning categories."""
if IS_POPUP_VAR in request.GET:
return []
opts = self.model._meta
verbose_name_plural = opts.verbose_name_plural
actions = super(FileAdminBase, self).get_actions(request)
# Add the dynamic labels.
for label in Label.objects.all():
# Add action.
action_function = partial(self.__class__.add_label_action, label=label)
action_description = 'Remove label %s from selected %s"' % (label.name, verbose_name_plural)
action_name = action_description.lower().replace(" ", "_")
actions[action_name] = (action_function, action_name, action_description)
# Remove action.
action_function = partial(self.__class__.remove_label_action, label=label)
action_description = 'Remove label %s from selected %s"' % (label.name, verbose_name_plural)
action_name = action_description.lower().replace(" ", "_")
actions[action_name] = (action_function, action_name, action_description)
return actions
# Custom display routines.
def get_size(self, obj):
"""Returns the size of the media in a human-readable format."""
try:
return filesizeformat(obj.file.size)
except OSError:
return "0 bytes"
get_size.short_description = "size"
def get_preview(self, obj):
"""Generates a thumbnail of the image."""
_, extension = os.path.splitext(obj.file.name)
extension = extension.lower()[1:]
icon = FILE_ICONS.get(extension, UNKNOWN_FILE_ICON)
permalink = permalinks.create(obj)
if icon == IMAGE_FILE_ICON:
try:
thumbnail = get_thumbnail(obj.file, '100x66', quality=99)
except IOError:
return '<img cms:permalink="{}" src="{}" width="66" height="66" alt="" title="{}"/>'.format(
permalink,
icon,
obj.title
)
else:
try:
return '<img cms:permalink="{}" src="{}" width="{}" height="{}" alt="" title="{}"/>'.format(
permalink,
thumbnail.url,
thumbnail.width,
thumbnail.height,
obj.title
)
except TypeError:
return '<img cms:permalink="{}" src="{}" width="66" height="66" alt="" title="{}"/>'.format(
permalink,
icon,
obj.title
)
else:
icon = staticfiles_storage.url(icon)
return '<img cms:permalink="{}" src="{}" width="66" height="66" alt="" title="{}"/>'.format(
permalink,
icon,
obj.title
)
get_preview.short_description = "preview"
get_preview.allow_tags = True
def get_title(self, obj):
"""Returns a truncated title of the object."""
return Truncator(obj.title).words(8)
get_title.short_description = "title"
# Custom view logic.
def response_add(self, request, obj, *args, **kwargs):
"""Returns the response for a successful add action."""
if "_tinymce" in request.GET:
context = {"permalink": permalinks.create(obj),
"title": obj.title}
return render(request, "admin/media/file/filebrowser_add_success.html", context)
return super(FileAdminBase, self).response_add(request, obj, *args, **kwargs)
def changelist_view(self, request, extra_context=None):
"""Renders the change list."""
context = {
"changelist_template_parent": externals.reversion and "reversion/change_list.html" or "admin/change_list.html",
}
if extra_context:
context.update(extra_context)
return super(FileAdminBase, self).changelist_view(request, context)
# Create a URL route and a view for saving the Adobe SDK callback URL.
def get_urls(self):
urls = super(FileAdminBase, self).get_urls()
new_urls = patterns(
'',
url(r'^(?P<object_id>\d+)/remote/$', self.remote_view, name="media_file_remote"),
url(r'^redactor/upload/(?P<file_type>image|file)/$', self.redactor_upload, name="media_file_redactor_upload"),
url(r'^redactor/(?P<file_type>images|files)/$', self.redactor_data, name="media_file_redactor_data"),
url(r'^redactor/(?P<file_type>images|files)/(?P<page>\d+)/$', self.redactor_data, name="media_file_redactor_data"),
)
return new_urls + urls
def remote_view(self, request, object_id):
if not self.has_change_permission(request):
return HttpResponseForbidden("You do not have permission to modify this file.")
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
url = request.POST.get('url', None)
if not url:
raise Http404("No URL supplied.")
# Pull down the remote image and save it as a temporary file.
img_temp = NamedTemporaryFile()
img_temp.write(requests.get(url).content)
img_temp.flush()
obj = get_object_or_404(File, pk=object_id)
obj.file.save(url.split('/')[-1], DjangoFile(img_temp))
messages.success(request, 'The file "{}" was changed successfully. You may edit it again below.'.format(
obj.__str__()
))
return HttpResponse('{"status": "ok"}', content_type='application/json')
def redactor_data(self, request, **kwargs):
if not self.has_change_permission(request):
return HttpResponseForbidden("You do not have permission to view these files.")
file_type = kwargs.get('file_type', 'files')
page = kwargs.get('page', 1)
# Make sure we serve the correct data
if file_type == 'files':
file_objects = File.objects.all()
elif file_type == 'images':
file_objects = File.objects.filter(file__regex=r'(?i)\.(png|gif|jpg|jpeg)$')
# Sort objects by title
file_objects = file_objects.order_by('title')
# Create paginator
paginator = Paginator(file_objects, 15)
# Create files usable by the CMS
json_data = {
'page': page,
'pages': paginator.page_range,
}
if file_type == 'files':
json_data['objects'] = [
{'title': file_object.title, 'url': permalinks.create(file_object)}
for file_object in paginator.page(page)
]
elif file_type == 'images':
json_data['objects'] = [
{'title': file_object.title, 'url': permalinks.create(file_object), 'thumbnail': get_thumbnail(file_object.file, '100x75', crop="center", quality=99).url}
for file_object in paginator.page(page)
]
# Return files as ajax
return HttpResponse(json.dumps(json_data), content_type='application/json')
def redactor_upload(self, request, file_type):
if not self.has_change_permission(request):
return HttpResponseForbidden("You do not have permission to upload this file.")
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
image_content_types = [
'image/gif',
'image/jpeg',
'image/png',
'image/bmp'
]
try:
if file_type == 'image':
if request.FILES.getlist('file')[0].content_type not in image_content_types:
raise Exception()
new_file = File(
title=request.FILES.getlist('file')[0].name,
file=request.FILES.getlist('file')[0]
)
new_file.save()
if file_type == 'image':
return HttpResponse(json.dumps({
'filelink': permalinks.create(new_file)
}))
else:
return HttpResponse(json.dumps({
'filelink': permalinks.create(new_file),
'filename': request.FILES.getlist('file')[0].name,
}))
except:
return HttpResponse('')
# Renaming needed to allow inheritance to take place in this class without infinite recursion.
FileAdmin = FileAdminBase
if externals.reversion:
class FileAdmin(FileAdmin, externals.reversion["admin.VersionMetaAdmin"]):
list_display = FileAdmin.list_display + ["get_date_modified"]
if externals.watson:
class FileAdmin(FileAdmin, externals.watson["admin.SearchAdmin"]):
pass
admin.site.register(File, FileAdmin)
| {
"repo_name": "dan-gamble/cms",
"path": "cms/apps/media/admin.py",
"copies": "1",
"size": "13204",
"license": "bsd-3-clause",
"hash": 2716498346055599600,
"line_mean": 34.9782016349,
"line_max": 170,
"alpha_frac": 0.5984550136,
"autogenerated": false,
"ratio": 3.9497457373616514,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5048200750961651,
"avg_score": null,
"num_lines": null
} |
"""Admin settings for the static media management application."""
import os
from functools import partial
from django.contrib import admin
from django.contrib.admin.views.main import IS_POPUP_VAR
from django.shortcuts import render
from django.template.defaultfilters import filesizeformat
from django.utils.text import Truncator
import optimizations
from cms import permalinks, externals
from cms.apps.media.models import Label, File
class LabelAdmin(admin.ModelAdmin):
"""Admin settings for Label models."""
list_display = ("name",)
search_fields = ("name",)
admin.site.register(Label, LabelAdmin)
# Different types of file.
AUDIO_FILE_ICON = "media/img/audio-x-generic.png"
DOCUMENT_FILE_ICON = "media/img/x-office-document.png"
SPREADSHEET_FILE_ICON = "media/img/x-office-spreadsheet.png"
TEXT_FILE_ICON = "media/img/text-x-generic.png"
IMAGE_FILE_ICON = "media/img/image-x-generic.png"
MOVIE_FILE_ICON = "media/img/video-x-generic.png"
UNKNOWN_FILE_ICON = "media/img/text-x-generic-template.png"
# Different types of recognised file extensions.
FILE_ICONS = {
"mp3": AUDIO_FILE_ICON,
"m4a": AUDIO_FILE_ICON,
"wav": AUDIO_FILE_ICON,
"doc": DOCUMENT_FILE_ICON,
"odt": DOCUMENT_FILE_ICON,
"pdf": DOCUMENT_FILE_ICON,
"xls": SPREADSHEET_FILE_ICON,
"txt": TEXT_FILE_ICON,
"png": IMAGE_FILE_ICON,
"gif": IMAGE_FILE_ICON,
"jpg": IMAGE_FILE_ICON,
"jpeg": IMAGE_FILE_ICON,
"swf": MOVIE_FILE_ICON,
"flv": MOVIE_FILE_ICON,
"mp4": MOVIE_FILE_ICON,
"mov": MOVIE_FILE_ICON,
"wmv": MOVIE_FILE_ICON,
}
class FileAdminBase(admin.ModelAdmin):
"""Admin settings for File models."""
fieldsets = (
(None, {
"fields": ("title", "file",),
},),
("Media management", {
"fields": ("labels",),
"classes": ("collapse",),
},),
)
list_filter = ("labels",)
search_fields = ("title",)
list_display = ("get_preview", "get_title", "get_size",)
change_list_template = "admin/media/file/change_list.html"
filter_horizontal = ("labels",)
# Customizations.
def lookup_allowed(self, lookup, *args, **kwargs):
"""Allows the file iregex lookup needed by TinyMCE integration."""
if lookup == "file__iregex":
return True
return super(FileAdminBase, self).lookup_allowed(lookup, *args, **kwargs)
# Custom actions.
def add_label_action(self, request, queryset, label):
"""Adds the label on the given queryset."""
for file in queryset:
file.labels.add(label)
def remove_label_action(self, request, queryset, label):
"""Removes the label on the given queryset."""
for file in queryset:
file.labels.remove(label)
def get_actions(self, request):
"""Generates the actions for assigning categories."""
if IS_POPUP_VAR in request.GET:
return []
opts = self.model._meta
verbose_name_plural = opts.verbose_name_plural
actions = super(FileAdminBase, self).get_actions(request)
# Add the dynamic labels.
for label in Label.objects.all():
# Add action.
action_function = partial(self.__class__.add_label_action, label=label)
action_description = u'Remove label %s from selected %s"' % (label.name, verbose_name_plural)
action_name = action_description.lower().replace(" ", "_")
actions[action_name] = (action_function, action_name, action_description)
# Remove action.
action_function = partial(self.__class__.remove_label_action, label=label)
action_description = u'Remove label %s from selected %s"' % (label.name, verbose_name_plural)
action_name = action_description.lower().replace(" ", "_")
actions[action_name] = (action_function, action_name, action_description)
return actions
def remove_label(self, request, queryset):
"""Removes the label from selected files."""
queryset.update(label=None)
# Custom display routines.
def get_label(self, obj):
"""Returns a pretty version of the label."""
if obj.label:
return obj.label.name
return ""
get_label.short_description = "label"
get_label.admin_order_field = "label"
def get_size(self, obj):
"""Returns the size of the media in a human-readable format."""
try:
return filesizeformat(obj.file.size)
except OSError:
return "0 bytes"
get_size.short_description = "size"
def get_preview(self, obj):
"""Generates a thumbnail of the image."""
_, extension = os.path.splitext(obj.file.name)
extension = extension.lower()[1:]
icon = FILE_ICONS.get(extension, UNKNOWN_FILE_ICON)
permalink = permalinks.create(obj)
if icon == IMAGE_FILE_ICON:
try:
thumbnail = optimizations.get_thumbnail(obj.file, 100, 66)
except IOError:
pass
else:
return '<img cms:permalink="%s" src="%s" width="%s" height="%s" alt="" title="%s"/>' % (permalink, thumbnail.url, thumbnail.width, thumbnail.height, obj.title)
else:
icon = optimizations.get_url(icon)
return '<img cms:permalink="%s" src="%s" width="66" height="66" alt="" title="%s"/>' % (permalink, icon, obj.title)
get_preview.short_description = "preview"
get_preview.allow_tags = True
def get_title(self, obj):
"""Returns a truncated title of the object."""
return Truncator(obj.title).words(8)
get_title.short_description = "title"
# Custom view logic.
def response_add(self, request, obj, *args, **kwargs):
"""Returns the response for a successful add action."""
if "_tinymce" in request.GET:
context = {"permalink": permalinks.create(obj),
"title": obj.title}
return render(request, "admin/media/file/filebrowser_add_success.html", context)
return super(FileAdminBase, self).response_add(request, obj, *args, **kwargs)
def changelist_view(self, request, extra_context=None):
"""Renders the change list."""
context = {
"changelist_template_parent": externals.reversion and "reversion/change_list.html" or "admin/change_list.html",
}
if extra_context:
context.update(extra_context)
return super(FileAdminBase, self).changelist_view(request, context)
# Renaming needed to allow inheritance to take place in this class without infinite recursion.
FileAdmin = FileAdminBase
if externals.reversion:
class FileAdmin(FileAdmin, externals.reversion["admin.VersionMetaAdmin"]):
list_display = FileAdmin.list_display + ("get_date_modified",)
if externals.watson:
class FileAdmin(FileAdmin, externals.watson["admin.SearchAdmin"]):
pass
admin.site.register(File, FileAdmin)
| {
"repo_name": "etianen/cms",
"path": "src/cms/apps/media/admin.py",
"copies": "2",
"size": "7178",
"license": "bsd-3-clause",
"hash": -1386376479596811300,
"line_mean": 33.8446601942,
"line_max": 175,
"alpha_frac": 0.6179994427,
"autogenerated": false,
"ratio": 3.8160552897395004,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.54340547324395,
"avg_score": null,
"num_lines": null
} |
"""Admin settings for the static media management application."""
import os
from functools import partial
from django.core.files import File as DjangoFile
from django.core.files.temp import NamedTemporaryFile
from django.core.paginator import Paginator
from django.conf.urls import patterns, url
from django.contrib import admin, messages
from django.contrib.admin.views.main import IS_POPUP_VAR
from django.contrib.staticfiles.storage import staticfiles_storage
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseNotAllowed, Http404
from django.shortcuts import render, get_object_or_404
from django.template.defaultfilters import filesizeformat
from django.utils.text import Truncator
from sorl.thumbnail import get_thumbnail
from cms import permalinks, externals
from cms.apps.media.models import Label, File, Video
import requests
import json
class LabelAdmin(admin.ModelAdmin):
"""Admin settings for Label models."""
list_display = ("name",)
search_fields = ("name",)
admin.site.register(Label, LabelAdmin)
class VideoAdmin(admin.ModelAdmin):
def to_field_allowed(self, request, to_field):
"""
This is a workaround for issue #552 which will raise a security
exception in the media select popup with django 1.6.6.
According to the release notes, this should be fixed by the
yet (2014-09-22) unreleased 1.6.8, 1.5.11, 1.7.1.
Details: https://code.djangoproject.com/ticket/23329#comment:11
"""
if to_field == 'id':
return True
return super(VideoAdmin, self).to_field_allowed(request, to_field)
admin.site.register(Video, VideoAdmin)
# Different types of file.
AUDIO_FILE_ICON = "media/img/audio-x-generic.png"
DOCUMENT_FILE_ICON = "media/img/x-office-document.png"
SPREADSHEET_FILE_ICON = "media/img/x-office-spreadsheet.png"
TEXT_FILE_ICON = "media/img/text-x-generic.png"
IMAGE_FILE_ICON = "media/img/image-x-generic.png"
MOVIE_FILE_ICON = "media/img/video-x-generic.png"
UNKNOWN_FILE_ICON = "media/img/text-x-generic-template.png"
# Different types of recognised file extensions.
FILE_ICONS = {
"mp3": AUDIO_FILE_ICON,
"m4a": AUDIO_FILE_ICON,
"wav": AUDIO_FILE_ICON,
"doc": DOCUMENT_FILE_ICON,
"odt": DOCUMENT_FILE_ICON,
"pdf": DOCUMENT_FILE_ICON,
"xls": SPREADSHEET_FILE_ICON,
"txt": TEXT_FILE_ICON,
"png": IMAGE_FILE_ICON,
"gif": IMAGE_FILE_ICON,
"jpg": IMAGE_FILE_ICON,
"jpeg": IMAGE_FILE_ICON,
"swf": MOVIE_FILE_ICON,
"flv": MOVIE_FILE_ICON,
"mp4": MOVIE_FILE_ICON,
"mov": MOVIE_FILE_ICON,
"wmv": MOVIE_FILE_ICON,
'webm': MOVIE_FILE_ICON,
'm4v': MOVIE_FILE_ICON,
}
class FileAdminBase(admin.ModelAdmin):
"""Admin settings for File models."""
fieldsets = (
(None, {
"fields": ("title", "file",),
},),
("Media management", {
"fields": ("attribution", "copyright", "labels",),
},),
)
list_filter = ("labels",)
search_fields = ("title",)
list_display = ("get_preview", "get_title", "get_size",)
change_list_template = "admin/media/file/change_list.html"
filter_horizontal = ("labels",)
def to_field_allowed(self, request, to_field):
"""
This is a workaround for issue #552 which will raise a security
exception in the media select popup with django 1.6.6.
According to the release notes, this should be fixed by the
yet (2014-09-22) unreleased 1.6.8, 1.5.11, 1.7.1.
Details: https://code.djangoproject.com/ticket/23329#comment:11
"""
if to_field == 'id':
return True
return super(FileAdminBase, self).to_field_allowed(request, to_field)
# Custom actions.
def add_label_action(self, request, queryset, label):
"""Adds the label on the given queryset."""
for file in queryset:
file.labels.add(label)
def remove_label_action(self, request, queryset, label):
"""Removes the label on the given queryset."""
for file in queryset:
file.labels.remove(label)
def get_actions(self, request):
"""Generates the actions for assigning categories."""
if IS_POPUP_VAR in request.GET:
return []
opts = self.model._meta
verbose_name_plural = opts.verbose_name_plural
actions = super(FileAdminBase, self).get_actions(request)
# Add the dynamic labels.
for label in Label.objects.all():
# Add action.
action_function = partial(self.__class__.add_label_action, label=label)
action_description = 'Remove label %s from selected %s"' % (label.name, verbose_name_plural)
action_name = action_description.lower().replace(" ", "_")
actions[action_name] = (action_function, action_name, action_description)
# Remove action.
action_function = partial(self.__class__.remove_label_action, label=label)
action_description = 'Remove label %s from selected %s"' % (label.name, verbose_name_plural)
action_name = action_description.lower().replace(" ", "_")
actions[action_name] = (action_function, action_name, action_description)
return actions
# Custom display routines.
def get_size(self, obj):
"""Returns the size of the media in a human-readable format."""
try:
return filesizeformat(obj.file.size)
except OSError:
return "0 bytes"
get_size.short_description = "size"
def get_preview(self, obj):
"""Generates a thumbnail of the image."""
_, extension = os.path.splitext(obj.file.name)
extension = extension.lower()[1:]
icon = FILE_ICONS.get(extension, UNKNOWN_FILE_ICON)
permalink = permalinks.create(obj)
if icon == IMAGE_FILE_ICON:
try:
thumbnail = get_thumbnail(obj.file, '100x66', quality=99)
except IOError:
pass
else:
try:
return '<img cms:permalink="{}" src="{}" width="{}" height="{}" alt="" title="{}"/>'.format(
permalink,
thumbnail.url,
thumbnail.width,
thumbnail.height,
obj.title
)
except TypeError:
pass
else:
icon = staticfiles_storage.url(icon)
return '<img cms:permalink="{}" src="{}" width="66" height="66" alt="" title="{}"/>'.format(
permalink,
icon,
obj.title
)
get_preview.short_description = "preview"
get_preview.allow_tags = True
def get_title(self, obj):
"""Returns a truncated title of the object."""
return Truncator(obj.title).words(8)
get_title.short_description = "title"
# Custom view logic.
def response_add(self, request, obj, *args, **kwargs):
"""Returns the response for a successful add action."""
if "_redactor" in request.GET:
context = {"permalink": permalinks.create(obj),
"title": obj.title}
return render(request, "admin/media/file/filebrowser_add_success.html", context)
return super(FileAdminBase, self).response_add(request, obj, *args, **kwargs)
def changelist_view(self, request, extra_context=None):
"""Renders the change list."""
context = {
"changelist_template_parent": externals.reversion and "reversion/change_list.html" or "admin/change_list.html",
}
if extra_context:
context.update(extra_context)
return super(FileAdminBase, self).changelist_view(request, context)
# Create a URL route and a view for saving the Adobe SDK callback URL.
def get_urls(self):
urls = super(FileAdminBase, self).get_urls()
new_urls = patterns(
'',
url(r'^(?P<object_id>\d+)/remote/$', self.remote_view, name="media_file_remote"),
url(r'^redactor/upload/(?P<file_type>image|file)/$', self.redactor_upload, name="media_file_redactor_upload"),
url(r'^redactor/(?P<file_type>images|files)/$', self.redactor_data, name="media_file_redactor_data"),
url(r'^redactor/(?P<file_type>images|files)/(?P<page>\d+)/$', self.redactor_data, name="media_file_redactor_data"),
)
return new_urls + urls
def remote_view(self, request, object_id):
if not self.has_change_permission(request):
return HttpResponseForbidden("You do not have permission to modify this file.")
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
url = request.POST.get('url', None)
if not url:
raise Http404("No URL supplied.")
# Pull down the remote image and save it as a temporary file.
img_temp = NamedTemporaryFile()
img_temp.write(requests.get(url).content)
img_temp.flush()
obj = get_object_or_404(File, pk=object_id)
obj.file.save(url.split('/')[-1], DjangoFile(img_temp))
messages.success(request, 'The file "{}" was changed successfully. You may edit it again below.'.format(
obj.__str__()
))
return HttpResponse('{"status": "ok"}', content_type='application/json')
def redactor_data(self, request, **kwargs):
if not self.has_change_permission(request):
return HttpResponseForbidden("You do not have permission to view these files.")
file_type = kwargs.get('file_type', 'files')
page = kwargs.get('page', 1)
# Make sure we serve the correct data
if file_type == 'files':
file_objects = File.objects.all()
elif file_type == 'images':
file_objects = File.objects.filter(file__regex=r'(?i)\.(png|gif|jpg|jpeg)$')
# Sort objects by title
file_objects = file_objects.order_by('title')
# Create paginator
paginator = Paginator(file_objects, 15)
# Create files usable by the CMS
json_data = {
'page': page,
'pages': paginator.page_range,
}
if file_type == 'files':
json_data['objects'] = [
{'title': file_object.title, 'url': permalinks.create(file_object)}
for file_object in paginator.page(page)
]
elif file_type == 'images':
json_data['objects'] = [
{'title': file_object.title, 'url': permalinks.create(file_object), 'thumbnail': get_thumbnail(file_object.file, '100x75', crop="center", quality=99).url}
for file_object in paginator.page(page)
]
# Return files as ajax
return HttpResponse(json.dumps(json_data), content_type='application/json')
def redactor_upload(self, request, file_type):
if not self.has_change_permission(request):
return HttpResponseForbidden("You do not have permission to upload this file.")
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
image_content_types = [
'image/gif',
'image/jpeg',
'image/png',
'image/bmp'
]
try:
if file_type == 'image':
if request.FILES.getlist('file')[0].content_type not in image_content_types:
raise Exception()
new_file = File(
title=request.FILES.getlist('file')[0].name,
file=request.FILES.getlist('file')[0]
)
new_file.save()
if file_type == 'image':
return HttpResponse(json.dumps({
'filelink': permalinks.create(new_file)
}))
else:
return HttpResponse(json.dumps({
'filelink': permalinks.create(new_file),
'filename': request.FILES.getlist('file')[0].name,
}))
except:
return HttpResponse('')
# Renaming needed to allow inheritance to take place in this class without infinite recursion.
FileAdmin = FileAdminBase
if externals.reversion:
class FileAdmin(FileAdmin, externals.reversion["admin.VersionMetaAdmin"]):
list_display = FileAdmin.list_display + ("get_date_modified",)
if externals.watson:
class FileAdmin(FileAdmin, externals.watson["admin.SearchAdmin"]):
pass
admin.site.register(File, FileAdmin)
| {
"repo_name": "danielsamuels/cms",
"path": "cms/apps/media/admin.py",
"copies": "2",
"size": "12638",
"license": "bsd-3-clause",
"hash": -2195960247288868600,
"line_mean": 33.9116022099,
"line_max": 170,
"alpha_frac": 0.6029435037,
"autogenerated": false,
"ratio": 3.9187596899224806,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0010086215406613461,
"num_lines": 362
} |
"""Admin settings"""
from django.conf import settings
from django.contrib import admin
from social.utils import setting_name
from social.apps.django_app.default.compat import get_all_field_names_from_options
from social.apps.django_app.default.models import UserSocialAuth, Nonce, \
Association
class UserSocialAuthOption(admin.ModelAdmin):
"""Social Auth user options"""
list_display = ('user', 'id', 'provider', 'uid')
list_filter = ('provider',)
raw_id_fields = ('user',)
list_select_related = True
def get_search_fields(self, request=None):
search_fields = getattr(
settings, setting_name('ADMIN_USER_SEARCH_FIELDS'), None
)
if search_fields is None:
_User = UserSocialAuth.user_model()
username = getattr(_User, 'USERNAME_FIELD', None) or \
hasattr(_User, 'username') and 'username' or \
None
fieldnames = ('first_name', 'last_name', 'email', username)
all_names = get_all_field_names_from_options(_User._meta)
search_fields = [name for name in fieldnames
if name and name in all_names]
return ['user__' + name for name in search_fields]
class NonceOption(admin.ModelAdmin):
"""Nonce options"""
list_display = ('id', 'server_url', 'timestamp', 'salt')
search_fields = ('server_url',)
class AssociationOption(admin.ModelAdmin):
"""Association options"""
list_display = ('id', 'server_url', 'assoc_type')
list_filter = ('assoc_type',)
search_fields = ('server_url',)
admin.site.register(UserSocialAuth, UserSocialAuthOption)
admin.site.register(Nonce, NonceOption)
admin.site.register(Association, AssociationOption)
| {
"repo_name": "cmichal/python-social-auth",
"path": "social/apps/django_app/default/admin.py",
"copies": "2",
"size": "1814",
"license": "bsd-3-clause",
"hash": -1996341371485674800,
"line_mean": 36.0204081633,
"line_max": 82,
"alpha_frac": 0.6240352811,
"autogenerated": false,
"ratio": 4.013274336283186,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5637309617383186,
"avg_score": null,
"num_lines": null
} |
"""Admin settings"""
from django.conf import settings
from django.contrib import admin
from social.utils import setting_name
from social.apps.django_app.default.models import UserSocialAuth, Nonce, \
Association
class UserSocialAuthOption(admin.ModelAdmin):
"""Social Auth user options"""
list_display = ('id', 'user', 'provider', 'uid')
list_filter = ('provider',)
raw_id_fields = ('user',)
list_select_related = True
def get_search_fields(self, request=None):
search_fields = getattr(
settings, setting_name('ADMIN_USER_SEARCH_FIELDS'), None
)
if search_fields is None:
_User = UserSocialAuth.user_model()
username = getattr(_User, 'USERNAME_FIELD', None) or \
hasattr(_User, 'username') and 'username' or \
None
fieldnames = ('first_name', 'last_name', 'email', username)
all_names = _User._meta.get_all_field_names()
search_fields = [name for name in fieldnames
if name and name in all_names]
return ['user_' + name for name in search_fields]
class NonceOption(admin.ModelAdmin):
"""Nonce options"""
list_display = ('id', 'server_url', 'timestamp', 'salt')
search_fields = ('server_url',)
class AssociationOption(admin.ModelAdmin):
"""Association options"""
list_display = ('id', 'server_url', 'assoc_type')
list_filter = ('assoc_type',)
search_fields = ('server_url',)
admin.site.register(UserSocialAuth, UserSocialAuthOption)
admin.site.register(Nonce, NonceOption)
admin.site.register(Association, AssociationOption)
| {
"repo_name": "duoduo369/python-social-auth",
"path": "social/apps/django_app/default/admin.py",
"copies": "2",
"size": "1718",
"license": "bsd-3-clause",
"hash": 7619568021891054000,
"line_mean": 34.7916666667,
"line_max": 74,
"alpha_frac": 0.6123399302,
"autogenerated": false,
"ratio": 4.05188679245283,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.566422672265283,
"avg_score": null,
"num_lines": null
} |
"""Admin settings"""
from itertools import chain
from django.conf import settings
from django.contrib import admin
from social.utils import setting_name
from social.apps.django_app.default.models import UserSocialAuth, Nonce, \
Association
class UserSocialAuthOption(admin.ModelAdmin):
"""Social Auth user options"""
list_display = ('user', 'id', 'provider', 'uid')
list_filter = ('provider',)
raw_id_fields = ('user',)
list_select_related = True
def get_search_fields(self, request=None):
search_fields = getattr(
settings, setting_name('ADMIN_USER_SEARCH_FIELDS'), None
)
if search_fields is None:
_User = UserSocialAuth.user_model()
username = getattr(_User, 'USERNAME_FIELD', None) or \
hasattr(_User, 'username') and 'username' or \
None
fieldnames = ('first_name', 'last_name', 'email', username)
all_names = self._get_all_field_names(_User._meta)
search_fields = [name for name in fieldnames
if name and name in all_names]
return ['user__' + name for name in search_fields]
@staticmethod
def _get_all_field_names(model):
names = chain.from_iterable(
(field.name, field.attname)
if hasattr(field, 'attname') else (field.name,)
for field in model.get_fields()
# For complete backwards compatibility, you may want to exclude
# GenericForeignKey from the results.
if not (field.many_to_one and field.related_model is None)
)
return list(set(names))
class NonceOption(admin.ModelAdmin):
"""Nonce options"""
list_display = ('id', 'server_url', 'timestamp', 'salt')
search_fields = ('server_url',)
class AssociationOption(admin.ModelAdmin):
"""Association options"""
list_display = ('id', 'server_url', 'assoc_type')
list_filter = ('assoc_type',)
search_fields = ('server_url',)
admin.site.register(UserSocialAuth, UserSocialAuthOption)
admin.site.register(Nonce, NonceOption)
admin.site.register(Association, AssociationOption)
| {
"repo_name": "sbuss/voteswap",
"path": "lib/social/apps/django_app/default/admin.py",
"copies": "2",
"size": "2233",
"license": "mit",
"hash": 484149995774980300,
"line_mean": 35.0161290323,
"line_max": 75,
"alpha_frac": 0.6103896104,
"autogenerated": false,
"ratio": 4.127541589648798,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5737931200048798,
"avg_score": null,
"num_lines": null
} |
"""Admin settings"""
from social_auth.utils import setting
if setting('SOCIAL_AUTH_MODELS') in (None, 'social_auth.db.django_models'):
from django.contrib import admin
from social_auth.models import UserSocialAuth, Nonce, Association
_User = UserSocialAuth.user_model()
if hasattr(_User, 'USERNAME_FIELD'):
username_field = _User.USERNAME_FIELD
elif hasattr(_User, 'username'):
username_field = 'username'
else:
username_field = None
fieldnames = ('first_name', 'last_name', 'email') + (username_field,)
all_names = _User._meta.get_all_field_names()
user_search_fields = ['user__' + name for name in fieldnames
if name in all_names]
class UserSocialAuthOption(admin.ModelAdmin):
"""Social Auth user options"""
list_display = ('id', 'user', 'provider', 'uid')
search_fields = user_search_fields
list_filter = ('provider',)
raw_id_fields = ('user',)
list_select_related = True
class NonceOption(admin.ModelAdmin):
"""Nonce options"""
list_display = ('id', 'server_url', 'timestamp', 'salt')
search_fields = ('server_url',)
class AssociationOption(admin.ModelAdmin):
"""Association options"""
list_display = ('id', 'server_url', 'assoc_type')
list_filter = ('assoc_type',)
search_fields = ('server_url',)
admin.site.register(UserSocialAuth, UserSocialAuthOption)
admin.site.register(Nonce, NonceOption)
admin.site.register(Association, AssociationOption)
| {
"repo_name": "jdavidagudelo/django-social-auth-corrected",
"path": "social_auth/admin.py",
"copies": "2",
"size": "1581",
"license": "bsd-3-clause",
"hash": 8623839891200768000,
"line_mean": 34.9318181818,
"line_max": 75,
"alpha_frac": 0.6280834915,
"autogenerated": false,
"ratio": 3.9133663366336635,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00042087542087542086,
"num_lines": 44
} |
"""Admins for the aps_purchasing app."""
from django.contrib import admin
from . import models
class AMLAdmin(admin.ModelAdmin):
list_display = ('ipn', 'manufacturer')
search_fields = ('ipn__code', 'manufacturer__code', 'manufacturer__name')
class CurrencyAdmin(admin.ModelAdmin):
list_display = ('iso_code', 'name', 'sign')
search_fields = ('iso_code', 'name', 'sign')
list_editable = ('name', 'sign')
class DistributorAdmin(admin.ModelAdmin):
list_display = (
'name', 'questionnaire_form', 'supplier_form', 'min_order_value',
'currency', 'payment_terms', 'is_approved', 'is_active',
)
search_fields = (
'name', 'questionnaire_form', 'supplier_form', 'min_order_value',
'currency__iso_code', 'payment_terms__code', 'is_approved',
'is_active',
)
list_editable = ('is_approved', 'is_active')
class DPNAdmin(admin.ModelAdmin):
list_display = ('code', 'name', 'ipn', 'distributor', 'mpn')
search_fields = (
'code', 'name', 'ipn__code', 'distributor__name', 'mpn__code',
'mpn__name'
)
class ManufacturerAdmin(admin.ModelAdmin):
list_display = ('code', 'name')
search_fields = ('code', 'name')
list_editable = ('name', )
class MPNAdmin(admin.ModelAdmin):
list_display = (
'code', 'name', 'manufacturer', 'pku',
'unit')
search_fields = (
'code', 'name', 'manufacturer__code', 'manufacturer__name', 'pku',
)
list_filter = ('manufacturer__name', 'unit')
class PackagingUnitAdmin(admin.ModelAdmin):
list_display = ('name', )
search_fields = ('name', )
class PaymentTermAdmin(admin.ModelAdmin):
list_display = ('code', 'description')
search_fields = ('code', 'description')
class PriceAdmin(admin.ModelAdmin):
list_display = ('quotation_item', 'moq', 'price', 'currency')
search_fields = ('moq', 'price', 'currency__iso_code')
list_filter = ('currency__iso_code', )
class QuotationItemInline(admin.TabularInline):
model = models.QuotationItem
class QuotationAdmin(admin.ModelAdmin):
list_display = (
'distributor', 'ref_number', 'issuance_date', 'expiry_date',
'is_completed'
)
inlines = [QuotationItemInline]
class QuotationItemAdmin(admin.ModelAdmin):
list_display = ('quotation', 'manufacturer', 'ipns', 'mpn',
'min_lead_time', 'max_lead_time')
search_fields = (
'quotation__ref_number', 'mpn__code', 'mpn__name' 'min_lead_time',
'max_lead_time', 'manufacturer__name'
)
def ipns(self, obj):
return ', '.join([
aml.ipn.code for aml in obj.mpn.manufacturer.aml_set.all()])
admin.site.register(models.AML, AMLAdmin)
admin.site.register(models.Currency, CurrencyAdmin)
admin.site.register(models.Distributor, DistributorAdmin)
admin.site.register(models.DPN, DPNAdmin)
admin.site.register(models.Manufacturer, ManufacturerAdmin)
admin.site.register(models.MPN, MPNAdmin)
admin.site.register(models.PackagingUnit, PackagingUnitAdmin)
admin.site.register(models.PaymentTerm, PaymentTermAdmin)
admin.site.register(models.Price, PriceAdmin)
admin.site.register(models.Quotation, QuotationAdmin)
admin.site.register(models.QuotationItem, QuotationItemAdmin)
| {
"repo_name": "bitmazk/django-aps-purchasing",
"path": "aps_purchasing/admin.py",
"copies": "1",
"size": "3264",
"license": "mit",
"hash": -676135390778606200,
"line_mean": 29.2222222222,
"line_max": 77,
"alpha_frac": 0.6531862745,
"autogenerated": false,
"ratio": 3.334014300306435,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4487200574806435,
"avg_score": null,
"num_lines": null
} |
"""Admins for the models of the ``paypal_express_checkout`` app."""
import django
from django.contrib import admin
from . import models
try:
user_model = django.contrib.auth.get_user_model()
except AttributeError:
user_model = django.contrib.auth.models.User
username_field = getattr(user_model, 'USERNAME_FIELD', 'username')
class ItemAdmin(admin.ModelAdmin):
"""Custom admin for the ``Item`` model."""
list_display = ['name', 'description_short', 'value']
search_fields = ['name', 'description']
def description_short(self, obj):
return '{0}...'.format(obj.description[:50])
class PaymentTransactionAdmin(admin.ModelAdmin):
"""Custom admin for the ``PaymentTransaction`` model."""
list_display = [
'creation_date', 'date', 'user', 'user_email', 'transaction_id',
'value', 'status',
]
search_fields = [
'transaction_id', 'status', 'user__email', 'user__' + username_field]
date_hierarchy = 'creation_date'
list_filter = ['status']
raw_id_fields = ['user', ]
def user_email(self, obj):
return obj.user.email
class PaymentTransactionErrorAdmin(admin.ModelAdmin):
"""Custom admin for the ``PaymentTransactionError`` model."""
list_display = [
# FIXME 'transaction_id'
'date', 'user', 'user_email', 'response_short',
]
def user_email(self, obj):
return obj.user.email
def response_short(self, obj):
return '{0}...'.format(obj.response[:50])
def transaction_id(self, obj):
return obj.transaction_id
class PurchasedItemAdmin(admin.ModelAdmin):
"""Custom admin for the ``PurchasedItem`` model."""
list_display = [
'identifier', 'date', 'user', 'user_email', 'transaction', 'item',
'price', 'quantity', 'subtotal', 'total', 'status',
]
list_filter = [
'identifier', 'transaction__status', 'item', ]
search_fields = [
'transaction__transaction_id', 'user__email', ]
raw_id_fields = ['user', 'transaction', ]
def date(self, obj):
return obj.transaction.date
def status(self, obj):
return obj.transaction.status
def subtotal(self, obj):
price = 0
if obj.item is not None:
price = obj.item.value
if obj.price:
price = obj.price
return price * obj.quantity
def total(self, obj):
return obj.transaction.value
def user_email(self, obj):
return obj.user.email
admin.site.register(models.Item, ItemAdmin)
admin.site.register(models.PaymentTransaction, PaymentTransactionAdmin)
admin.site.register(
models.PaymentTransactionError, PaymentTransactionErrorAdmin)
admin.site.register(models.PurchasedItem, PurchasedItemAdmin)
| {
"repo_name": "bitmazk/django-paypal-express-checkout",
"path": "paypal_express_checkout/admin.py",
"copies": "1",
"size": "2758",
"license": "mit",
"hash": 2885437441450097700,
"line_mean": 28.0315789474,
"line_max": 77,
"alpha_frac": 0.6388687455,
"autogenerated": false,
"ratio": 3.814661134163209,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4953529879663209,
"avg_score": null,
"num_lines": null
} |
"""Admin site configuration for the jobs app."""
import logging
from django.contrib import admin
from .models import Post, Job, TagVariant, UserJob
logger = logging.getLogger(__name__)
def remove_tags(modeladmin, request, queryset):
"""Remove tags."""
logger.debug('MA: %s, request: %s', modeladmin, request)
for obj in queryset:
obj.tags.clear()
def set_is_removed(modeladmin, request, queryset):
"""Soft Delete objects."""
logger.debug('MA: %s, request: %s', modeladmin, request)
queryset.update(is_removed=True)
def set_as_garbage(modeladmin, request, queryset):
"""Set posts as garbage."""
logger.debug('MA: %s, request: %s', modeladmin, request)
queryset.update(garbage=True)
def set_as_freelance(modeladmin, request, queryset):
"""Set posts as freelance."""
logger.debug('MA: %s, request: %s', modeladmin, request)
queryset.update(is_freelance=True)
remove_tags.short_description = "Remove Tags"
set_is_removed.short_description = "Soft Delete"
set_as_garbage.short_description = 'Mark Garbage'
set_as_freelance.short_description = 'Mark Freelance'
class JobAdmin(admin.ModelAdmin):
"""The Job model admin has some special tag handling."""
model = Job
actions = [remove_tags]
# List fields
list_display = ('title', 'tag_list', 'created', 'modified')
search_fields = ('title',)
# Detail screen fields
fields = ('title', 'description', 'tags', 'created', 'modified', 'fingerprint')
readonly_fields = ('created', 'modified', 'fingerprint')
def get_queryset(self, request):
"""Prefetch the tags data to make this more efficient."""
return super(JobAdmin, self).get_queryset(request).prefetch_related('tags')
def tag_list(self, obj):
"""Concatenate all tags for each job."""
logger.debug('Called Tag_list in admin: %s', self)
return u", ".join(o.name for o in obj.tags.all())
class UserJobAdmin(admin.ModelAdmin):
"""The UserJob model admin."""
model = UserJob
actions = [set_is_removed]
# List fields
list_display = ('job', 'user', 'is_removed', 'created', 'modified')
search_fields = ('job__title', 'user__username')
list_filter = ('user__username', 'is_removed')
# Detail screen fields
fields = ('job', 'user', 'is_removed', 'created', 'modified')
readonly_fields = ('created', 'modified')
def get_queryset(self, request):
"""Don't use the default manager."""
querys = self.model.all_objects.get_queryset()
ordering = self.get_ordering(request)
if ordering:
querys = querys.order_by(*ordering)
return querys
class PostAdmin(admin.ModelAdmin):
"""The Post model needs no special admin configuration."""
model = Post
actions = [remove_tags, set_as_garbage, set_as_freelance]
# List fields
list_display = ('title', 'source', 'subarea', 'tag_list', 'is_freelance', 'processed', 'garbage', 'created')
search_fields = ('title',)
list_filter = ('source__name', 'garbage', 'is_freelance')
# Detail screen fields
fields = ('title', 'url', 'source', 'subarea', 'description', 'unique', 'tags', 'is_freelance', 'processed', 'garbage', 'created', 'modified')
readonly_fields = ('created', 'modified')
def get_queryset(self, request):
"""Prefetch the tags data to make this more efficient."""
querys = self.model.all_objects.get_queryset()
ordering = self.get_ordering(request)
if ordering:
querys = querys.order_by(*ordering)
return querys.prefetch_related('tags')
def tag_list(self, obj): # pylint: disable=no-self-use
"""Concatenate all tags for each post."""
return u", ".join(o.name for o in obj.tags.all())
class TagVariantAdmin(admin.ModelAdmin):
"""The TagVariant admin lets the user put in new tags."""
model = TagVariant
list_display = ('variant', 'tag')
search_fields = ('variant', 'tag')
fields = ('variant', 'tag')
admin.site.register(Job, JobAdmin)
admin.site.register(Post, PostAdmin)
admin.site.register(TagVariant, TagVariantAdmin)
admin.site.register(UserJob, UserJobAdmin)
| {
"repo_name": "ScorpionResponse/freelancefinder",
"path": "freelancefinder/jobs/admin.py",
"copies": "1",
"size": "4194",
"license": "bsd-3-clause",
"hash": -7990392476977715000,
"line_mean": 31.2615384615,
"line_max": 146,
"alpha_frac": 0.6497377206,
"autogenerated": false,
"ratio": 3.6692913385826773,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48190290591826773,
"avg_score": null,
"num_lines": null
} |
"""Admin site configuration for the notifications app."""
import logging
from django.contrib import admin
from django.contrib import messages
from .models import Message, Notification, NotificationHistory
logger = logging.getLogger(__name__)
def send_to_all_users(modeladmin, request, queryset):
"""Send this message to all users."""
logger.debug('MA: %s, request: %s', modeladmin, request)
logger.info("Scheduling notification for all users: %s", queryset)
if len(queryset) > 1:
messages.warning(request, 'Not scheduling multiple notifications')
return
notification = queryset.get()
notification.schedule_for_all_users()
messages.success(request, "Notification {} scheduled for all users.".format(notification))
def resend_notifications(modeladmin, request, queryset):
"""Resend already sent notifications."""
logger.debug('MA: %s, request: %s', modeladmin, request)
resent_count = 0
for obj in queryset:
if obj.sent:
obj.sent = False
obj.save()
resent_count += 1
messages.success(request, "Resending {} notifications".format(resent_count))
send_to_all_users.short_description = "Send this notification to all users"
resend_notifications.short_description = "Resend notifications"
class MessageAdmin(admin.ModelAdmin):
"""Admin for the Message model."""
model = Message
# List fields
list_display = ('url', 'subject')
search_display = ('url', 'subject')
# Detail screen
fields = ('url', 'subject', 'email_body', 'slack_body')
class NotificationAdmin(admin.ModelAdmin):
"""Admin for the Notification model."""
model = Notification
actions = [send_to_all_users]
# List fields
list_display = ('notification_type', 'message', 'user')
search_display = ('message', 'user')
list_filter = ('notification_type',)
# Detail screen
fields = ('notification_type', 'message', 'user')
class NotificationHistoryAdmin(admin.ModelAdmin):
"""Admin for the NotificationHistory model."""
model = NotificationHistory
actions = [resend_notifications]
# List fields
list_display = ('user', 'notification', 'sent', 'sent_at', 'created', 'modified')
search_fields = ('user', 'notification')
list_filter = ('sent', 'user', 'notification')
# Detail screen
fields = ('user', 'notification', 'sent', 'sent_at', 'created', 'modified')
readonly_fields = ('sent_at', 'created', 'modified')
admin.site.register(Message, MessageAdmin)
admin.site.register(Notification, NotificationAdmin)
admin.site.register(NotificationHistory, NotificationHistoryAdmin)
| {
"repo_name": "ScorpionResponse/freelancefinder",
"path": "freelancefinder/notifications/admin.py",
"copies": "1",
"size": "2659",
"license": "bsd-3-clause",
"hash": -5769006677708660000,
"line_mean": 29.9186046512,
"line_max": 94,
"alpha_frac": 0.6818352764,
"autogenerated": false,
"ratio": 4.11609907120743,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.529793434760743,
"avg_score": null,
"num_lines": null
} |
"""Admin site settings for the animal app."""
from mousedb.animal.models import Strain, Animal, Breeding
from django.contrib import admin
import datetime
class AnimalInline(admin.TabularInline):
"""Provides an inline tabular formset for animal objects.
Currently used with the breeding admin page.
"""
model = Animal
fields = ('Strain', 'Background', 'MouseID','Cage', 'Genotype', 'Gender', 'Born', 'Weaned', 'Generation', 'Markings', 'Notes', 'Rack', 'Rack_Position')
radio_fields = {"Gender": admin.HORIZONTAL, "Strain":admin.HORIZONTAL, "Background": admin.HORIZONTAL, "Genotype": admin.HORIZONTAL}
class AnimalAdmin(admin.ModelAdmin):
"""Provides parameters for animal objects within the admin interface."""
fieldsets = (
(None, {
'fields': ('Strain', 'Background', 'MouseID','Cage', 'Genotype', 'Gender', 'Born', 'Weaned', 'Backcross', 'Generation', 'Markings', 'Notes', 'Breeding', 'Rack', 'Rack_Position')
}),
('Animal Death Information', {
'classes' : ('collapse',),
'fields' : ('Death', 'Cause_of_Death','Alive'),
}),
)
raw_id_fields = ("Breeding",)
list_display = ('MouseID', 'Rack', 'Rack_Position', 'Cage', 'Markings','Gender', 'Genotype', 'Strain', 'Background', 'Generation', 'Backcross', 'Born', 'Alive', 'Death')
list_filter = ('Alive','Strain', 'Background','Gender','Genotype','Backcross')
search_fields = ['MouseID', 'Cage']
radio_fields = {"Gender": admin.HORIZONTAL, "Strain":admin.HORIZONTAL, "Background": admin.HORIZONTAL, "Cause_of_Death": admin.HORIZONTAL}
actions = ['mark_sacrificed', 'mark_estimated_death']
def mark_sacrificed(self,request,queryset):
"""An admin action for marking several animals as sacrificed.
This action sets the selected animals as Alive=False, Death=today and Cause_of_Death as sacrificed. To use other paramters, mice muse be individually marked as sacrificed.
This admin action also shows as the output the number of mice sacrificed."""
rows_updated = queryset.update(Alive=False, Death=datetime.date.today(), Cause_of_Death='Sacrificed')
if rows_updated == 1:
message_bit = "1 animal was"
else:
message_bit = "%s animals were" % rows_updated
self.message_user(request, "%s successfully marked as sacrificed." % message_bit)
mark_sacrificed.short_description = "Mark Animals as Sacrificed"
def mark_estimated_death(self,request,queryset):
"""An admin action for marking several animals as sacrificed.
This action sets the selected animals as Alive=False, Death=today and Cause_of_Death as Estimated. To use other paramters, mice muse be individually marked as sacrificed.
This admin action also shows as the output the number of mice sacrificed."""
rows_updated = queryset.update(Alive=False, Death=datetime.date.today(), Cause_of_Death='Estimated')
if rows_updated == 1:
message_bit = "1 animal was"
else:
message_bit = "%s animals were" % rows_updated
self.message_user(request, "%s successfully marked as dead (estimated date of death)." % message_bit)
mark_estimated_death.short_description = "Mark Animals as Dead (Unknown Date)"
admin.site.register(Animal, AnimalAdmin)
class StrainAdmin(admin.ModelAdmin):
"""Settings in the admin interface for dealing with Strain objects."""
fields = ('Strain', 'Strain_slug', 'Comments', 'Source')
prepopulated_fields = {"Strain_slug": ("Strain",)}
admin.site.register(Strain, StrainAdmin)
class BreedingAdmin(admin.ModelAdmin):
"""Settings in the admin interface for dealing with Breeding objects.
This interface also includes an form for adding objects associated with this breeding cage."""
list_display = ('Cage', 'Start', 'Rack', 'Rack_Position', 'Strain', 'Crosstype', 'BreedingName', 'Notes', 'Active')
list_filter = ('Timed_Mating', 'Strain', 'Active', 'Crosstype')
fields = ('Male', 'Females', 'Timed_Mating', 'backcross', 'background','generation','Cage', 'Rack', 'Rack_Position', 'BreedingName', 'Strain', 'Start', 'End', 'Crosstype', 'Notes', 'Active',)
ordering = ('Active', 'Start')
search_fields = ['Cage',]
raw_id_fields = ("Male", "Females")
radio_fields = {"Crosstype": admin.VERTICAL, "Strain": admin.HORIZONTAL}
actions = ['mark_deactivated']
def mark_deactivated(self,request,queryset):
"""An admin action for marking several cages as inactive.
This action sets the selected cages as Active=False and Death=today.
This admin action also shows as the output the number of mice sacrificed."""
rows_updated = queryset.update(Active=False, End=datetime.date.today() )
if rows_updated == 1:
message_bit = "1 cage was"
else:
message_bit = "%s cages were" % rows_updated
self.message_user(request, "%s successfully marked as deactivated." % message_bit)
mark_deactivated.short_description = "Mark Cages as Inactive"
admin.site.register(Breeding, BreedingAdmin)
| {
"repo_name": "davebridges/mousedb",
"path": "mousedb/animal/admin.py",
"copies": "2",
"size": "5125",
"license": "bsd-3-clause",
"hash": 2675015600600305700,
"line_mean": 55.9444444444,
"line_max": 195,
"alpha_frac": 0.6708292683,
"autogenerated": false,
"ratio": 3.5320468642315643,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5202876132531564,
"avg_score": null,
"num_lines": null
} |
"""Admin sites for the ``django-tinylinks`` app."""
from django.contrib import admin
from django.template.defaultfilters import truncatechars
from django.utils.translation import ugettext_lazy as _
from tinylinks.forms import TinylinkAdminForm
from tinylinks.models import Tinylink, TinylinkLog
class TinylinkAdmin(admin.ModelAdmin):
list_display = (
"short_url",
"url_truncated",
"amount_of_views",
"user",
"last_checked",
"status",
"validation_error",
)
search_fields = ["short_url", "long_url"]
form = TinylinkAdminForm
fieldsets = [
("Tinylink", {"fields": ["user", "long_url", "short_url",]},),
]
def url_truncated(self, obj):
return truncatechars(obj.long_url, 60)
url_truncated.short_description = _("Long URL")
def status(self, obj):
if not obj.is_broken:
return _("OK")
return _("Link broken")
status.short_description = _("Status")
admin.site.register(Tinylink, TinylinkAdmin)
class TinylinkLogAdmin(admin.ModelAdmin):
list_display = ("tinylink", "datetime", "remote_ip", "tracked")
readonly_fields = ("datetime",)
date_hierarchy = "datetime"
admin.site.register(TinylinkLog, TinylinkLogAdmin)
| {
"repo_name": "KuwaitNET/django-shorter",
"path": "tinylinks/admin.py",
"copies": "1",
"size": "1269",
"license": "mit",
"hash": 2233306615319457300,
"line_mean": 25.4375,
"line_max": 70,
"alpha_frac": 0.6477541371,
"autogenerated": false,
"ratio": 3.765578635014837,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4913332772114837,
"avg_score": null,
"num_lines": null
} |
ADMINS = (
('Edwin Steele', 'edwin@wordspeak.org'),
)
MANAGERS = ADMINS
TIME_ZONE = None
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = False
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'visualcommute.urls'
WSGI_APPLICATION = 'visualcommute.wsgi.application'
TEMPLATE_DIRS = (
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
# 'django_nose',
'vcapp',
)
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
},
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
'formatter': 'standard'
},
},
'loggers': {
'django': {
'handlers':['console'],
'propagate': True,
'level':'INFO',
},
'sensorsproject': {
'handlers': ['console'],
'level': 'DEBUG',
},
'sensors': {
'handlers': ['console'],
'level': 'DEBUG',
},
}
}
| {
"repo_name": "edwinsteele/visual-commute",
"path": "visualcommute/settings.py",
"copies": "1",
"size": "2054",
"license": "cc0-1.0",
"hash": 7646256555540051000,
"line_mean": 20.3958333333,
"line_max": 87,
"alpha_frac": 0.5837390458,
"autogenerated": false,
"ratio": 3.5846422338568935,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 0.46683812796568935,
"avg_score": null,
"num_lines": null
} |
ADMINS = ()
MANAGERS = ()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'email_tracker_tests.db',
},
}
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.admin',
'django.contrib.sessions',
'email_tracker',
]
MIDDLEWARE = MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
EMAIL_BACKEND = 'email_tracker.backends.EmailTrackerBackend'
EMAIL_TRACKER_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
SECRET_KEY = 'very secred key ;)'
ROOT_URLCONF = 'email_tracker.tests.urls'
WSGI_APPLICATION = 'email_tracker.tests.wsgi.application'
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.Loader',
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
],
},
}
]
SILENCED_SYSTEM_CHECKS = [
'1_8.W001', # Silance warning for using TEMPLATE_*
'1_10.W001', # Silance warning for using MIDDLEWARE_CLASSES
]
| {
"repo_name": "MagicSolutions/django-email-tracker",
"path": "email_tracker/tests/settings.py",
"copies": "2",
"size": "1302",
"license": "mit",
"hash": -7460270498357701000,
"line_mean": 24.0384615385,
"line_max": 71,
"alpha_frac": 0.6551459293,
"autogenerated": false,
"ratio": 3.4906166219839143,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5145762551283914,
"avg_score": null,
"num_lines": null
} |
ADMINS = ()
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'example.sqlite',
}
}
ALLOWED_HOSTS = []
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = "1234567890evonove"
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'debug': True,
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'oauth2_provider.tests.urls'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.staticfiles',
'django.contrib.admin',
'oauth2_provider',
'oauth2_provider.tests',
)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'oauth2_provider': {
'handlers': ['null'],
'level': 'DEBUG',
'propagate': True,
},
}
}
OAUTH2_PROVIDER = {
'_SCOPES': ['example']
}
| {
"repo_name": "StepicOrg/django-oauth-toolkit",
"path": "oauth2_provider/tests/settings.py",
"copies": "1",
"size": "3140",
"license": "bsd-2-clause",
"hash": -5623549672328518000,
"line_mean": 23.1538461538,
"line_max": 95,
"alpha_frac": 0.552866242,
"autogenerated": false,
"ratio": 3.7876960193003617,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 0.4840562261300362,
"avg_score": null,
"num_lines": null
} |
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DEBUG = False
TEMPLATE_DEBUG = DEBUG
LOGIN_URL = '/accounts/login/' #this presumes that apache is pointing at /mousedb and may need to be changed if a different root is being used
MEDIA_URL = '/mousedb-media/'
STATIC_URL = '/mousedb-static/'
import os.path
PROJECT_DIR = os.path.dirname(__file__)
#these locations can be absolue paths or relative to the installation (as is shown here)
MEDIA_ROOT = os.path.join(PROJECT_DIR, "served-media") #set to where pictures and files will be stored. Default is media folder and this is where MEDIA_URL on your webserver should point
STATIC_ROOT = os.path.join(PROJECT_DIR, "served-static") #this folder is populated by the collectstatic command and is where STATIC_URL on your webserver should point
MEDIA_URL = '/mousedb-media/'
STATIC_URL = '/mousedb-static/'
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Detroit'
DATABASES = {
'default': {
'NAME': '', # Or path to database file if using sqlite3.
'ENGINE': '', # Choose one of 'django.db.backends.postgresql_psycopg2','django.db.backends.postgresql', 'django.db.backends.mysql', 'django.db.backends.sqlite3', 'django.db.backends.oracle'
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3
'HOST':'', # Set to empty string for localhost. Not used with sqlite3.
'PORT':'', # Set to empty string for default. Not used with sqlite3.
}
}
WEAN_AGE = 21 #this is the earliers age at which pups can be weaned from their parents.
GENOTYPE_AGE = 14 #this is the earliest age at which pups can be genotyped or ear tagged.
| {
"repo_name": "BridgesLab/mousedb",
"path": "mousedb/localsettings_empty.py",
"copies": "2",
"size": "1923",
"license": "bsd-3-clause",
"hash": 957346720073162800,
"line_mean": 45.9024390244,
"line_max": 198,
"alpha_frac": 0.7176287051,
"autogenerated": false,
"ratio": 3.4963636363636366,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.012874049988507892,
"num_lines": 41
} |
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = ''
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
| {
"repo_name": "elmiko/kanbango",
"path": "kanbango/local_settings_template.py",
"copies": "1",
"size": "2183",
"license": "mit",
"hash": -1333543916861475600,
"line_mean": 37.9821428571,
"line_max": 127,
"alpha_frac": 0.6688043976,
"autogenerated": false,
"ratio": 3.7508591065292096,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49196635041292097,
"avg_score": null,
"num_lines": null
} |
"""Admin-specific form widgets."""
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.forms.widgets import HiddenInput
from django.template.loader import render_to_string
from django.utils import six
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from reviewboard.avatars import avatar_services
class RelatedUserWidget(HiddenInput):
"""A form widget to allow people to select one or more User relations.
It's not unheard of to have a server with thousands or tens of thousands of
registered users. In this case, the existing Django admin widgets fall down
hard. The filtered select widgets can actually crash the webserver due to
trying to pre-populate an enormous ``<select>`` element, and the raw ID
widget is basically a write-only field.
This field does much better, offering both the ability to see who's already
in the list, as well as interactive search and filtering.
"""
# We inherit from HiddenInput in order for the superclass to render a
# hidden <input> element, but the siteconfig field template special cases
# when ``is_hidden`` is True. Setting it to False still gives us the
# rendering and data handling we want but renders fieldset fields
# correctly.
is_hidden = False
def __init__(self, local_site_name=None, multivalued=True):
"""Initalize the RelatedUserWidget.
Args:
local_site_name (unicode, optional):
The name of the LocalSite where the widget is being rendered.
multivalued (bool, optional):
Whether or not the widget should allow selecting multiple
values.
"""
super(RelatedUserWidget, self).__init__()
self.local_site_name = local_site_name
self.multivalued = multivalued
def render(self, name, value, attrs=None):
"""Render the widget.
Args:
name (unicode):
The name of the field.
value (list or None):
The current value of the field.
attrs (dict):
Attributes for the HTML element.
Returns:
django.utils.safestring.SafeText:
The rendered HTML.
"""
if value:
if not self.multivalued:
value = [value]
value = [v for v in value if v]
input_value = ','.join(force_text(v) for v in value)
existing_users = (
User.objects
.filter(pk__in=value)
.order_by('first_name', 'last_name', 'username')
)
else:
input_value = None
existing_users = []
final_attrs = self.build_attrs(attrs, name=name)
input_html = super(RelatedUserWidget, self).render(
name, input_value, attrs)
use_avatars = avatar_services.avatars_enabled
user_data = []
for user in existing_users:
data = {
'fullname': user.get_full_name(),
'id': user.pk,
'username': user.username,
}
if use_avatars:
data['avatarURL'] = (
avatar_services.for_user(user)
.get_avatar_urls_uncached(user, 40)
)['1x']
user_data.append(data)
extra_html = render_to_string('admin/related_user_widget.html', {
'input_id': final_attrs['id'],
'local_site_name': self.local_site_name,
'multivalued': self.multivalued,
'use_avatars': use_avatars,
'users': user_data,
})
return mark_safe(input_html + extra_html)
def value_from_datadict(self, data, files, name):
"""Unpack the field's value from a datadict.
Args:
data (dict):
The form's data.
files (dict):
The form's files.
name (unicode):
The name of the field.
Returns:
list:
The list of PKs of User objects.
"""
value = data.get(name)
if self.multivalued:
if isinstance(value, list):
return value
elif isinstance(value, six.string_types):
return [v for v in value.split(',') if v]
else:
return None
elif value:
return value
else:
return None
| {
"repo_name": "brennie/reviewboard",
"path": "reviewboard/admin/form_widgets.py",
"copies": "1",
"size": "4554",
"license": "mit",
"hash": -548339915415432800,
"line_mean": 30.4068965517,
"line_max": 79,
"alpha_frac": 0.569828722,
"autogenerated": false,
"ratio": 4.451612903225806,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 145
} |
"""Admin-specific form widgets."""
from __future__ import unicode_literals
import logging
from django.contrib.auth.models import User
from django.utils import six
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from djblets.forms.widgets import (
RelatedObjectWidget as DjbletsRelatedObjectWidget)
from djblets.util.compat.django.template.loader import render_to_string
from reviewboard.avatars import avatar_services
from reviewboard.reviews.models import Group
from reviewboard.scmtools.models import Repository
logger = logging.getLogger(__name__)
class RelatedObjectWidget(DjbletsRelatedObjectWidget):
"""A base class form widget that lets people select one or more objects.
This is a base class. Extended classes must define their own render()
method, to render their own widget with their own data.
This should be used with relatedObjectSelectorView.es6.js, which extends
a Backbone view to display data.
"""
def __init__(self, local_site_name=None, multivalued=True):
super(RelatedObjectWidget, self).__init__(multivalued)
self.local_site_name=local_site_name
class RelatedUserWidget(RelatedObjectWidget):
"""A form widget to allow people to select one or more User relations.
It's not unheard of to have a server with thousands or tens of thousands of
registered users. In this case, the existing Django admin widgets fall down
hard. The filtered select widgets can actually crash the webserver due to
trying to pre-populate an enormous ``<select>`` element, and the raw ID
widget is basically a write-only field.
This field does much better, offering both the ability to see who's already
in the list, as well as interactive search and filtering.
"""
def render(self, name, value, attrs=None):
"""Render the widget.
Args:
name (unicode):
The name of the field.
value (list):
The current value of the field.
attrs (dict, optional):
Attributes for the HTML element.
Returns:
django.utils.safestring.SafeText:
The rendered HTML.
"""
if value:
if not self.multivalued:
value = [value]
value = [v for v in value if v]
input_value = ','.join(force_text(v) for v in value)
existing_users = (
User.objects
.filter(pk__in=value)
.order_by('first_name', 'last_name', 'username')
)
else:
input_value = None
existing_users = []
final_attrs = dict(self.attrs, **attrs)
final_attrs['name'] = name
input_html = super(RelatedUserWidget, self).render(
name, input_value, attrs)
use_avatars = avatar_services.avatars_enabled
user_data = []
for user in existing_users:
data = {
'fullname': user.get_full_name(),
'id': user.pk,
'username': user.username,
}
if use_avatars:
try:
data['avatarHTML'] = (
avatar_services.for_user(user)
.render(request=None,
user=user,
size=20)
)
except Exception as e:
logger.exception(
'Error rendering avatar for RelatedUserWidget: %s',
e)
data['avatarHTML'] = None
user_data.append(data)
return render_to_string(
template_name='admin/related_user_widget.html',
context={
'input_html': mark_safe(input_html),
'input_id': final_attrs['id'],
'local_site_name': self.local_site_name,
'multivalued': self.multivalued,
'use_avatars': use_avatars,
'users': user_data,
})
def value_from_datadict(self, data, files, name):
"""Unpack the field's value from a datadict.
Args:
data (dict):
The form's data.
files (dict):
The form's files.
name (unicode):
The name of the field.
Returns:
list:
The list of PKs of User objects.
"""
value = data.get(name)
if self.multivalued:
if isinstance(value, list):
return value
elif isinstance(value, six.string_types):
return [v for v in value.split(',') if v]
else:
return None
elif value:
return value
else:
return None
class RelatedRepositoryWidget(RelatedObjectWidget):
"""A form widget allowing people to select one or more Repository objects.
This widget offers both the ability to see which repositories are already
in the list, as well as interactive search and filtering.
"""
def render(self, name, value, attrs=None):
"""Render the widget.
Args:
name (unicode):
The name of the field.
value (list):
The current value of the field.
attrs (dict, optional):
Attributes for the HTML element.
Returns:
django.utils.safestring.SafeText:
The rendered HTML.
"""
if value:
if not self.multivalued:
value = [value]
value = [v for v in value if v]
input_value = ','.join(force_text(v) for v in value)
existing_repos = (
Repository.objects
.filter(pk__in=value)
.order_by('name')
)
else:
input_value = None
existing_repos = []
final_attrs = dict(self.attrs, **attrs)
final_attrs['name'] = name
input_html = super(RelatedRepositoryWidget, self).render(
name, input_value, attrs)
repo_data = [
{
'id': repo.pk,
'name': repo.name,
}
for repo in existing_repos
]
return render_to_string(
template_name='admin/related_repo_widget.html',
context={
'input_html': mark_safe(input_html),
'input_id': final_attrs['id'],
'local_site_name': self.local_site_name,
'multivalued': self.multivalued,
'repos': repo_data,
})
def value_from_datadict(self, data, files, name):
"""Unpack the field's value from a datadict.
Args:
data (dict):
The form's data.
files (dict):
The form's files.
name (unicode):
The name of the field.
Returns:
list:
The list of IDs of
:py:class:`~reviewboard.scmtools.models.Repository` objects.
"""
value = data.get(name)
if self.multivalued:
if isinstance(value, list):
return value
elif isinstance(value, six.string_types):
return [v for v in value.split(',') if v]
else:
return None
elif value:
return value
else:
return None
class RelatedGroupWidget(RelatedObjectWidget):
"""A form widget allowing people to select one or more Group objects.
This widget offers both the ability to see which groups are already in the
list, as well as interactive search and filtering.
"""
def __init__(self, invite_only=False, *args, **kwargs):
"""Initialize the RelatedGroupWidget.
Args:
invite_only (bool, optional):
Whether or not to display groups that are invite-only.
*args (tuple):
Positional arguments to pass to the handler.
**kwargs (dict):
Keyword arguments to pass to the handler.
"""
super(RelatedGroupWidget, self).__init__(*args, **kwargs)
self.invite_only = invite_only
def render(self, name, value, attrs=None):
"""Render the widget.
Args:
name (unicode):
The name of the field.
value (list):
The current value of the field.
attrs (dict, optional):
Attributes for the HTML element.
Returns:
django.utils.safestring.SafeText:
The rendered HTML.
"""
if value:
if not self.multivalued:
value = [value]
value = [v for v in value if v]
input_value = ','.join(force_text(v) for v in value)
existing_groups = (
Group.objects
.filter(pk__in=value)
.order_by('name')
)
else:
input_value = None
existing_groups = []
final_attrs = dict(self.attrs, **attrs)
final_attrs['name'] = name
input_html = super(RelatedGroupWidget, self).render(
name, input_value, attrs)
group_data = []
for group in existing_groups:
data = {
'name': group.name,
'display_name': group.display_name,
'id': group.pk,
}
group_data.append(data)
return render_to_string(
template_name='admin/related_group_widget.html',
context={
'input_html': mark_safe(input_html),
'input_id': final_attrs['id'],
'local_site_name': self.local_site_name,
'multivalued': self.multivalued,
'groups': group_data,
'invite_only': self.invite_only,
})
def value_from_datadict(self, data, files, name):
"""Unpack the field's value from a datadict.
Args:
data (dict):
The form's data.
files (dict):
The form's files.
name (unicode):
The name of the field.
Returns:
list:
The list of PKs of Group objects.
"""
value = data.get(name)
if self.multivalued:
if isinstance(value, list):
return value
elif isinstance(value, six.string_types):
return [v for v in value.split(',') if v]
else:
return None
elif value:
return value
else:
return None
| {
"repo_name": "chipx86/reviewboard",
"path": "reviewboard/admin/form_widgets.py",
"copies": "2",
"size": "10875",
"license": "mit",
"hash": -3813980115101280000,
"line_mean": 28.6321525886,
"line_max": 79,
"alpha_frac": 0.5265287356,
"autogenerated": false,
"ratio": 4.627659574468085,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6154188310068085,
"avg_score": null,
"num_lines": null
} |
ADMINS = (
('Your Name', 'email@company.com')
)
MANAGERS = ADMINS
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/media/' #serve the MEDIA_ROOT to this url
LOGIN_URL = '/accounts/login/'
STATIC_URL = '/static/'
#these locations can be absolue paths or relative to the installation (as is shown here)
MEDIA_ROOT = "/var/www/media/files" #set to where pictures and files will be stored. Default is media folder and this is where MEDIA_URL on your webserver should point
STATIC_ROOT = "/var/www/served-static" #this folder is populated by the collectstatic command and is where STATIC_URL on your webserver should point
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'ci%^08ig-0qu*&b(kz_=n6lvbx*puyx6=8!yxzm0+*z)w@7+%6'
DEBUG = False
TEMPLATE_DEBUG = DEBUG
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Detroit'
DATABASES = {
'default': {
'NAME': 'default.db', # Or path to database file if using sqlite3.
'ENGINE': 'django.db.backends.sqlite3', # Choose one of 'django.db.backends.postgresql_psycopg2','django.db.backends.postgresql', 'django.db.backends.mysql', 'django.db.backends.sqlite3', 'django.db.backends.oracle'
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3
'HOST':'', # Set to empty string for localhost. Not used with sqlite3.
'PORT':'', # Set to empty string for default. Not used with sqlite3.
}
}
| {
"repo_name": "davebridges/ExperimentDB",
"path": "experimentdb/localsettings_default.py",
"copies": "1",
"size": "1901",
"license": "bsd-3-clause",
"hash": -4677477814982149000,
"line_mean": 44.3658536585,
"line_max": 224,
"alpha_frac": 0.6970015781,
"autogenerated": false,
"ratio": 3.370567375886525,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4567568953986525,
"avg_score": null,
"num_lines": null
} |
"""Admin tools for assays alongside helper functions
Note that the code for templates can be found here
"""
# import csv
from django.contrib import admin
from django import forms
from django.contrib.auth.models import Group, User
# from assays.forms import (
# AssayStudyConfigurationForm,
# AssayChipReadoutInlineFormset,
# AssayPlateReadoutInlineFormset,
# )
from assays.utils import (
# save_assay_layout,
# modify_qc_status_chip,
# modify_qc_status_plate,
DEFAULT_CSV_HEADER,
# modify_templates
)
# TODO SPAGHETTI CODE
# from django.http import HttpResponseRedirect
from assays.models import (
AssayQualityIndicator,
UnitType,
PhysicalUnits,
AssayStudyModel,
AssayStudyConfiguration,
AssayTarget,
AssaySampleLocation,
AssayMeasurementType,
AssaySupplier,
AssayMethod,
AssayStudyAssay,
AssayStudySupportingData,
AssayStudyStakeholder,
AssayStudy,
AssayMatrixItem,
AssayMatrix,
AssayImage,
AssayImageSetting,
AssaySetting,
AssaySubtarget,
AssayReference,
AssayStudyReference,
AssayStudySet,
AssayCategory,
SpeciesParameters,
AssayPlateReaderMap,
AssayPlateReaderMapItem,
AssayPlateReaderMapDataFile,
AssayPlateReaderMapDataFileBlock,
AssayPlateReaderMapItemValue,
# AssayOmicDataGroup,
AssayOmicDataFileUpload,
AssayOmicDataPoint,
AssayOmicAnalysisTarget,
AssayOmicSampleMetadata,
AssayOmicDataPointCounts,
)
from microdevices.models import MicrophysiologyCenter
# from compounds.models import Compound
from mps.base.admin import LockableAdmin
# from assays.resource import *
# from import_export.admin import ImportExportModelAdmin
# from compounds.models import *
# import unicodedata
# from io import BytesIO
# import ujson as json
# I use regular expressions for a string split at one point
# import re
# from django.db import connection, transaction
# from urllib import unquote
from .forms import AssayStudyFormAdmin #, AssayStudyConfigurationForm
# import os
# import xlsxwriter
# from xlsxwriter.utility import xl_col_to_name
from django.template.loader import render_to_string, TemplateDoesNotExist
from mps.settings import DEFAULT_FROM_EMAIL
from mps.templatetags.custom_filters import (
ADMIN_SUFFIX,
VIEWER_SUFFIX,
)
from datetime import datetime, timedelta
import pytz
from import_export.admin import ImportExportModelAdmin
from django.utils.safestring import mark_safe
from mps.settings import TIME_ZONE
# DEPRECATED
class AssayQualityIndicatorFormAdmin(forms.ModelForm):
"""Admin Form for Quality Indicators"""
class Meta(object):
model = AssayQualityIndicator
widgets = {
'description': forms.Textarea(attrs={'rows': 10}),
}
exclude = ('',)
class UnitTypeFormAdmin(forms.ModelForm):
"""Admin Form for Unit Types"""
class Meta(object):
model = UnitType
widgets = {
'description': forms.Textarea(attrs={'rows': 10}),
}
exclude = ('',)
class UnitTypeAdmin(LockableAdmin):
"""Admin for Unit Types"""
form = UnitTypeFormAdmin
save_on_top = True
list_per_page = 300
list_display = ('unit_type', 'description')
search_fields = ('unit_type', 'description')
fieldsets = (
(
None, {
'fields': (
('unit_type', 'description'),
)
}
),
('Change Tracking', {
'fields': (
# 'locked',
('created_by', 'created_on'),
('modified_by', 'modified_on'),
('signed_off_by', 'signed_off_date'),
)
}
),
)
admin.site.register(UnitType, UnitTypeAdmin)
class PhysicalUnitsFormAdmin(forms.ModelForm):
"""Admin Form for Physical Units"""
class Meta(object):
model = PhysicalUnits
widgets = {
'description': forms.Textarea(attrs={'rows': 10}),
}
exclude = ('',)
class PhysicalUnitsAdmin(LockableAdmin):
"""Admin for Units
Note that all assay units should link to Physical Units
"""
form = PhysicalUnitsFormAdmin
save_on_top = True
list_per_page = 300
list_display = ('unit_type', 'unit', 'base_unit', 'scale_factor', 'availability', 'description')
search_fields = ('unit_type__unit_type', 'unit', 'availability', 'description')
fieldsets = (
(
None, {
'fields': (
'unit',
'unit_type',
('base_unit', 'scale_factor'),
'availability',
'description',
)
}
),
('Change Tracking', {
'fields': (
# 'locked',
('created_by', 'created_on'),
('modified_by', 'modified_on'),
('signed_off_by', 'signed_off_date'),
)
}
),
)
def save_model(self, request, obj, form, change):
# Strip the name
form.instance.unit = form.instance.unit.strip()
obj.unit = obj.unit.strip()
if change:
obj.modified_by = request.user
else:
obj.modified_by = obj.created_by = request.user
obj.save()
admin.site.register(PhysicalUnits, PhysicalUnitsAdmin)
class AssayStudyModelInline(admin.TabularInline):
"""Inline for Study Configurations"""
model = AssayStudyModel
verbose_name = 'Study Model'
fields = (
(
'label', 'organ', 'sequence_number', 'output', 'integration_mode',
),
)
extra = 1
class Media(object):
css = {'all': ('css/hide_admin_original.css',)}
class AssayStudyConfigurationAdmin(LockableAdmin):
"""Admin for study configurations"""
class Media(object):
js = ('js/inline_fix.js',)
# form = AssayStudyConfigurationForm
save_on_top = True
list_per_page = 300
list_display = ('name',)
fieldsets = (
(
'Study Configuration', {
'fields': (
'name',
'media_composition',
'hardware_description',
)
}
),
(
'Change Tracking', {
'fields': (
# 'locked',
('created_by', 'created_on'),
('modified_by', 'modified_on'),
('signed_off_by', 'signed_off_date'),
)
}
),
)
inlines = [AssayStudyModelInline]
admin.site.register(AssayStudyConfiguration, AssayStudyConfigurationAdmin)
class AssayTargetFormAdmin(forms.ModelForm):
"""Admin Form for Targets"""
class Meta(object):
model = AssayTarget
widgets = {
'description': forms.Textarea(attrs={'rows': 10}),
'name': forms.Textarea(attrs={'rows': 2}),
'alt_name': forms.Textarea(attrs={'rows': 2}),
}
exclude = ('',)
# TODO MAKE A VARIABLE TO CONTAIN TRACKING DATA TO AVOID COPY/PASTE
class AssayTargetAdmin(LockableAdmin):
# model = AssayTarget
form = AssayTargetFormAdmin
save_on_top = True
list_per_page = 300
list_display = (
'name',
'short_name',
'alt_name',
'description'
)
search_fields = (
'name',
'short_name',
'description'
)
filter_horizontal = ('methods',)
fieldsets = (
(
'Target', {
'fields': (
'name',
'alt_name',
'short_name',
'description',
'methods'
)
}
),
(
'Change Tracking', {
'fields': (
# 'locked',
('created_by', 'created_on'),
('modified_by', 'modified_on'),
('signed_off_by', 'signed_off_date'),
)
}
),
)
def save_model(self, request, obj, form, change):
# Strip the name and short name
form.instance.name = form.instance.name.strip()
form.instance.short_name = form.instance.short_name.strip()
obj.name = obj.name.strip()
obj.short_name = obj.short_name.strip()
if change:
obj.modified_by = request.user
else:
obj.modified_by = obj.created_by = request.user
obj.save()
admin.site.register(AssayTarget, AssayTargetAdmin)
class AssaySampleLocationFormAdmin(forms.ModelForm):
"""Admin Form for Sample Locations"""
class Meta(object):
model = AssaySampleLocation
widgets = {
'description': forms.Textarea(attrs={'rows': 10}),
}
exclude = ('',)
class AssaySampleLocationAdmin(LockableAdmin):
# model = AssaySampleLocation
form = AssaySampleLocationFormAdmin
save_on_top = True
list_per_page = 300
list_display = ('name', 'description')
search_fields = ('name', 'description')
fieldsets = (
(
'Sample Location', {
'fields': (
'name',
'description',
)
}
),
(
'Change Tracking', {
'fields': (
# 'locked',
('created_by', 'created_on'),
('modified_by', 'modified_on'),
('signed_off_by', 'signed_off_date'),
)
}
),
)
def save_model(self, request, obj, form, change):
# Strip the name
form.instance.name = form.instance.name.strip()
obj.name = obj.name.strip()
if change:
obj.modified_by = request.user
else:
obj.modified_by = obj.created_by = request.user
obj.save()
admin.site.register(AssaySampleLocation, AssaySampleLocationAdmin)
class AssayMeasurementTypeFormAdmin(forms.ModelForm):
"""Admin Form for Measurement Types"""
class Meta(object):
model = AssayMeasurementType
widgets = {
'description': forms.Textarea(attrs={'rows': 10}),
}
exclude = ('',)
class AssayMeasurementTypeAdmin(LockableAdmin):
# model = AssayMeasurementType
form = AssayMeasurementTypeFormAdmin
save_on_top = True
list_per_page = 300
list_display = ('name', 'description')
search_fields = (
'name',
'description'
)
fieldsets = (
(
'Measurement Type', {
'fields': (
'name',
'description',
)
}
),
(
'Change Tracking', {
'fields': (
# 'locked',
('created_by', 'created_on'),
('modified_by', 'modified_on'),
('signed_off_by', 'signed_off_date'),
)
}
),
)
admin.site.register(AssayMeasurementType, AssayMeasurementTypeAdmin)
class AssaySupplierFormAdmin(forms.ModelForm):
"""Admin Form for Suppliers"""
class Meta(object):
model = AssaySupplier
widgets = {
'description': forms.Textarea(attrs={'rows': 10}),
}
exclude = ('',)
class AssaySupplierAdmin(LockableAdmin):
# model = AssaySupplier
form = AssaySupplierFormAdmin
save_on_top = True
list_per_page = 300
list_display = ('name', 'description')
search_fields = (
'name',
'description'
)
fieldsets = (
(
'Measurement Type', {
'fields': (
'name',
'description',
)
}
),
(
'Change Tracking', {
'fields': (
# 'locked',
('created_by', 'created_on'),
('modified_by', 'modified_on'),
('signed_off_by', 'signed_off_date'),
)
}
),
)
admin.site.register(AssaySupplier, AssaySupplierAdmin)
class AssayMethodFormAdmin(forms.ModelForm):
"""Admin Form for Methods"""
class Meta(object):
model = AssayMethod
widgets = {
'description': forms.Textarea(attrs={'rows': 10}),
'name': forms.Textarea(attrs={'rows': 2}),
'alt_name': forms.Textarea(attrs={'rows': 2}),
}
exclude = ('',)
class AssayMethodAdmin(LockableAdmin):
# model = AssayMethod
form = AssayMethodFormAdmin
save_on_top = True
list_per_page = 300
list_display = (
'name',
'alt_name',
'measurement_type',
'supplier',
'protocol_file',
'description'
)
search_fields = (
'name',
'description'
)
fieldsets = (
(
'Measurement Type', {
'fields': (
'name',
'alt_name',
'description',
'measurement_type',
'supplier',
'protocol_file'
)
}
),
(
'Change Tracking', {
'fields': (
# 'locked',
('created_by', 'created_on'),
('modified_by', 'modified_on'),
('signed_off_by', 'signed_off_date'),
)
}
),
)
def save_model(self, request, obj, form, change):
# Strip the name
form.instance.name = form.instance.name.strip()
obj.name = obj.name.strip()
if change:
obj.modified_by = request.user
else:
obj.modified_by = obj.created_by = request.user
obj.save()
admin.site.register(AssayMethod, AssayMethodAdmin)
# admin.site.register(AssayStudyType)
class AssayStudyAssayInline(admin.TabularInline):
model = AssayStudyAssay
exclude = []
# TODO REVIEW
# TODO NOT DRY
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'target':
target_queryset = AssayTarget.objects.all().order_by('name')
kwargs["queryset"] = target_queryset
elif db_field.name == 'method':
method_queryset = AssayMethod.objects.all().order_by('name')
kwargs["queryset"] = method_queryset
elif db_field.name == 'unit':
unit_queryset = PhysicalUnits.objects.all().order_by('unit_type__unit_type', 'base_unit__unit', 'scale_factor')
kwargs["queryset"] = unit_queryset
return super(AssayStudyAssayInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
class AssayStudySupportingDataInline(admin.TabularInline):
"""Inline for Studies"""
model = AssayStudySupportingData
verbose_name = 'Study Supporting Data'
fields = (
(
'description', 'supporting_data'
),
)
extra = 1
# class AssayOmicDataGroupInline(admin.TabularInline):
# """Inline for Studies"""
# model = AssayOmicDataGroup
# verbose_name = 'Assay Omic Data Group - Temporary Group Options'
# fields = (
# (
# 'name', 'number'
# ),
# )
# extra = 1
# TODO REMAKE FOR ASSAY STUDY
class AssayStudyStakeholderInline(admin.TabularInline):
"""Inline for Studies"""
model = AssayStudyStakeholder
verbose_name = 'Study Stakeholders (Level 1)'
extra = 1
# TODO REVIEW
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "group":
groups_with_center = MicrophysiologyCenter.objects.all().values_list('groups', flat=True)
groups_with_center_full = Group.objects.filter(
id__in=groups_with_center
).order_by(
'name'
)
kwargs["queryset"] = groups_with_center_full
return super(AssayStudyStakeholderInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
class AssayStudyReferenceInline(admin.TabularInline):
"""Inline for Studies"""
model = AssayStudyReference
exclude = []
extra = 1
# TODO REMAKE FOR ASSAY STUDY
class AssayStudyAdmin(LockableAdmin):
"""Admin for Studies"""
# class Media(object):
# js = ('assays/assaystudy_add.js',)
form = AssayStudyFormAdmin
save_on_top = True
list_per_page = 300
search_fields = ('name', 'group__name', 'start_date', 'description')
date_hierarchy = 'start_date'
list_display = (
'name',
'id',
'group',
'get_study_types_string',
'start_date',
'signed_off_by',
'signed_off_date',
'release_date',
'stakeholder_display',
'access_group_display',
'collaborator_group_display',
'restricted',
'locked',
# 'description',
)
filter_horizontal = ('access_groups', 'collaborator_groups')
fieldsets = (
(
'Study', {
'fields': (
('toxicity', 'efficacy', 'disease', 'cell_characterization', 'omics'),
'study_configuration',
'start_date',
'name',
'description',
'use_in_calculations',
'image',
)
}
),
(
'PBPK', {
'fields': (
'pbpk_steady_state',
'pbpk_bolus',
'number_of_relevant_cells',
'total_device_volume',
'flow_rate',
)
}
),
(
'Protocol File Upload', {
'fields': (
'protocol',
)
}
),
(
'Change Tracking', {
'fields': (
# 'locked',
('created_by', 'created_on'),
('modified_by', 'modified_on'),
('signed_off_by', 'signed_off_date'),
('signed_off_notes',),
('flagged', 'reason_for_flag')
)
}
),
(
'Study Data Group and Access Group Info', {
'fields': (
'group', 'release_date', 'restricted', 'locked', 'access_groups', 'collaborator_groups'
),
},
),
)
# inlines = [AssayStudyStakeholderInline, AssayStudyAssayInline, AssayStudySupportingDataInline, AssayStudyReferenceInline, AssayOmicDataGroupInline]
inlines = [AssayStudyStakeholderInline, AssayStudyAssayInline, AssayStudySupportingDataInline, AssayStudyReferenceInline]
def get_queryset(self, request):
qs = super(AssayStudyAdmin, self).get_queryset(request)
qs = qs.prefetch_related(
'access_groups',
'collaborator_groups',
# Needs to be revised to actually improve time
'assaystudystakeholder_set__group',
# 'assaystudystakeholder_set__signed_off_by',
'signed_off_by',
)
return qs
# Not a, uh, great query. Way too large.
@mark_safe
def stakeholder_display(self, obj):
contents = ''
trigger = ''
queryset = obj.assaystudystakeholder_set.all()
count = queryset.count()
released = True
if count:
stakes = []
for stakeholder in queryset.order_by('group__name'):
if not stakeholder.signed_off_by_id:
released = False
current_approval_status = False
else:
current_approval_status = True
stakes.append('{0} Approved?: {1}'.format(stakeholder.group.name, current_approval_status))
contents = '<br>'.join(stakes)
if released:
released = 'Approved!'
else:
released = ''
trigger = '<a href="javascript:void(0)" onclick=$("#stakes_{0}").toggle()>Show/Hide Stakeholders ({1}) {2}</a>'.format(
obj.pk, count, released
)
return '{0}<div hidden id="stakes_{1}">{2}</div>'.format(trigger, obj.pk, contents)
stakeholder_display.allow_tags = True
@mark_safe
def access_group_display(self, obj):
contents = ''
trigger = ''
queryset = obj.access_groups.all()
count = queryset.count()
if count:
contents = '<br>'.join(
[
group.name for group in queryset.order_by('name')
]
)
trigger = '<a href="javascript:void(0)" onclick=$("#access_{0}").toggle()>Show/Hide Access Groups ({1})</a>'.format(
obj.pk, count
)
return '{0}<div hidden id="access_{1}">{2}</div>'.format(trigger, obj.pk, contents)
access_group_display.allow_tags = True
@mark_safe
def collaborator_group_display(self, obj):
contents = ''
trigger = ''
queryset = obj.collaborator_groups.all()
count = queryset.count()
if count:
contents = '<br>'.join(
[
group.name for group in queryset.order_by('name')
]
)
trigger = '<a href="javascript:void(0)" onclick=$("#collaborator_{0}").toggle()>Show/Hide Collaborator Groups ({1})</a>'.format(
obj.pk, count
)
return '{0}<div hidden id="collaborator_{1}">{2}</div>'.format(trigger, obj.pk, contents)
collaborator_group_display.allow_tags = True
# save_related takes the place of save_model so that the inline can be referred to
# TODO TODO TODO THIS IS NOT VERY DRY
# This code may pose a problem if multiple people are editing an entry at once...
def save_related(self, request, form, formsets, change):
# Local datetime
tz = pytz.timezone(TIME_ZONE)
datetime_now_local = datetime.now(tz)
fourteen_days_from_date = datetime_now_local + timedelta(days=14)
send_initial_sign_off_alert = False
# SAVE FORM HERE
# TODO TODO TODO
if change:
initial_study = AssayStudy.objects.get(pk=form.instance.id)
initial_sign_off = initial_study.signed_off_by
initial_restricted = initial_study.restricted
initial_required_stakeholders = AssayStudyStakeholder.objects.filter(
study_id=initial_study.id,
signed_off_by_id=None,
sign_off_required=True
)
initial_required_stakeholder_group_ids = list(initial_required_stakeholders.values_list('group_id', flat=True))
previous_access_groups = {group.name: group.id for group in initial_study.access_groups.all()}
obj = form.save()
obj.modified_by = request.user
obj.save()
if not initial_sign_off and obj.signed_off_by:
send_initial_sign_off_alert = True
else:
initial_study = form.instance
initial_sign_off = initial_study.signed_off_by
initial_restricted = initial_study.restricted
initial_required_stakeholders = AssayStudyStakeholder.objects.none()
initial_required_stakeholder_group_ids = list(initial_required_stakeholders.values_list('group_id', flat=True))
previous_access_groups = {}
obj = form.save()
obj.modified_by = obj.created_by = request.user
obj.save()
if change:
initial_number_of_required_sign_offs = initial_required_stakeholders.count()
else:
initial_number_of_required_sign_offs = 0
viewer_subject = 'Study {0} Now Available for Viewing'.format(initial_study)
# SAVE FORMSETS HERE
# TODO TODO TODO
# Save inline and many to many
super(AssayStudyAdmin, self).save_related(request, form, formsets, change)
# Crude way to make sure M2M is up-to-date
study_after_save = AssayStudy.objects.get(pk=form.instance.id)
new_access_group_names = {
group.name: group.id for group in study_after_save.access_groups.all() if
group.name not in previous_access_groups
}
current_number_of_required_sign_offs = AssayStudyStakeholder.objects.filter(
study_id=obj.id,
signed_off_by_id=None,
sign_off_required=True
).count()
send_stakeholder_sign_off_alert = current_number_of_required_sign_offs < initial_number_of_required_sign_offs
# TODO TODO TODO
# ONLY SEND VIEWER ALERT IF:
# Sign off occurred and no stakeholders
# Sign off occurred and final stakeholder has acknowledged
# send_viewer_alert = current_number_of_required_sign_offs == 0 and obj.signed_off_by
send_viewer_alert = (
send_initial_sign_off_alert and current_number_of_required_sign_offs == 0
) or (
obj.signed_off_by and current_number_of_required_sign_offs == 0 and send_stakeholder_sign_off_alert
)
# TODO TODO TODO TODO
# stakeholder_admin_subject = 'Acknowledgement of Study {0} Requested'.format(obj)
stakeholder_admin_subject = 'Approval for Release Requested: {0}'.format(obj)
stakeholder_viewer_groups = {}
stakeholder_admin_groups = {}
stakeholder_admins_to_be_alerted = []
stakeholder_viewers_to_be_alerted = []
# VULGAR! NOT DRY
# PASTED HERE
if send_initial_sign_off_alert:
# TODO TODO TODO TODO ALERT STAKEHOLDER ADMINS
stakeholder_admin_groups = {
group + ADMIN_SUFFIX: True for group in
AssayStudyStakeholder.objects.filter(
study_id=obj.id, sign_off_required=True
).prefetch_related('group').values_list('group__name', flat=True)
}
stakeholder_admins_to_be_alerted = User.objects.filter(
groups__name__in=stakeholder_admin_groups, is_active=True
).distinct()
for user_to_be_alerted in stakeholder_admins_to_be_alerted:
try:
stakeholder_admin_message = render_to_string(
'assays/email/tctc_stakeholder_email.txt',
{
'user': user_to_be_alerted,
'study': obj,
'fourteen_days_from_date': fourteen_days_from_date
}
)
except TemplateDoesNotExist:
stakeholder_admin_message = render_to_string(
'assays/email/stakeholder_sign_off_request.txt',
{
'user': user_to_be_alerted,
'study': obj
}
)
user_to_be_alerted.email_user(
stakeholder_admin_subject,
stakeholder_admin_message,
DEFAULT_FROM_EMAIL
)
# TODO TODO TODO TODO ALERT STAKEHOLDER VIEWERS
stakeholder_viewer_groups = {
group: True for group in
AssayStudyStakeholder.objects.filter(
study_id=obj.id
).prefetch_related('group').values_list('group__name', flat=True)
}
initial_groups = list(stakeholder_viewer_groups.keys())
for group in initial_groups:
stakeholder_viewer_groups.update({
# group + ADMIN_SUFFIX: True,
group + VIEWER_SUFFIX: True
})
# BE SURE THIS IS MATCHED BELOW
stakeholder_viewers_to_be_alerted = User.objects.filter(
groups__name__in=stakeholder_viewer_groups, is_active=True
).exclude(
id__in=stakeholder_admins_to_be_alerted
).distinct()
for user_to_be_alerted in stakeholder_viewers_to_be_alerted:
# TODO TODO TODO WHAT DO WE CALL THE PROCESS OF SIGN OFF ACKNOWLEDGEMENT?!
viewer_message = render_to_string(
'assays/email/viewer_alert.txt',
{
'user': user_to_be_alerted,
'study': obj
}
)
user_to_be_alerted.email_user(
viewer_subject,
viewer_message,
DEFAULT_FROM_EMAIL
)
if send_viewer_alert:
access_group_names = {group.name: group.id for group in obj.access_groups.all()}
matching_groups = list(set([
group.id for group in Group.objects.all() if
group.name.replace(ADMIN_SUFFIX, '').replace(VIEWER_SUFFIX, '') in access_group_names
]))
# Just in case, exclude stakeholders to prevent double messages
viewers_to_be_alerted = User.objects.filter(
groups__id__in=matching_groups, is_active=True
).exclude(
id__in=stakeholder_admins_to_be_alerted
).exclude(
id__in=stakeholder_viewers_to_be_alerted
).distinct()
# Update viewer groups to include admins
stakeholder_viewer_groups.update(stakeholder_admin_groups)
# if stakeholder_viewer_groups or stakeholder_admin_groups:
# viewers_to_be_alerted.exclude(
# groups__name__in=stakeholder_viewer_groups
# ).exclude(
# group__name__in=stakeholder_admin_groups
# )
for user_to_be_alerted in viewers_to_be_alerted:
viewer_message = render_to_string(
'assays/email/viewer_alert.txt',
{
'user': user_to_be_alerted,
'study': obj
}
)
user_to_be_alerted.email_user(
viewer_subject,
viewer_message,
DEFAULT_FROM_EMAIL
)
# Superusers to contact
superusers_to_be_alerted = User.objects.filter(is_superuser=True, is_active=True)
if send_initial_sign_off_alert:
# Magic strings are in poor taste, should use a template instead
superuser_subject = 'Study Sign Off Detected: {0}'.format(obj)
superuser_message = render_to_string(
'assays/email/superuser_initial_sign_off_alert.txt',
{
'study': obj,
'stakeholders': AssayStudyStakeholder.objects.filter(study_id=obj.id).order_by('-signed_off_date')
}
)
for user_to_be_alerted in superusers_to_be_alerted:
user_to_be_alerted.email_user(superuser_subject, superuser_message, DEFAULT_FROM_EMAIL)
if send_stakeholder_sign_off_alert:
# Magic strings are in poor taste, should use a template instead
# superuser_subject = 'Stakeholder Acknowledgement Detected: {0}'.format(obj)
superuser_subject = 'Stakeholder Approval Detected: {0}'.format(obj)
superuser_message = render_to_string(
'assays/email/superuser_stakeholder_alert.txt',
{
'study': obj,
'stakeholders': AssayStudyStakeholder.objects.filter(study_id=obj.id).order_by('-signed_off_date')
}
)
for user_to_be_alerted in superusers_to_be_alerted:
user_to_be_alerted.email_user(superuser_subject, superuser_message, DEFAULT_FROM_EMAIL)
if send_viewer_alert:
# Magic strings are in poor taste, should use a template instead
superuser_subject = 'Study Released to Next Level: {0}'.format(obj)
superuser_message = render_to_string(
'assays/email/superuser_viewer_release_alert.txt',
{
'study': obj
}
)
for user_to_be_alerted in superusers_to_be_alerted:
user_to_be_alerted.email_user(superuser_subject, superuser_message, DEFAULT_FROM_EMAIL)
# END PASTE
# Special alerts for adding a stakeholder after sign off
# Will send a message to all required admins and viewers
# BE SURE NOT TO SEND TO STAKEHOLDERS THAT HAVE ALREADY SIGNED OFF
if obj.signed_off_by and not send_initial_sign_off_alert and initial_number_of_required_sign_offs < current_number_of_required_sign_offs:
# ...
# UGLY NOT DRY
stakeholder_admin_groups = {
group + ADMIN_SUFFIX: True for group in
AssayStudyStakeholder.objects.filter(
study_id=obj.id, sign_off_required=True, signed_off_by_id=None
).exclude(
# id__in=initial_required_stakeholders
group_id__in=initial_required_stakeholder_group_ids
).prefetch_related('group').values_list('group__name', flat=True)
}
stakeholder_admins_to_be_alerted = User.objects.filter(
groups__name__in=stakeholder_admin_groups, is_active=True
).distinct()
for user_to_be_alerted in stakeholder_admins_to_be_alerted:
try:
stakeholder_admin_message = render_to_string(
'assays/email/tctc_stakeholder_email.txt',
{
'user': user_to_be_alerted,
'study': obj,
'fourteen_days_from_date': fourteen_days_from_date
}
)
except TemplateDoesNotExist:
stakeholder_admin_message = render_to_string(
'assays/email/stakeholder_sign_off_request.txt',
{
'user': user_to_be_alerted,
'study': obj
}
)
user_to_be_alerted.email_user(
stakeholder_admin_subject,
stakeholder_admin_message,
DEFAULT_FROM_EMAIL
)
# TODO TODO TODO TODO ALERT STAKEHOLDER VIEWERS
stakeholder_viewer_groups = {
group: True for group in
AssayStudyStakeholder.objects.filter(
study_id=obj.id, signed_off_by_id=None
).exclude(
# id__in=initial_required_stakeholders
group_id__in=initial_required_stakeholder_group_ids
).prefetch_related('group').values_list('group__name', flat=True)
}
initial_groups = list(stakeholder_viewer_groups.keys())
for group in initial_groups:
stakeholder_viewer_groups.update({
# group + ADMIN_SUFFIX: True,
group + VIEWER_SUFFIX: True
})
stakeholder_viewers_to_be_alerted = User.objects.filter(
groups__name__in=stakeholder_viewer_groups, is_active=True
).exclude(
id__in=stakeholder_admins_to_be_alerted
).distinct()
for user_to_be_alerted in stakeholder_viewers_to_be_alerted:
# TODO TODO TODO WHAT DO WE CALL THE PROCESS OF SIGN OFF ACKNOWLEDGEMENT?!
viewer_message = render_to_string(
'assays/email/viewer_alert.txt',
{
'user': user_to_be_alerted,
'study': obj
}
)
user_to_be_alerted.email_user(
viewer_subject,
viewer_message,
DEFAULT_FROM_EMAIL
)
# Special alerts for new access groups
if not send_viewer_alert and new_access_group_names and obj.signed_off_by and current_number_of_required_sign_offs == 0:
matching_groups = list(set([
group.id for group in Group.objects.all() if
group.name.replace(ADMIN_SUFFIX, '').replace(VIEWER_SUFFIX, '') in new_access_group_names
]))
exclude_groups = list(set([
group.id for group in Group.objects.all() if
group.name.replace(ADMIN_SUFFIX, '').replace(VIEWER_SUFFIX, '') in previous_access_groups
]))
viewers_to_be_alerted = User.objects.filter(
groups__id__in=matching_groups,
is_active=True
).exclude(
groups__id__in=exclude_groups
).distinct()
for user_to_be_alerted in viewers_to_be_alerted:
viewer_message = render_to_string(
'assays/email/viewer_alert.txt',
{
'user': user_to_be_alerted,
'study': obj
}
)
user_to_be_alerted.email_user(
viewer_subject,
viewer_message,
DEFAULT_FROM_EMAIL
)
# TODO CHANGE SUPERUSER VIEWER RELEASE ALERT
# Magic strings are in poor taste, should use a template instead
superuser_subject = 'Study Released to Next Level: {0}'.format(obj)
superuser_message = render_to_string(
'assays/email/superuser_viewer_release_alert.txt',
{
'study': obj,
'new_access_group_names': new_access_group_names
}
)
for user_to_be_alerted in superusers_to_be_alerted:
user_to_be_alerted.email_user(superuser_subject, superuser_message, DEFAULT_FROM_EMAIL)
# Special case for going public
if initial_restricted and not obj.restricted:
# Magic strings are in poor taste, should use a template instead
superuser_subject = 'Study Released to Next Level: {0}'.format(obj)
superuser_message = render_to_string(
'assays/email/superuser_viewer_release_alert.txt',
{
'study': obj,
'new_access_group_names': []
}
)
for user_to_be_alerted in superusers_to_be_alerted:
user_to_be_alerted.email_user(superuser_subject, superuser_message, DEFAULT_FROM_EMAIL)
# Odd, I know, but prevents double save
def save_model(self, request, obj, form, change):
pass
admin.site.register(AssayStudy, AssayStudyAdmin)
# TODO TODO TODO TODO NEW MODELS HERE
class AssayMatrixItemAdmin(ImportExportModelAdmin):
model = AssayMatrixItem
search_fields = ('name', 'notes')
admin.site.register(AssayMatrixItem, AssayMatrixItemAdmin)
class AssayMatrixAdmin(ImportExportModelAdmin):
model = AssayMatrix
search_fields = ('name', 'notes')
admin.site.register(AssayMatrix, AssayMatrixAdmin)
class AssayImageAdmin(ImportExportModelAdmin):
model = AssayImage
search_fields = ('matrix_item__name', 'file_name')
admin.site.register(AssayImage, AssayImageAdmin)
class AssayImageSettingAdmin(ImportExportModelAdmin):
model = AssayImageSetting
search_fields = ('study__name', 'label_name')
admin.site.register(AssayImageSetting, AssayImageSettingAdmin)
class AssaySettingAdmin(ImportExportModelAdmin):
model = AssaySetting
search_fields = ('name', 'description')
admin.site.register(AssaySetting, AssaySettingAdmin)
class AssaySubtargetAdmin(ImportExportModelAdmin):
model = AssaySubtarget
search_fields = ('name', 'description')
admin.site.register(AssaySubtarget, AssaySubtargetAdmin)
class AssayReferenceAdmin(ImportExportModelAdmin):
model = AssayReference
search_fields = ('pubmed_id', 'title', 'authors')
admin.site.register(AssayReference, AssayReferenceAdmin)
class AssayStudySetAdminForm(forms.ModelForm):
class Meta(object):
model = AssayStudySet
exclude = ('',)
widgets = {
'description': forms.Textarea(attrs={'rows': 10})
}
def __init__(self, *args, **kwargs):
super(AssayStudySetAdminForm, self).__init__(*args, **kwargs)
study_queryset = AssayStudy.objects.all().prefetch_related(
'group__center_groups'
)
assay_queryset = AssayStudyAssay.objects.all().prefetch_related(
'target',
'method',
'unit',
)
self.fields['studies'].queryset = study_queryset
self.fields['assays'].queryset = assay_queryset
class AssayStudySetAdmin(ImportExportModelAdmin):
model = AssayStudySet
form = AssayStudySetAdminForm
search_fields = ('name', 'description')
admin.site.register(AssayStudySet, AssayStudySetAdmin)
class AssayCategoryAdmin(ImportExportModelAdmin):
model = AssayCategory
search_fields = ('name', 'description')
filter_horizontal = ('targets',)
admin.site.register(AssayCategory, AssayCategoryAdmin)
class SpeciesParametersAdmin(ImportExportModelAdmin):
model = SpeciesParameters
search_fields = ('species', 'organ', 'reference')
admin.site.register(SpeciesParameters, SpeciesParametersAdmin)
# do not want to allow editing of the wells in the plate in the admin
# the relationship between the item and item value tables needs to be controlled by the GUI
class AssayPlateReaderMapAdmin(ImportExportModelAdmin):
model = AssayPlateReaderMap
list_display = ('name', 'description', 'device', 'study_assay', 'time_unit', 'volume_unit', 'cell_count')
search_fields = ('name', 'description')
admin.site.register(AssayPlateReaderMap, AssayPlateReaderMapAdmin)
class AssayPlateReaderMapDataFileAdmin(ImportExportModelAdmin):
model = AssayPlateReaderMapDataFile
list_display = ('description', )
search_fields = ('description',)
admin.site.register(AssayPlateReaderMapDataFile, AssayPlateReaderMapDataFileAdmin)
class AssayPlateReaderMapDataFileBlockAdmin(ImportExportModelAdmin):
model = AssayPlateReaderMapDataFileBlock
list_display = ('assayplatereadermap', 'assayplatereadermapdatafile', 'data_block', 'data_processing_parsable')
search_fields = ('data_block',)
admin.site.register(AssayPlateReaderMapDataFileBlock, AssayPlateReaderMapDataFileBlockAdmin)
# class AssayOmicDataGroupAdmin(ImportExportModelAdmin):
# model = AssayOmicDataGroup
# list_display = ('name', 'number', 'study')
# search_fields = ('name', 'study')
#
# admin.site.register(AssayOmicDataGroup, AssayOmicDataGroupAdmin)
class AssayOmicDataFileUploadAdmin(ImportExportModelAdmin):
model = AssayOmicDataFileUpload
list_display = ('description', 'study', 'omic_data_file', 'study_assay', 'analysis_method', 'data_type',
'group_1', 'group_2', 'time_1', 'time_2', 'location_1', 'location_2', 'name_reference')
search_fields = ('description', )
admin.site.register(AssayOmicDataFileUpload, AssayOmicDataFileUploadAdmin)
class AssayOmicDataPointAdmin(ImportExportModelAdmin):
model = AssayOmicDataPoint
list_display = ('study', 'omic_data_file', 'name', 'analysis_target', 'value')
search_fields = ('name', 'analysis_target', 'study', 'omic_data_file')
admin.site.register(AssayOmicDataPoint, AssayOmicDataPointAdmin)
class AssayOmicAnalysisTargetAdmin(ImportExportModelAdmin):
"""Admin for Analysis Targets"""
model = AssayOmicAnalysisTarget
list_display = ('method', 'method_order', 'name', 'vizname', 'target', 'data_type', 'unit')
search_fields = ('method', 'method_order', 'name', 'vizname', 'target', 'data_type', 'unit')
list_editable = ('method_order', 'name', 'target', 'vizname', 'data_type', 'unit')
admin.site.register(AssayOmicAnalysisTarget, AssayOmicAnalysisTargetAdmin)
class AssayOmicSampleMetadataAdmin(ImportExportModelAdmin):
"""Admin for Sample Metadata"""
model = AssayOmicSampleMetadata
list_display = ('study', 'sample_name', 'matrix_item', 'sample_location', 'sample_time')
search_fields = ('study', 'sample_name', 'matrix_item', 'sample_location', 'sample_time')
admin.site.register(AssayOmicSampleMetadata, AssayOmicSampleMetadataAdmin)
class AssayOmicDataPointCountsAdmin(ImportExportModelAdmin):
model = AssayOmicDataPoint
list_display = ('study', 'omic_data_file', 'sample_metadata', 'name', 'analysis_target', 'value')
search_fields = ('name', 'analysis_target', 'study', 'omic_data_file')
admin.site.register(AssayOmicDataPointCounts, AssayOmicDataPointCountsAdmin)
| {
"repo_name": "UPDDI/mps-database-server",
"path": "assays/admin.py",
"copies": "1",
"size": "45378",
"license": "mit",
"hash": -1730603436826269400,
"line_mean": 32.0502549162,
"line_max": 153,
"alpha_frac": 0.5587509366,
"autogenerated": false,
"ratio": 4.034317211948791,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.509306814854879,
"avg_score": null,
"num_lines": null
} |
# admin_tools/views.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from candidate.controllers import candidates_import_from_sample_file
from config.base import get_environment_variable, LOGIN_URL
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.messages import get_messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from election.models import Election
from election.controllers import elections_import_from_sample_file
from import_export_google_civic.models import GoogleCivicApiCounterManager
from import_export_vote_smart.models import VoteSmartApiCounterManager
from office.controllers import offices_import_from_sample_file
from organization.controllers import organizations_import_from_sample_file
from polling_location.controllers import import_and_save_all_polling_locations_data
from position.controllers import positions_import_from_sample_file
from voter.models import Voter, VoterDeviceLinkManager, VoterManager, voter_has_authority, voter_setup
from wevote_functions.functions import convert_to_int, delete_voter_api_device_id_cookie, generate_voter_device_id, \
get_voter_api_device_id, positive_value_exists, set_voter_api_device_id, STATE_CODE_MAP
BALLOT_ITEMS_SYNC_URL = get_environment_variable("BALLOT_ITEMS_SYNC_URL")
BALLOT_RETURNED_SYNC_URL = get_environment_variable("BALLOT_RETURNED_SYNC_URL")
ELECTIONS_SYNC_URL = get_environment_variable("ELECTIONS_SYNC_URL")
ORGANIZATIONS_SYNC_URL = get_environment_variable("ORGANIZATIONS_SYNC_URL")
OFFICES_SYNC_URL = get_environment_variable("OFFICES_SYNC_URL")
CANDIDATES_SYNC_URL = get_environment_variable("CANDIDATES_SYNC_URL")
MEASURES_SYNC_URL = get_environment_variable("MEASURES_SYNC_URL")
POLLING_LOCATIONS_SYNC_URL = get_environment_variable("POLLING_LOCATIONS_SYNC_URL")
POSITIONS_SYNC_URL = get_environment_variable("POSITIONS_SYNC_URL")
VOTER_GUIDES_SYNC_URL = get_environment_variable("VOTER_GUIDES_SYNC_URL")
@login_required
def admin_home_view(request):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
# Create a voter_device_id and voter in the database if one doesn't exist yet
results = voter_setup(request)
voter_api_device_id = results['voter_api_device_id']
store_new_voter_api_device_id_in_cookie = results['store_new_voter_api_device_id_in_cookie']
google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
template_values = {
'google_civic_election_id': google_civic_election_id,
}
response = render(request, 'admin_tools/index.html', template_values)
# We want to store the voter_api_device_id cookie if it is new
if positive_value_exists(voter_api_device_id) and positive_value_exists(store_new_voter_api_device_id_in_cookie):
set_voter_api_device_id(request, response, voter_api_device_id)
return response
@login_required
def import_sample_data_view(request):
authority_required = {'admin'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
# This routine works without requiring a Google Civic API key
# We want to make sure that all voters have been updated to have a we_vote_id
voter_list = Voter.objects.all()
for one_voter in voter_list:
one_voter.save()
polling_locations_results = import_and_save_all_polling_locations_data()
# NOTE: The approach of having each developer pull directly from Google Civic won't work because if we are going
# to import positions, we need to have stable we_vote_ids for all ballot items
# =========================
# # We redirect to the view that calls out to Google Civic and brings in ballot data
# # This isn't ideal (I'd rather call a controller instead of redirecting to a view), but this is a unique case
# # and we have a lot of error-display-to-screen code
# election_local_id = 0
# google_civic_election_id = 4162 # Virginia
# return HttpResponseRedirect(reverse('election:election_all_ballots_retrieve',
# args=(election_local_id,)) +
# "?google_civic_election_id=" + str(google_civic_election_id))
# Import election data from We Vote export file
elections_results = elections_import_from_sample_file()
# Import ContestOffices
load_from_uri = False
offices_results = offices_import_from_sample_file(request, load_from_uri)
# Import candidate data from We Vote export file
load_from_uri = False
candidates_results = candidates_import_from_sample_file(request, load_from_uri)
# Import ContestMeasures
# Import organization data from We Vote export file
load_from_uri = False
organizations_results = organizations_import_from_sample_file(request, load_from_uri)
# Import positions data from We Vote export file
# load_from_uri = False
positions_results = positions_import_from_sample_file(request) # , load_from_uri
messages.add_message(request, messages.INFO,
'The following data has been imported: <br />'
'Polling locations saved: {polling_locations_saved}, updated: {polling_locations_updated},'
' not_processed: {polling_locations_not_processed} <br />'
'Elections saved: {elections_saved}, updated: {elections_updated},'
' not_processed: {elections_not_processed} <br />'
'Offices saved: {offices_saved}, updated: {offices_updated},'
' not_processed: {offices_not_processed} <br />'
'Candidates saved: {candidates_saved}, updated: {candidates_updated},'
' not_processed: {candidates_not_processed} <br />'
'Organizations saved: {organizations_saved}, updated: {organizations_updated},'
' not_processed: {organizations_not_processed} <br />'
'Positions saved: {positions_saved}, updated: {positions_updated},'
' not_processed: {positions_not_processed} <br />'
''.format(
polling_locations_saved=polling_locations_results['saved'],
polling_locations_updated=polling_locations_results['updated'],
polling_locations_not_processed=polling_locations_results['not_processed'],
elections_saved=elections_results['saved'],
elections_updated=elections_results['updated'],
elections_not_processed=elections_results['not_processed'],
offices_saved=offices_results['saved'],
offices_updated=offices_results['updated'],
offices_not_processed=offices_results['not_processed'],
candidates_saved=candidates_results['saved'],
candidates_updated=candidates_results['updated'],
candidates_not_processed=candidates_results['not_processed'],
organizations_saved=organizations_results['saved'],
organizations_updated=organizations_results['updated'],
organizations_not_processed=organizations_results['not_processed'],
positions_saved=positions_results['saved'],
positions_updated=positions_results['updated'],
positions_not_processed=positions_results['not_processed'],
))
return HttpResponseRedirect(reverse('admin_tools:admin_home', args=()))
@login_required
def delete_test_data_view(request):
authority_required = {'admin'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
# We leave in place the polling locations data and the election data from Google civic
# Delete candidate data from exported file
# Delete organization data from exported file
# Delete positions data from exported file
return HttpResponseRedirect(reverse('admin_tools:admin_home', args=()))
def login_user(request):
"""
This method is called when you login from the /login/ form
:param request:
:return:
"""
voter_api_device_id = get_voter_api_device_id(request) # We look in the cookies for voter_api_device_id
store_new_voter_api_device_id_in_cookie = False
voter_signed_in = False
voter_manager = VoterManager()
voter_device_link_manager = VoterDeviceLinkManager()
results = voter_manager.retrieve_voter_from_voter_device_id(voter_api_device_id)
if results['voter_found']:
voter_on_stage = results['voter']
voter_on_stage_id = voter_on_stage.id
# Just because a We Vote voter is found doesn't mean they are authenticated for Django
else:
voter_on_stage_id = 0
info_message = ''
error_message = ''
username = ''
# Does Django think user is already signed in?
if request.user.is_authenticated():
# If so, make sure user and voter_on_stage are the same.
if request.user.id != voter_on_stage_id:
# Delete the prior voter_api_device_id from database
voter_device_link_manager.delete_voter_device_link(voter_api_device_id)
# Create a new voter_api_device_id and voter_device_link
voter_api_device_id = generate_voter_device_id()
results = voter_device_link_manager.save_new_voter_device_link(voter_api_device_id, request.user.id)
store_new_voter_api_device_id_in_cookie = results['voter_device_link_created']
voter_on_stage = request.user
voter_on_stage_id = voter_on_stage.id
elif request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
info_message = "You're successfully logged in!"
# Delete the prior voter_api_device_id from database
voter_device_link_manager.delete_voter_device_link(voter_api_device_id)
# Create a new voter_api_device_id and voter_device_link
voter_api_device_id = generate_voter_device_id()
results = voter_device_link_manager.save_new_voter_device_link(voter_api_device_id, user.id)
store_new_voter_api_device_id_in_cookie = results['voter_device_link_created']
else:
error_message = "Your account is not active, please contact the site admin."
if user.id != voter_on_stage_id:
# Eventually we want to merge voter_on_stage into user account
pass
else:
error_message = "Your username and/or password were incorrect."
elif not positive_value_exists(voter_on_stage_id):
# If here, delete the prior voter_api_device_id from database
voter_device_link_manager.delete_voter_device_link(voter_api_device_id)
# We then need to set a voter_api_device_id cookie and create a new voter (even though not signed in)
results = voter_setup(request)
voter_api_device_id = results['voter_api_device_id']
store_new_voter_api_device_id_in_cookie = results['store_new_voter_api_device_id_in_cookie']
# Does Django think user is signed in?
if request.user.is_authenticated():
voter_signed_in = True
else:
info_message = "Please log in below..."
if positive_value_exists(error_message):
messages.add_message(request, messages.ERROR, error_message)
if positive_value_exists(info_message):
messages.add_message(request, messages.INFO, info_message)
messages_on_stage = get_messages(request)
template_values = {
'request': request,
'username': username,
'next': next,
'voter_signed_in': voter_signed_in,
'messages_on_stage': messages_on_stage,
}
response = render(request, 'registration/login_user.html', template_values)
# We want to store the voter_api_device_id cookie if it is new
if positive_value_exists(voter_api_device_id) and positive_value_exists(store_new_voter_api_device_id_in_cookie):
set_voter_api_device_id(request, response, voter_api_device_id)
return response
def logout_user(request):
logout(request)
info_message = "You are now signed out."
messages.add_message(request, messages.INFO, info_message)
messages_on_stage = get_messages(request)
template_values = {
'request': request,
'next': '/admin/',
'messages_on_stage': messages_on_stage,
}
response = render(request, 'registration/login_user.html', template_values)
# Find current voter_api_device_id
voter_api_device_id = get_voter_api_device_id(request)
delete_voter_api_device_id_cookie(response)
# Now delete voter_api_device_id from database
voter_device_link_manager = VoterDeviceLinkManager()
voter_device_link_manager.delete_voter_device_link(voter_api_device_id)
return response
def redirect_to_sign_in_page(request, authority_required={}):
authority_required_text = ''
for each_authority in authority_required:
if each_authority == 'admin':
authority_required_text += 'or ' if len(authority_required_text) > 0 else ''
authority_required_text += 'has Admin rights'
if each_authority == 'verified_volunteer':
authority_required_text += 'or ' if len(authority_required_text) > 0 else ''
authority_required_text += 'has Verified Volunteer rights'
error_message = "You must sign in with account that " \
"{authority_required_text} to see that page." \
"".format(authority_required_text=authority_required_text)
messages.add_message(request, messages.ERROR, error_message)
if positive_value_exists(request.path):
next_url_variable = '?next=' + request.path
else:
next_url_variable = ''
return HttpResponseRedirect(LOGIN_URL + next_url_variable)
@login_required
def statistics_summary_view(request):
authority_required = {'verified_volunteer'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
google_civic_api_counter_manager = GoogleCivicApiCounterManager()
google_civic_daily_summary_list = google_civic_api_counter_manager.retrieve_daily_summaries()
vote_smart_api_counter_manager = VoteSmartApiCounterManager()
vote_smart_daily_summary_list = vote_smart_api_counter_manager.retrieve_daily_summaries()
template_values = {
'google_civic_daily_summary_list': google_civic_daily_summary_list,
'vote_smart_daily_summary_list': vote_smart_daily_summary_list,
}
response = render(request, 'admin_tools/statistics_summary.html', template_values)
return response
@login_required
def sync_data_with_master_servers_view(request):
authority_required = {'admin'} # admin, verified_volunteer
if not voter_has_authority(request, authority_required):
return redirect_to_sign_in_page(request, authority_required)
google_civic_election_id = request.GET.get('google_civic_election_id', '')
state_code = request.GET.get('state_code', '')
election_list = Election.objects.order_by('-election_day_text')
state_list = STATE_CODE_MAP
sorted_state_list = sorted(state_list.items())
template_values = {
'election_list': election_list,
'google_civic_election_id': google_civic_election_id,
'state_list': sorted_state_list,
'state_code': state_code,
'ballot_items_sync_url': BALLOT_ITEMS_SYNC_URL,
'ballot_returned_sync_url': BALLOT_RETURNED_SYNC_URL,
'candidates_sync_url': CANDIDATES_SYNC_URL,
'elections_sync_url': ELECTIONS_SYNC_URL,
'measures_sync_url': MEASURES_SYNC_URL,
'offices_sync_url': OFFICES_SYNC_URL,
'organizations_sync_url': ORGANIZATIONS_SYNC_URL,
'polling_locations_sync_url': POLLING_LOCATIONS_SYNC_URL,
'positions_sync_url': POSITIONS_SYNC_URL,
'voter_guides_sync_url': VOTER_GUIDES_SYNC_URL,
}
response = render(request, 'admin_tools/sync_data_with_master_dashboard.html', template_values)
return response
| {
"repo_name": "wevote/WebAppPublic",
"path": "admin_tools/views.py",
"copies": "1",
"size": "17374",
"license": "bsd-3-clause",
"hash": -2800165666899160000,
"line_mean": 46.9944751381,
"line_max": 117,
"alpha_frac": 0.6600667664,
"autogenerated": false,
"ratio": 3.7893129770992364,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.994113483855172,
"avg_score": 0.0016489809895031417,
"num_lines": 362
} |
#admin에서 메뉴 입력과 삭제, 재고 입력과 삭제, 가격조정 가능
number_of_coffee=3
coffee={1:'블랙커피', 2:'밀크커피', 3:'고급커피'}
stock={1 : 10, 2 : 10, 3 : 10}
cost={1:100, 2:150, 3:250}
while True:
money = input("자판기에 돈을 넣으세요 : ")
if money == "admin":
while True:
print("관리자 모드입니다.")
for i in range(1,number_of_coffee+1):
print(str(i)+"."+coffee[i]+" : "+str(stock[i])+"개")
add = input("기존 커피의 재고를 추가하려면 'stock_add'를, \n"
"기존 커피의 재고를 제거하려면 'stock_remove'를, \n"
"새로운 커피를 추가하려면 'type_add'를, \n"
"기존 커피를 제거하려면 'type_remove'를, \n"
"기존 커피의 가격을 조정하려면 'cost_renewal'을 입력하세요.(exit를 입력하면 종료됩니다.) : ")
if add == "type_add":
name_of_new_coffee = input("새로운 커피의 이름을 입력하세요 : ")
stock_of_new_coffee = int(input("추가할 새로운 커피의 개수를 입력하세요 : "))
cost_of_new_coffee = int(input("추가할 새로운 커피의 가격을 입력하세요 : "))
coffee[number_of_coffee+1]= name_of_new_coffee
stock[number_of_coffee+1]=stock_of_new_coffee
cost[number_of_coffee+1]= cost_of_new_coffee
number_of_coffee = number_of_coffee + 1
elif add == "type_remove":
coffee_to_remove = int(input("제거할 커피를 선택하세요 : "))
if coffee_to_remove not in range(1,number_of_coffee+1):
print("그런건 원래 없었습니다.")
else:
coffee_list =[]
stock_list =[]
cost_list =[]
for i in range(1,number_of_coffee+1):
coffee_list.append(coffee[i])
stock_list.append(stock[i])
cost_list.append(cost[i])
del coffee_list[coffee_to_remove-1]
del stock_list[coffee_to_remove-1]
del cost_list[coffee_to_remove-1]
number_of_coffee = number_of_coffee - 1
coffee={}
stock={}
cost={}
for i in range(1,number_of_coffee+1):
coffee[i]=coffee_list[i-1]
stock[i]=stock_list[i-1]
cost[i]=cost_list[i-1]
elif add == "stock_add":
type_to_add = int(input("추가할 커피를 선택하세요 : "))
stock_to_add = int(input("추가할 개수를 입력하세요 : "))
if type_to_add > number_of_coffee or type_to_add <= 0:
print("그런건 없습니다.")
else:
stock[type_to_add] = stock[type_to_add] + stock_to_add
elif add == "stock_remove":
type_to_remove = int(input("재고를 제거할 커피를 선택하세요 : "))
stock_to_remove = int(input("제거할 개수를 입력하세요 : "))
if type_to_remove not in range(1,number_of_coffee+1):
print("그런건 없습니다.")
elif type_to_remove in range(1,number_of_coffee+1):
if stock[type_to_remove] < stock_to_remove:
stock[type_to_remove] = 0
else:
stock[type_to_remove] = stock[type_to_remove] - stock_to_remove
elif add == "cost_renewal":
type_to_renew_cost=int(input("가격을 재설정할 커피를 선택하세요 : "))
if type_to_renew_cost not in range(1,number_of_coffee+1):
print("그런건 없습니다.")
else:
new_cost = int(input("새로운 가격을 입력하세요 : "))
cost[type_to_renew_cost]=new_cost
elif add == "exit":
print("관리자 모드를 끝냅니다.")
break
else:
print("그런건 없습니다.")
else:
while True:
money = int(money)
for i in range(1,number_of_coffee+1):
print("%d%s%s" %(i,'. ',coffee[i]))
print("%d%s" %(number_of_coffee+1,'. 거스름돈'))
choice=int(input('선택하세요 : '))
if choice not in range(1,number_of_coffee+2):
print("그런건 없습니다.")
elif choice != number_of_coffee+1 and money < cost[choice]:
print("돈이 부족합니다."+"\n거스름돈 : "+str(money)+"원")
break
elif choice == number_of_coffee+1:
print("거스름돈 : "+str(money)+"원")
elif stock[choice] == 0:
print("품절입니다.")
else:
print(coffee[choice]+"(이)가 나왔습니다.")
stock[choice] = stock[choice]-1
money = money - cost[choice]
print(money)
| {
"repo_name": "imn00133/pythonSeminar17",
"path": "exercise/vending_machine/Sehun/10_14_coffee5.py",
"copies": "1",
"size": "5336",
"license": "mit",
"hash": -5604026346085573000,
"line_mean": 45.2,
"line_max": 88,
"alpha_frac": 0.4506493506,
"autogenerated": false,
"ratio": 2.2736220472440944,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3224271397844094,
"avg_score": null,
"num_lines": null
} |
"""admin URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth.views import (
login, logout,
password_reset, password_reset_done,
password_reset_confirm, password_reset_complete
)
from apps.users import views
url_password_reset = {
'template_name':'auth/password/send_email.html',
'email_template_name':'auth/password/reset_email.html'
}
url_password_done = {
'template_name':'auth/password/reset_done.html'
}
url_password_confirm = {
'template_name': 'auth/password/reset_confirm.html'
}
url_done = {
'template_name': 'auth/password/reset_complete.html'
}
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', login, {'template_name':'auth/login.html'}, name='login'),
url(r'^register/', views.register_user, name = 'register'),
url(r'^logout/$', logout, {'next_page': '/'}, name= 'logout'),
url(r'^reset/password/$', password_reset,
url_password_reset, name='password_reset'
),
url(r'^reset/password_done/$', password_reset_done,
url_password_done, name='password_reset_done'
),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', password_reset_confirm,
url_password_confirm, name='password_reset_confirm'
),
url(r'^reset/done', password_reset_complete,
url_done, name='password_reset_complete'
),
#urls admin
url(r'^', include('apps.home.urls')),
url(r'^users/', include('apps.users.urls', namespace='users')),
url(r'^teams/', include('apps.teams.urls', namespace='teams')),
url(r'^players/', include('apps.players.urls', namespace='players')),
url(r'^competitions/', include('apps.competitions.urls', namespace='competitions')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) | {
"repo_name": "xeroz/admin-django",
"path": "admin/urls.py",
"copies": "1",
"size": "2623",
"license": "mit",
"hash": 6907791475670362000,
"line_mean": 37.5882352941,
"line_max": 88,
"alpha_frac": 0.6782310332,
"autogenerated": false,
"ratio": 3.4287581699346403,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46069892031346404,
"avg_score": null,
"num_lines": null
} |
"""admin URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'visualization.views.index', name='index'),
url(r'^base_monitor$', 'visualization.views.base_monitor', name='base_monitor'),
url(r'^conf_dashboard$', 'customization.views.conf_dashboard', name='conf_dashboard'),
url(r'^manage_pic$', 'customization.views.manage_pic', name='manage_pic'),
url(r'^database_monitor$', 'visualization.views.database_monitor', name='database_monitor'),
url(r'^money_of_all$', 'visualization.views.money_of_all', name='money_of_all'),
url(r'^money_of_province$', 'visualization.views.money_of_province', name='money_of_province'),
url(r'^order_count$', 'visualization.views.order_count', name='order_count'),
url(r'^product_count$', 'visualization.views.product_count', name='product_count'),
url(r'^site_data$', 'visualization.views.site_data', name='site_data'),
url(r'^dashboard1$', 'visualization.views.dashboard1', name='dashboard1'),
url(r'^dashboard2$', 'visualization.views.dashboard2', name='dashboard2'),
url(r'^api/post_profile_data$', 'visualization.views.api_post_profile_data', name='api_post_profile_data'),
url(r'^api/post_get_profile_data$', 'customization.views.post_get_profile_data', name='post_get_profile_data'),
url(r'^api/post_update_pic_profile$', 'customization.views.post_update_pic_profile', name='post_update_pic_profile'),
]
| {
"repo_name": "Madongming/admin",
"path": "admin/urls.py",
"copies": "1",
"size": "2105",
"license": "unlicense",
"hash": 218237839985339260,
"line_mean": 57.4722222222,
"line_max": 121,
"alpha_frac": 0.6983372922,
"autogenerated": false,
"ratio": 3.309748427672956,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4508085719872956,
"avg_score": null,
"num_lines": null
} |
"""Admin urls."""
from django.conf.urls import url, include
from django.conf import settings
import importlib
from happening.utils import plugin_enabled_decorator
from lib.required import required
from admin import views
urlpatterns = [
url(r'^$', views.index, name='admin'),
url(r'^backup$', views.backup, name='backup'),
url(r'^backup/(?P<pk>\d+)/cancel$', views.cancel_backup,
name='cancel_backup'),
url(r'^backup/(?P<pk>\d+)/delete$', views.delete_backup,
name='delete_backup'),
url(r'^backup/schedule$', views.schedule_backup, name='schedule_backup'),
# url(r'^backup/restore$', views.restore_backup, name='restore_backup'),
url(r'^plugins$', views.plugins, name='plugins'),
url(r'^configuration$', views.configuration, name='configuration'),
url(r'^appearance$', views.appearance, name='appearance'),
url(r'^menus$', views.menus, name='menus'),
url(r'^menus/(?P<pk>\d+)/up$', views.move_menu_up,
name='move_menu_up'),
url(r'^menus/(?P<pk>\d+)/down$', views.move_menu_down,
name='move_menu_down'),
url(r'^menus/(?P<pk>\d+)/delete$', views.delete_menu,
name='delete_menu'),
url(r'^payment_handlers$', views.payment_handlers,
name='payment_handlers'),
url(r'^payment_handlers/add$', views.add_payment_handler,
name='add_payment_handler'),
url(r'^payment_handlers/(?P<pk>\d+)/edit$', views.edit_payment_handler,
name='edit_payment_handler'),
url(r'^payment_handlers/(?P<pk>\d+)/delete$', views.delete_payment_handler,
name='delete_payment_handler'),
url(r'^payment_handlers/(?P<pk>\d+)/make_active$',
views.make_active_payment_handler,
name='make_active_payment_handler'),
url(r'^authentication$', views.authentication,
name='authentication'),
url(r'^authentication/add$', views.add_authentication,
name='add_authentication'),
url(r'^authentication/(?P<pk>\d+)/edit$', views.edit_authentication,
name='edit_authentication'),
url(r'^authentication/(?P<pk>\d+)/delete$', views.delete_authentication,
name='delete_authentication'),
url(r'^members$', views.members, name='staff_members'),
url(r'^members/(?P<member_pk>\d+)/groups/assign$', views.assign_to_group,
name='assign_to_group'),
url(r'^members/(?P<member_pk>\d+)/groups/(?P<group_pk>\d+)/assign$',
views.remove_from_group, name='remove_from_group'),
url(r'^members/groups$', views.groups, name='groups'),
url(r'^members/groups/create$', views.create_group, name='create_group'),
url(r'^members/groups/(?P<pk>\d+)/edit$', views.edit_group,
name='edit_group'),
url(r'^members/export$', views.export_members_to_csv,
name='export_members_to_csv'),
url(r'^events$', views.events, name='staff_events'),
url(r'^events/create$', views.create_event, name='create_event'),
url(r'^events/(?P<pk>\d+)$', views.event, name='staff_event'),
url(r'^events/(?P<pk>\d+)/export$', views.export_tickets_to_csv,
name='export_tickets_to_csv'),
url(r'^events/(?P<pk>\d+)/edit$', views.edit_event, name='edit_event'),
url(r'^events/(?P<pk>\d+)/email$', views.email_event, name='email_event'),
url(r'^events/waiting-lists/(?P<pk>\d+)$', views.manage_waiting_list,
name='manage_waiting_list'),
url(r'^events/waiting-lists/(?P<pk>\d+)/settings$',
views.waiting_list_settings,
name='waiting_list_settings'),
url(r'^events/waiting-lists/(?P<pk>\d+)/remove/(?P<user_pk>\d+)$',
views.remove_from_waiting_list,
name='remove_from_waiting_list'),
url(r'^events/waiting-lists/(?P<pk>\d+)/release/(?P<user_pk>\d+)$',
views.release_to_waiting_list,
name='release_to_waiting_list'),
url(r'^pages$', views.pages, name='pages'),
url(r'^pages/create$', views.create_page, name='create_page'),
url(r'^pages/block$', views.render_block, name='render_block'),
url(r'^pages/(?P<pk>\d+)$', views.edit_page, name='edit_page'),
url(r'^pages/(?P<pk>\d+)/delete$', views.delete_page, name='delete_page'),
url(r'^events/(?P<pk>\d+)/add_attendee$', views.add_attendee,
name='add_attendee'),
url(r'^tickets/(?P<pk>\d+)/check_in$', views.check_in, name='check_in'),
url(r'^tickets/(?P<pk>\d+)/cancel_check_in$', views.cancel_check_in,
name='cancel_check_in'),
url(r'^events/(?P<pk>\d+)/manage_check_ins$', views.manage_check_ins,
name='manage_check_ins'),
url(r'^emails$', views.staff_emails, name='staff_emails'),
url(r'^emails/preview$', views.preview_email, name='preview_email'),
url(r'^emails/(?P<pk>\d+)$', views.email, name='email'),
url(r'^emails/(?P<pk>\d+)/edit$', views.edit_email, name='edit_email'),
url(r'^emails/(?P<pk>\d+)/disable$', views.disable_email,
name='disable_email'),
url(r'^emails/(?P<pk>\d+)/enable$', views.enable_email,
name='enable_email'),
url(r'^emails/(?P<pk>\d+)/delete$', views.delete_email,
name='delete_email'),
url(r'^create_email$', views.create_email, name='create_email'),
url(r'^tags$', views.tags, name='tags'),
url(r'^tags/create$', views.create_tag, name='create_tag'),
url(r'^tags/(?P<pk>\d+)$', views.view_tag, name='view_tag'),
# url(r'^tags/(?P<pk>\d+)/edit$', views.edit_tag, name='edit_tag'),
url(r'^tags/(?P<pk>\d+)/delete$', views.delete_tag, name='delete_tag'),
url(r'^tags/(?P<member_pk>\d+)/(?P<tag_pk>\d+)/remove$', views.remove_tag,
name='remove_tag'),
url(r'^tags/(?P<member_pk>\d+)/add$', views.add_tag, name='add_tag'),
url(r'^tracking-links$', views.tracking_links, name='tracking_links'),
url(r'^tracking-links/create$', views.create_tracking_link,
name='create_tracking_link'),
url(r'^tracking-links/(?P<pk>\d+)/delete$', views.delete_tracking_link,
name='delete_tracking_link'),
]
if hasattr(settings, "PLUGINS"):
for plugin in settings.PLUGINS:
p = importlib.import_module(plugin)
if hasattr(p.Plugin, "admin_url_root"):
# Include the urlpatterns
urlpatterns += required(
plugin_enabled_decorator(plugin),
[url(p.Plugin.admin_url_root, include("%s.admin" % plugin))])
| {
"repo_name": "jscott1989/happening",
"path": "src/admin/urls.py",
"copies": "2",
"size": "6274",
"license": "mit",
"hash": -2572050165900328400,
"line_mean": 48.4015748031,
"line_max": 79,
"alpha_frac": 0.6195409627,
"autogenerated": false,
"ratio": 3.2848167539267017,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9904357716626702,
"avg_score": 0,
"num_lines": 127
} |
adminUser = raw_input('Enter the admin username, without the domain (e.g. dhay):')
adminPassword = raw_input('Enter the admin password: ')
print "\n" * 80 #clear screen
csvFile = 'EIPSTeacherGoogleAppsAccounts2014-08-26.csv'
import time
import csv
import gdata.apps.service
totalRows = sum(1 for row in open(csvFile, 'rb')) #count how many rows there are in the CSV file
print 'There are ', totalRows, ' entries in ', csvFile
countDown = totalRows #a variable we'll decrement as a count down to completion
currentRow = 0 #for keeping track of where we are in the CSV file
logFileName = 'GoogleAppsProvisioningScript' + time.strftime('%Y-%m-%d_%H%M%S') + '.txt' #build a name for the log file
logFile = open(logFileName, 'a') #create and/or open a log file that we'll append to
importFile = open(csvFile, 'rb') #(re)open the CSV file that we want to parse (since totalRows already looped through it)
reader = csv.reader(importFile) #we'll read the CSV file with this
def createUser(email, firstname, lastname, userPassword): #a function for creating a user account
domainIndex = email.find('@') #where is the @ at?
username = email[:domainIndex] #the username is the stuff before the @
domain = email[domainIndex+1:] #the domain is the stuff after the @
service = gdata.apps.service.AppsService(email=adminUser+'@'+domain, domain=domain, password=adminPassword)
service.ProgrammaticLogin() #log in to the Google Apps domain
try: #as long as there are no errors
# result = service.CreateUser(username, lastname, firstname, userPassword) #create the user account
agreedString = str(service.RetrieveUser(username)) #for testing we will check if user exists
agreedStart = agreedString.find('agreedToTerms="') + 15 #find the start of the "agreed"
agreedMessage = agreedString[agreedStart:5]
result = agreedMessage
# result = 'created successfully'
except gdata.apps.service.AppsForYourDomainException , e: #if there is an error
eString = str(e) #convert the error to a string
errorStart = eString.find('reason="') + 8 #find the start of the error
errorEnd = eString.find('" />') #find the end of the error, we'll do it this way rather than using ElementTree
#logFile.write('check https://developers.google.com/google-apps/provisioning/reference#GDATA_error_codes\n')
result = 'Error: ' + eString[errorStart:errorEnd] #return the error message, for logging purposes
return result #return the result back to the loop
for row in reader: #the loop that reads through the CSV file we mentioned earlier
email = row[0] #the first entry on this row is the email address
firstname = row[1]
lastname = row[2]
userPassword = row[3]
if currentRow > 0: #because we'll assume that the first row contains column titles, otherwise use >-1 or omit this line
result = createUser(email, firstname, lastname, userPassword) #call the function to create a User
rowString = str(currentRow) #convert that currentRow integer to a string so we can concatenate it
#print countDown + '(row number ' + rowString + ' parsed)' #print to the console, in case anyone is watching
print countDown, '(row number ', currentRow, ' parsed)'
logFile.write(rowString + time.strftime('%Y-%m-%d_%H:%M:%S') + ' ' + email + ' ') #log the date/time and email we tried to create
logFile.write(str(result)) #log the result of that function
logFile.write( '\n') #write a new line to the log file
currentRow += 1 #increment the currentRow variable
countDown -= 1 #decrement the countDown variable
#close the files
importFile.close()
logFile.close()
| {
"repo_name": "misterhay/GoogleAppsProvisioning",
"path": "checkUsers.py",
"copies": "1",
"size": "3703",
"license": "unlicense",
"hash": -3208486596006547500,
"line_mean": 57.7777777778,
"line_max": 137,
"alpha_frac": 0.7121253038,
"autogenerated": false,
"ratio": 3.75177304964539,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.496389835344539,
"avg_score": null,
"num_lines": null
} |
adminUser = raw_input('Enter the admin username, without the domain (e.g. dhay):')
adminPassword = raw_input('Enter the admin password: ')
print "\n" * 80 #clear screen
#csvFile = raw_input("Enter the name of the CSV file to parse, but don't include the .CSV part.")
csvFile = 'checkIfExist.csv'
import time
import csv
import gdata.apps.service
totalRows = sum(1 for row in open(csvFile, 'rb')) #count how many rows there are in the CSV file
print 'There are ', totalRows, ' entries in ', csvFile
countDown = totalRows #a variable we'll decrement as a count down to completion
currentRow = 0 #for keeping track of where we are in the CSV file
logFileName = 'checkUsersLog' + time.strftime('%Y-%m-%d_%H%M%S') + '.txt' #build a name for the log file
logFile = open(logFileName, 'a') #create and/or open a log file that we'll append to
importFile = open(csvFile, 'rb') #(re)open the CSV file that we want to parse (since totalRows already looped through it)
reader = csv.reader(importFile) #we'll read the CSV file with this
def checkUser(email): #a function for creating a user account
domainIndex = email.find('@') #where is the @ at?
username = email[:domainIndex] #the username is the stuff before the @
domain = email[domainIndex+1:] #the domain is the stuff after the @
service = gdata.apps.service.AppsService(email=adminUser+'@'+domain, domain=domain, password=adminPassword)
service.ProgrammaticLogin() #log in to the Google Apps domain
try: #as long as there are no errors
resultString = str(service.RetrieveUser(username)) #for testing we will check if user exists
resultStart = resultString.find('agreedToTerms=') + 14 #find the start of the "agreed"
resultEnd = resultStart + 6
resultMessage = resultString[resultStart:resultEnd]
result = resultMessage
except gdata.apps.service.AppsForYourDomainException , e: #if there is an error
eString = str(e) #convert the error to a string
errorStart = eString.find('reason="') + 8 #find the start of the error
errorEnd = eString.find('" />') #find the end of the error, we'll do it this way rather than using ElementTree
#logFile.write('check https://developers.google.com/google-apps/provisioning/reference#GDATA_error_codes\n')
result = 'Error: ' + eString[errorStart:errorEnd] #return the error message, for logging purposes
return result #return the result back to the loop
for row in reader: #the loop that reads through the CSV file we mentioned earlier
email = row[0] #the first entry on this row is the email address
#firstname = row[1]
#lastname = row[2]
#userPassword = row[3]
#if currentRow > 0: #because we'll assume that the first row contains column titles, otherwise use >-1 or omit this line
result = checkUser(email) #call the function to check a User
rowString = str(currentRow) #convert that currentRow integer to a string so we can concatenate it
#print countDown + '(row number ' + rowString + ' parsed)' #print to the console, in case anyone is watching
print countDown, '(row number ', currentRow, ' parsed)'
logFile.write(rowString + time.strftime('%Y-%m-%d_%H:%M:%S') + ' ' + email + ' ') #log the date/time and email we tried to create
logFile.write(str(result)) #log the result of that function
logFile.write( '\n') #write a new line to the log file
currentRow += 1 #increment the currentRow variable
countDown -= 1 #decrement the countDown variable
#close the files
importFile.close()
logFile.close()
| {
"repo_name": "misterhay/GoogleAppsProvisioning",
"path": "inProgress checkIfAgreedToTerms.py",
"copies": "1",
"size": "3559",
"license": "unlicense",
"hash": 2778714577523904000,
"line_mean": 55.4920634921,
"line_max": 133,
"alpha_frac": 0.710873841,
"autogenerated": false,
"ratio": 3.7189132706374086,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4929787111637408,
"avg_score": null,
"num_lines": null
} |
adminUser = raw_input('Enter the admin username, without the domain (e.g. dhay):')
adminPassword = raw_input('Enter the admin password: ')
print "\n" * 80 #clear screen
csvFile = 'schoolDomains.csv'
import time
import csv
import gdata.apps.organization.client
totalRows = sum(1 for row in open(csvFile, 'rb')) #count how many rows there are in the CSV file
print 'There are ', totalRows, ' entries in ', csvFile
countDown = totalRows #a variable we'll decrement as a count down to completion
currentRow = 0 #for keeping track of where we are in the CSV file
importFile = open(csvFile, 'rb') #(re)open the CSV file that we want to parse (since totalRows already looped through it)
reader = csv.reader(importFile) #we'll read the CSV file with this
##outputFileName = 'customerIDs' + time.strftime('%Y-%m-%d_%H%M%S') + '.csv' #build a name for the log file
##outputFile = open(outputFileName, 'a') #create and/or open a log file that we'll append to
def checkDomain(domain, organizationName):
domain = domain
organizationName = organizationName
adminEmail = adminUser + '@' + domain
##outputFile.write(domain)
##outputFile.write(',')
ouclient = gdata.apps.organization.client.OrganizationUnitProvisioningClient(domain=domain)
ouclient.ClientLogin(email=adminEmail, password=adminPassword, source ='apps')
customerIdString = str(ouclient.RetrieveCustomerId())
idStart = customerIdString.find('name="customerId" value="') + 25
idEnd = customerIdString.find(' /><ns2:property name="customerOrgUnitName"') - 1 #even though they are all 9 digits long
customer_id = customerIdString[idStart:idEnd]
##outputFile.write(customer_id)
#orgs = ouclient.RetrieveAllOrgUnits(customer_id)
#print ouclient.RetrieveOrgUnit(customer_id, 'Staff')
#numberOfOrgUnits = str(orgs).count('description')
#print numberOfOrgUnits
#outputFile.write(numberOfOrgUnits) #gives a buffer error of some sort
##outputFile.write( '\n')
ouclient.CreateOrgUnit(customer_id, organizationName, parent_org_unit_path='/', description=organizationName, block_inheritance=False) #create an organization
return customer_id
for row in reader:
print row[0], row[1]
result = checkDomain(row[0], row[1])
#import xml.etree.ElementTree as et
#root = et.fromstring(str(orgs))
#client = gdata.apps.client.AppsClient(domain=domain)
#client.ClientLogin(email=adminUser+'@'+domain, password=adminPassword, source='apps')
#client.ssl = True
#print username #to the terminal, so we know who the script is looking at
#user = client.RetrieveUser("david.hay")
#outputFile.write(user.login.user_name)
#outputFile.write(',')
#outputFile.write(domain)
#outputFile.write(',')
#outputFile.write(user.name.given_name)
#outputFile.write(',')
#outputFile.write(user.name.family_name)
#outputFile.write(',')
#outputFile.write(user.login.admin)
#outputFile.write(',')
#outputFile.write(user.login.agreed_to_terms)
#outputFile.write(',')
#outputFile.write(user.login.change_password)
#outputFile.write(',')
#outputFile.write(user.login.suspended)
#outputFile.write( '\n') #write a new line to the log file
def checkUser(email): #a function for checking a user account
domainIndex = email.find('@') #where is the @ at?
username = email[:domainIndex] #the username is the stuff before the @
domain = email[domainIndex+1:] #the domain is the stuff after the @
#service = gdata.apps.service.AppsService(email=adminUser+'@'+domain, domain=domain, password=adminPassword)
#service.ProgrammaticLogin() #log in to the Google Apps domain
try: #as long as there are no errors
#userObject = service.RetrieveUser(username) #retrieve user
result = username
except gdata.apps.service.AppsForYourDomainException , e: #if there is an error
eString = str(e) #convert the error to a string
errorStart = eString.find('reason="') + 8 #find the start of the error
errorEnd = eString.find('" />') #find the end of the error, we'll do it this way rather than using ElementTree
result = 'Error: ' + eString[errorStart:errorEnd] #return the error message
return result #return the result back to the loop
#call check UserFunction
#print result
#for row in reader: #the loop that reads through the CSV file we mentioned earlier
# email = row[0] #the first entry on this row is the email address
# #firstname = row[1]
# #lastname = row[2]
# #userPassword = row[3]
# #if currentRow > 0: #because we'll assume that the first row contains column titles, otherwise use >-1 or omit this line
# result = checkUser(email) #call the function to check a User
# rowString = str(currentRow) #convert that currentRow integer to a string so we can concatenate it
# #print countDown + '(row number ' + rowString + ' parsed)' #print to the console, in case anyone is watching
# print countDown, '(row number ', currentRow, ' parsed)'
# logFile.write(rowString + time.strftime('%Y-%m-%d_%H:%M:%S') + ' ' + email + ' ') #log the date/time and email we tried to create
# logFile.write(str(result)) #log the result of that function
# logFile.write( '\n') #write a new line to the log file
# currentRow += 1 #increment the currentRow variable
# countDown -= 1 #decrement the countDown variable
##outputFile.close() #close the file | {
"repo_name": "misterhay/GoogleAppsProvisioning",
"path": "createOrganizations.py",
"copies": "1",
"size": "5339",
"license": "unlicense",
"hash": 8268514091565728000,
"line_mean": 45.4347826087,
"line_max": 162,
"alpha_frac": 0.7203596179,
"autogenerated": false,
"ratio": 3.5357615894039736,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4756121207303973,
"avg_score": null,
"num_lines": null
} |
adminUser = raw_input('Enter the admin username, without the domain (e.g. dhay):')
adminPassword = raw_input('Enter the admin password: ')
print "\n" * 80 #clear screen
userToCheck = raw_input('Enter the email address of the user you want to check. ')
import time
import csv
import gdata.apps.client
#totalRows = sum(1 for row in open(csvFile, 'rb')) #count how many rows there are in the CSV file
#print 'There are ', totalRows, ' entries in ', csvFile
#countDown = totalRows #a variable we'll decrement as a count down to completion
#currentRow = 0 #for keeping track of where we are in the CSV file
outputFileName = 'checkUsers' + time.strftime('%Y-%m-%d_%H%M%S') + '.csv' #build a name for the log file
outputFile = open(outputFileName, 'a') #create and/or open a log file that we'll append to
outputFile.write('username')
outputFile.write(',')
outputFile.write('domain')
outputFile.write(',')
outputFile.write('first name')
outputFile.write(',')
outputFile.write('last name')
outputFile.write(',')
outputFile.write('admin')
outputFile.write(',')
outputFile.write('agreed to terms')
outputFile.write(',')
outputFile.write('change password at next login')
outputFile.write(',')
outputFile.write('suspended')
outputFile.write( '\n') #write a new line to the log file
domainIndex = userToCheck.find('@') #where is the @ at?
username = userToCheck[:domainIndex] #the username is the stuff before the @
domain = userToCheck[domainIndex+1:] #the domain is the stuff after the @
client = gdata.apps.client.AppsClient(domain=domain)
client.ClientLogin(email=adminUser+'@'+domain, password=adminPassword, source='apps')
client.ssl = True
print username #to the terminal, so we know who the script is looking at
user = client.RetrieveUser("david.hay")
outputFile.write(user.login.user_name)
outputFile.write(',')
outputFile.write(domain)
outputFile.write(',')
outputFile.write(user.name.given_name)
outputFile.write(',')
outputFile.write(user.name.family_name)
outputFile.write(',')
outputFile.write(user.login.admin)
outputFile.write(',')
outputFile.write(user.login.agreed_to_terms)
outputFile.write(',')
outputFile.write(user.login.change_password)
outputFile.write(',')
outputFile.write(user.login.suspended)
outputFile.write( '\n') #write a new line to the log file
def checkUser(email): #a function for checking a user account
domainIndex = email.find('@') #where is the @ at?
username = email[:domainIndex] #the username is the stuff before the @
domain = email[domainIndex+1:] #the domain is the stuff after the @
#service = gdata.apps.service.AppsService(email=adminUser+'@'+domain, domain=domain, password=adminPassword)
#service.ProgrammaticLogin() #log in to the Google Apps domain
try: #as long as there are no errors
#userObject = service.RetrieveUser(username) #retrieve user
result = username
except gdata.apps.service.AppsForYourDomainException , e: #if there is an error
eString = str(e) #convert the error to a string
errorStart = eString.find('reason="') + 8 #find the start of the error
errorEnd = eString.find('" />') #find the end of the error, we'll do it this way rather than using ElementTree
result = 'Error: ' + eString[errorStart:errorEnd] #return the error message
return result #return the result back to the loop
#call check UserFunction
#print result
#for row in reader: #the loop that reads through the CSV file we mentioned earlier
# email = row[0] #the first entry on this row is the email address
# #firstname = row[1]
# #lastname = row[2]
# #userPassword = row[3]
# #if currentRow > 0: #because we'll assume that the first row contains column titles, otherwise use >-1 or omit this line
# result = checkUser(email) #call the function to check a User
# rowString = str(currentRow) #convert that currentRow integer to a string so we can concatenate it
# #print countDown + '(row number ' + rowString + ' parsed)' #print to the console, in case anyone is watching
# print countDown, '(row number ', currentRow, ' parsed)'
# logFile.write(rowString + time.strftime('%Y-%m-%d_%H:%M:%S') + ' ' + email + ' ') #log the date/time and email we tried to create
# logFile.write(str(result)) #log the result of that function
# logFile.write( '\n') #write a new line to the log file
# currentRow += 1 #increment the currentRow variable
# countDown -= 1 #decrement the countDown variable
outputFile.close() #close the file
| {
"repo_name": "misterhay/GoogleAppsProvisioning",
"path": "inProgress checkUser.py",
"copies": "1",
"size": "4481",
"license": "unlicense",
"hash": 8757022562079803000,
"line_mean": 42.0865384615,
"line_max": 134,
"alpha_frac": 0.7203749163,
"autogenerated": false,
"ratio": 3.5283464566929132,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47487213729929134,
"avg_score": null,
"num_lines": null
} |
""" Admin view """
from flask import render_template, request, redirect, url_for
from flask.views import MethodView
from flask.ext.mongoengine.wtf import model_form
from ..models import Post, BlogPost, Video, Image, Quote
from ..app.auth import requires_auth
class List(MethodView):
""" Admin list view definition """
decorators = [requires_auth]
cls = Post
def get(self):
posts = self.cls.objects.all()
return render_template('admin/list.html', posts=posts)
class Detail(MethodView):
""" Admin detail view definition """
decorators = [requires_auth]
class_map = {
'post': BlogPost,
'video': Video,
'image': Image,
'quote': Quote
}
def get_context(self, slug=None):
""" Create context for template """
if slug:
post = Post.objects.get_or_404(slug=slug)
cls = post.__class__ if post.__class__ != Post else BlogPost
form_cls = model_form(Post, exclude=('created_at', 'comments'))
if 'POST' == request.method:
form = form_cls(request.form, initial=post._data)
else:
form = form_cls(obj=post)
else:
cls = self.class_map.get(request.args.get('type', 'post'))
post = cls()
form_cls = model_form(Post, exclude=('created_at', 'comments'))
form = form_cls(request.form)
context = {
'post': post,
'form': form,
'create': slug is None
}
return context
def get(self, slug): # pylint: disable=I0011,R0201
""" Render detail template """
context = self.get_context(slug)
return render_template('admin/detail.html', **context)
def post(self, slug):
""" Handle comment form post """
context = self.get_context(slug)
form = context.get('form')
if form.validate():
post = context.get('post')
form.populate_obj(post)
post.save()
return redirect(url_for('admin.index'))
return render_template('admin/detail.html', **context)
| {
"repo_name": "sudaraka/learn-flask-mongoengine",
"path": "src/views/admin.py",
"copies": "1",
"size": "2156",
"license": "bsd-2-clause",
"hash": 7488860261270935000,
"line_mean": 25.95,
"line_max": 75,
"alpha_frac": 0.5640074212,
"autogenerated": false,
"ratio": 4.029906542056075,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 80
} |
"""Admin views for the models of the ``calendarium`` app."""
from django.contrib import admin
from calendarium.models import (
Event,
EventCategory,
EventRelation,
Occurrence,
Rule,
)
class EventAdmin(admin.ModelAdmin):
"""Custom admin for the ``Event`` model."""
model = Event
fields = (
'title', 'start', 'end', 'description', 'category', 'created_by',
'rule', 'end_recurring_period', )
list_display = (
'title', 'start', 'end', 'category', 'created_by', 'rule',
'end_recurring_period', )
search_fields = ('title', 'description', )
date_hierarchy = 'start'
list_filter = ('category', )
class EventCategoryAdmin(admin.ModelAdmin):
"""Custom admin to display a small colored square."""
model = EventCategory
list_display = ('name', 'color', )
list_editable = ('color', )
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
admin.site.register(EventRelation)
admin.site.register(Occurrence)
admin.site.register(Rule)
| {
"repo_name": "claudep/django-calendarium",
"path": "calendarium/admin.py",
"copies": "3",
"size": "1061",
"license": "mit",
"hash": -112794819699884850,
"line_mean": 26.9210526316,
"line_max": 73,
"alpha_frac": 0.6540999057,
"autogenerated": false,
"ratio": 3.6460481099656357,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 38
} |
"""Admin views"""
from pathlib import Path
from flask import current_app
from flask_dance.contrib.google import make_google_blueprint
from flask_dance.consumer import oauth_authorized
from flask import flash, redirect, request, session, url_for
from flask_login import LoginManager, login_user, login_required, logout_user, AnonymousUserMixin
import ruamel.yaml
class AnonymousUser(AnonymousUserMixin):
def __init__(self):
self.name = "Paul T. Anderson"
self.email = "pt@anderson.com"
@property
def is_authenticated(self):
if current_app.config.get("LOGIN_DISABLED"):
return True
else:
return False
class UserManagement(object):
"""Provide usermanagement for a Flask app.
ENV variables:
GOOGLE_OAUTH_CLIENT_ID
GOOGLE_OAUTH_CLIENT_SECRET
USER_DATABASE_PATH
"""
def __init__(self, manager, User):
super(UserManagement, self).__init__()
self.User = User
self.manager = manager
self.login_manager = None
self.blueprint = None
self.setup()
def init_app(self, app):
app.register_blueprint(self.blueprint, url_prefix="/login")
@app.route("/login")
def login():
"""Redirect to the Google login page."""
# store potential next param URL in the session
if "next" in request.args:
session["next_url"] = request.args.get("next")
return redirect(url_for("google.login"))
@app.route("/logout")
@login_required
def logout():
logout_user()
flash("You have logged out", "info")
return redirect(url_for("index"))
self.login_manager.init_app(app)
def setup(self):
self.blueprint = make_google_blueprint(
scope=[
"https://www.googleapis.com/auth/userinfo.email",
"openid",
"https://www.googleapis.com/auth/userinfo.profile",
],
)
# setup login manager
self.login_manager = LoginManager()
self.login_manager.login_view = "login"
self.login_manager.anonymous_user = AnonymousUser
@self.login_manager.user_loader
def load_user(user_id):
return self.User.query.get(int(user_id))
@oauth_authorized.connect_via(self.blueprint)
def google_loggedin(blueprint, token, this=self):
"""Create/login local user on successful OAuth login."""
if not token:
flash("Failed to log in with {}".format(blueprint.name), "danger")
return redirect(url_for("index"))
# figure out who the user is
resp = blueprint.session.get("/oauth2/v1/userinfo?alt=json")
if resp.ok:
userinfo = resp.json()
# check if the user is whitelisted
email = userinfo["email"]
user_obj = this.User.query.filter_by(email=email).first()
if user_obj is None:
flash("email not whitelisted: {}".format(email), "danger")
return redirect(url_for("index"))
if user_obj:
user_obj.name = userinfo["name"]
user_obj.avatar = userinfo["picture"]
user_obj.google_id = userinfo["id"]
else:
user_obj = this.User(
google_id=userinfo["id"],
name=userinfo["name"],
avatar=userinfo["picture"],
email=email,
)
this.manager.add(user_obj)
this.manager.commit()
login_user(user_obj)
flash("Successfully signed in with Google", "success")
else:
message = "Failed to fetch user info from {}".format(blueprint.name)
flash(message, "danger")
next_url = session.pop("next_url", None)
return redirect(next_url or url_for("index"))
class UserAdmin(object):
"""docstring for UserAdmin"""
def __init__(self, database_path=None):
super(UserAdmin, self).__init__()
self.database_path = Path(database_path) if database_path else None
def init_app(self, app):
"""Initialize in Flask app context."""
self.database_path = Path(app.config["USER_DATABASE_PATH"])
def confirm(self, email):
"""Confirm that a user has been whitelisted."""
# read in the file on every request
with self.database_path.open("r") as in_handle:
whitelisted_emails = ruamel.yaml.safe_load(in_handle)["whitelist"]
return email in whitelisted_emails
| {
"repo_name": "Clinical-Genomics/taboo",
"path": "genotype/server/admin.py",
"copies": "1",
"size": "4781",
"license": "mit",
"hash": -7182568839287532000,
"line_mean": 33.15,
"line_max": 97,
"alpha_frac": 0.5645262497,
"autogenerated": false,
"ratio": 4.330615942028985,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5395142191728985,
"avg_score": null,
"num_lines": null
} |
"""Admin views."""
from flask import redirect, url_for, abort
from flask.globals import request
from flask_admin import expose, helpers
from flask_admin.contrib import sqla
import flask_admin as admin
import flask_login as login
from flaskiwsapp.admin.forms import AdminLoginForm, AdminUserForm
from flaskiwsapp.auth.snippets.authExceptions import AuthBaseException
from flaskiwsapp.auth.snippets.dbconections import auth0_user_signup, \
auth0_user_change_password
from flaskiwsapp.snippets.exceptions.baseExceptions import BaseIWSExceptions
from flaskiwsapp.users.validators import get_user
from flaskiwsapp.projects.controllers.requestControllers import insert_request_priority,\
remove_request_from_priority_list, update_request_on_priority_list, update_checked_request
from flaskiwsapp.workers.queueManager import create_request_sms_job, create_ticket_sms_job,\
create_ticket_email_job, create_welcome_user_email_job
from wtforms.fields.core import StringField
from wtforms.validators import DataRequired, URL
# Create customized model view class
class MyModelView(sqla.ModelView):
create_modal = True
edit_modal = True
def is_accessible(self):
return login.current_user.is_authenticated and login.current_user.is_admin
def _handle_view(self, name, **kwargs):
"""
Override builtin handle_view in order to redirect users when a
view is not accessible.
"""
if not self.is_accessible():
abort(404)
# Create customized view for user models
class UserView(MyModelView):
"""Flask user model view."""
form = AdminUserForm
list_template = 'admin/users/list.html'
column_searchable_list = ('email', 'phone_number', 'id')
def after_model_change(self, form, model, is_created):
# Set password if password_dummy is set
try:
if (form.password_dummy.data != '' and form.password_dummy.data is not None):
model.set_password(form.password_dummy.data)
if is_created:
auth0_user_signup(form.email.data, form.password_dummy.data)
create_welcome_user_email_job(model.id)
else:
auth0_user_change_password(form.email.data, form.password_dummy.data)
except (BaseIWSExceptions, AuthBaseException):
self.session.rollback()
class RequestView(MyModelView):
"""Flask Request model view."""
list_template = 'admin/request/list.html'
form_excluded_columns = ('ticket_url')
column_searchable_list = ('client_id', 'product_area', 'client_priority', 'target_date')
# Add dummy password field
form_extra_fields = {
'url_dummy': StringField('Ticket url', validators=[DataRequired(), URL()])
}
form_columns = (
'title',
'description',
'client',
'client_priority',
'product_area',
'url_dummy',
'target_date'
)
def on_model_change(self, form, model, is_created):
MyModelView.on_model_change(self, form, model, is_created)
model.ticket_url = form.url_dummy.data
def after_model_change(self, form, model, is_created):
MyModelView.after_model_change(self, form, model, is_created)
if is_created:
model = insert_request_priority(model)
create_request_sms_job(model.id)
else:
model = update_request_on_priority_list(model)
def on_model_delete(self, model):
MyModelView.after_model_delete(self, model)
model = remove_request_from_priority_list(model)
class TicketView(MyModelView):
"""Flask Request model view."""
form_columns = (
'request',
'user',
'detail'
)
column_searchable_list = ('user_id', 'request_id', 'created_at')
def after_model_change(self, form, model, is_created):
MyModelView.after_model_change(self, form, model, is_created)
request = update_checked_request(model.request.id)
create_ticket_sms_job(model.id)
create_ticket_email_job(model.id)
# Create customized index view class taht handles login & registration
class MyAdminIndexView(admin.AdminIndexView):
"""
Flask Admin view. Only Users with the 'is_admin' flag
have access.
"""
@expose('/')
def index(self):
if not login.current_user.is_authenticated:
return redirect(url_for('.login_view'))
return super(MyAdminIndexView, self).index()
@expose('/login/', methods=('GET', 'POST'))
def login_view(self):
# handle user login
form = AdminLoginForm(request.form)
if helpers.validate_form_on_submit(form):
user = get_user(form)
login.login_user(user)
if login.current_user.is_authenticated:
return redirect(url_for('.index'))
self._template_args['form'] = form
return super(MyAdminIndexView, self).index()
@expose('/logout/')
def logout_view(self):
login.logout_user()
return redirect(url_for('.login_view'))
| {
"repo_name": "rafasis1986/EngineeringMidLevel",
"path": "flaskiwsapp/admin/views.py",
"copies": "1",
"size": "5073",
"license": "mit",
"hash": -4235922436474208000,
"line_mean": 34.4755244755,
"line_max": 94,
"alpha_frac": 0.6613443722,
"autogenerated": false,
"ratio": 3.8402725208175625,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9998057204555275,
"avg_score": 0.0007119376924573943,
"num_lines": 143
} |
"""Admin views"""
import os.path
import logging
import re
import copy
from google.appengine.ext import webapp
from google.appengine.api import datastore_errors
from google.appengine.ext.webapp import template
from . import authorized
from . import utils
from . import admin_settings
from . import model_register
from .model_register import getModelAdmin
from .utils import Http404, Http500
from google.appengine.api import users
ADMIN_TEMPLATE_DIR = admin_settings.ADMIN_TEMPLATE_DIR
ADMIN_ITEMS_PER_PAGE = admin_settings.ADMIN_ITEMS_PER_PAGE
class BaseRequestHandler(webapp.RequestHandler):
def handle_exception(self, exception, debug_mode):
logging.warning("Exception catched: %r" % exception)
if isinstance(exception, Http404) or isinstance(exception, Http500):
self.error(exception.code)
path = os.path.join(ADMIN_TEMPLATE_DIR, str(exception.code) + ".html")
self.response.out.write(template.render(path, {'errorpage': True}))
else:
super(BaseRequestHandler, self).handle_exception(exception, debug_mode)
class Admin(BaseRequestHandler):
"""Use this class as view in your URL scheme definitions.
Example:
===
import appengine_admin
application = webapp.WSGIApplication([
...
# Admin pages
(r'^(/admin)(.*)$', appengine_admin.Admin),
...
], debug = settings.DEBUG)
===
Feel free to change "/admin" prefix to any other. Please don't change
anything else in given regular expression as get() and post() methods
of Admin class always expect to receive two attributes:
1) prefix - such as "/admin" that will be used for prefixing all generated admin
site urls
2) url - admin site page url (without prefix) that is used for determining what
action on what model user wants to make.
"""
def __init__(self):
logging.info("NEW Admin object created")
super(Admin, self).__init__()
# Define and compile regexps for Admin site URL scheme.
# Every URL will be mapped to appropriate method of this
# class that handles all requests of particular HTTP message
# type (GET or POST).
self.getRegexps = [
[r'^/?$', self.index_get],
[r'^/([^/]+)/list/$', self.list_get],
[r'^/([^/]+)/new/$', self.new_get],
[r'^/([^/]+)/edit/([^/]+)/$', self.edit_get],
[r'^/([^/]+)/delete/([^/]+)/$', self.delete_get],
[r'^/([^/]+)/get_blob_contents/([^/]+)/([^/]+)/$', self.get_blob_contents],
]
self.postRegexps = [
[r'^/([^/]+)/new/$', self.new_post],
[r'^/([^/]+)/edit/([^/]+)/$', self.edit_post],
]
self._compileRegexps(self.getRegexps)
self._compileRegexps(self.postRegexps)
# Store ordered list of registered data models.
self.models = model_register._modelRegister.keys()
self.models.sort()
# This variable is set by get and port methods and used later
# for constructing new admin urls.
self.urlPrefix = ''
def _compileRegexps(self, regexps):
"""Compiles all regular expressions in regexps list
"""
for i in range(len(regexps)):
regexps[i][0] = re.compile(regexps[i][0])
def get(self, urlPrefix, url):
"""Handle HTTP GET
"""
self.urlPrefix = urlPrefix
self._callHandlingMethod(url, self.getRegexps)
def post(self, urlPrefix, url):
"""Handle HTTP POST
"""
self.urlPrefix = urlPrefix
self.request.POST['author'] = users.get_current_user()
self._callHandlingMethod(url, self.postRegexps)
def _callHandlingMethod(self, url, regexps):
"""Tries matching given url by searching in list of compiled
regular expressions. Calls method that has been mapped
to matched regular expression or raises Http404 exception.
Url example: /ModelName/edit/kasdkjlkjaldkj/
"""
for regexp, function in regexps:
matched = regexp.match(url)
logging.info("Url: %s" % str(url))
logging.info("regex: %s" % str(regexp))
if matched:
function(*matched.groups())
return
# raise http error 404 (not found) if no match
raise Http404()
@staticmethod
def _safeGetItem(model, key):
"""Get record of particular model by key.
Raise Htt404 if not found or if key is not in correct format
"""
try:
item = model.get(key)
except datastore_errors.BadKeyError:
raise Http404()
if item is None:
raise Http404()
return item
@staticmethod
def _readonlyPropsWithValues(item, modelAdmin):
readonlyProperties = copy.deepcopy(modelAdmin._readonlyProperties)
for i in range(len(readonlyProperties)):
itemValue = getattr(item, readonlyProperties[i].name)
readonlyProperties[i].value = itemValue
if readonlyProperties[i].typeName == 'BlobProperty':
logging.info("%s :: Binary content" % readonlyProperties[i].name)
readonlyProperties[i].meta = utils.getBlobProperties(item, readonlyProperties[i].name)
if readonlyProperties[i].value:
readonlyProperties[i].value = True # release the memory
else:
logging.info("%s :: %s" % (readonlyProperties[i].name, readonlyProperties[i].value))
return readonlyProperties
@authorized.role("admin")
def index_get(self):
"""Show admin start page
"""
path = os.path.join(ADMIN_TEMPLATE_DIR, 'index.html')
self.response.out.write(template.render(path, {
'models': self.models,
'urlPrefix': self.urlPrefix,
}))
@authorized.role("admin")
def list_get(self, modelName):
"""Show list of records for particular model
"""
modelAdmin = getModelAdmin(modelName)
path = os.path.join(ADMIN_TEMPLATE_DIR, 'model_item_list.html')
page = utils.Page(
modelAdmin = modelAdmin,
itemsPerPage = ADMIN_ITEMS_PER_PAGE,
currentPage = self.request.get('page', 1)
)
# Get only those items that should be displayed in current page
items = page.getDataForPage()
self.response.out.write(template.render(path, {
'models': self.models,
'urlPrefix': self.urlPrefix,
'moduleTitle': modelAdmin.modelName,
'listProperties': modelAdmin._listProperties,
'items': map(modelAdmin._attachListFields, items),
'page': page,
}))
@authorized.role("admin")
def new_get(self, modelName):
"""Show form for creating new record of particular model
"""
modelAdmin = getModelAdmin(modelName)
templateValues = {
'models': self.models,
'urlPrefix': self.urlPrefix,
'item' : None,
'moduleTitle': modelAdmin.modelName,
'editForm': modelAdmin.AdminForm(urlPrefix = self.urlPrefix),
'readonlyProperties': modelAdmin._readonlyProperties,
}
path = os.path.join(ADMIN_TEMPLATE_DIR, 'model_item_edit.html')
self.response.out.write(template.render(path, templateValues))
@authorized.role("admin")
def new_post(self, modelName):
"""Create new record of particular model
"""
modelAdmin = getModelAdmin(modelName)
form = modelAdmin.AdminForm(urlPrefix = self.urlPrefix, data = self.request.POST)
if form.is_valid():
# Save the data, and redirect to the edit page
item = form.save()
self.redirect("%s/%s/edit/%s/" % (self.urlPrefix, modelAdmin.modelName, item.key()))
else:
# Display errors with entered values
templateValues = {
'models': self.models,
'urlPrefix': self.urlPrefix,
'item' : None,
'moduleTitle': modelAdmin.modelName,
'editForm': form,
'readonlyProperties': modelAdmin._readonlyProperties,
}
path = os.path.join(ADMIN_TEMPLATE_DIR, 'model_item_edit.html')
self.response.out.write(template.render(path, templateValues))
@authorized.role("admin")
def edit_get(self, modelName, key = None):
"""Show for for editing existing record of particular model.
Raises Http404 if record not found.
"""
modelAdmin = getModelAdmin(modelName)
item = self._safeGetItem(modelAdmin.model, key)
templateValues = {
'models': self.models,
'urlPrefix': self.urlPrefix,
'item' : item,
'moduleTitle': modelAdmin.modelName,
'editForm': modelAdmin.AdminForm(urlPrefix = self.urlPrefix, instance = item),
'readonlyProperties': self._readonlyPropsWithValues(item, modelAdmin),
}
path = os.path.join(ADMIN_TEMPLATE_DIR, 'model_item_edit.html')
self.response.out.write(template.render(path, templateValues))
@authorized.role("admin")
def edit_post(self, modelName, key):
"""Save details for already existing record of particular model.
Raises Http404 if record not found.
"""
modelAdmin = getModelAdmin(modelName)
item = self._safeGetItem(modelAdmin.model, key)
#item.author = users.get_current_user()
form = modelAdmin.AdminForm(urlPrefix = self.urlPrefix, data = self.request.POST, instance = item)
if form.is_valid():
# Save the data, and redirect to the edit page
item = form.save()
self.redirect("%s/%s/edit/%s/" % (self.urlPrefix, modelAdmin.modelName, item.key()))
else:
templateValues = {
'models': self.models,
'urlPrefix': self.urlPrefix,
'item' : item,
'moduleTitle': modelAdmin.modelName,
'editForm': form,
'readonlyProperties': self._readonlyPropsWithValues(item, modelAdmin),
}
path = os.path.join(ADMIN_TEMPLATE_DIR, 'model_item_edit.html')
self.response.out.write(template.render(path, templateValues))
@authorized.role("admin")
def delete_get(self, modelName, key):
"""Delete record of particular model.
Raises Http404 if record not found.
"""
modelAdmin = getModelAdmin(modelName)
item = self._safeGetItem(modelAdmin.model, key)
item.delete()
self.redirect("%s/%s/list/" % (self.urlPrefix, modelAdmin.modelName))
@authorized.role("admin")
def get_blob_contents(self, modelName, fieldName, key):
"""Returns blob field contents to user for downloading.
"""
modelAdmin = getModelAdmin(modelName)
item = self._safeGetItem(modelAdmin.model, key)
data = getattr(item, fieldName, None)
if data is None:
raise Http404()
else:
props = utils.getBlobProperties(item, fieldName)
if props:
self.response.headers['Content-Type'] = props['Content_Type']
self.response.headers['Content-Disposition'] = 'inline; filename=%s' % props['File_Name']
logging.info("Setting content type to %s" % props['Content_Type'])
else:
self.response.headers['Content-Type'] = 'application/octet-stream'
self.response.out.write(data)
| {
"repo_name": "frankk00/realtor",
"path": "appengine_admin/views.py",
"copies": "1",
"size": "11793",
"license": "bsd-3-clause",
"hash": 6384846311061600000,
"line_mean": 39.6655172414,
"line_max": 106,
"alpha_frac": 0.5954379717,
"autogenerated": false,
"ratio": 4.228397275008964,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5323835246708964,
"avg_score": null,
"num_lines": null
} |
"""Admin view to clear the cache."""
import logging
from auvsi_suas.models import FlyZone
from auvsi_suas.models import MissionConfig
from auvsi_suas.models import MovingObstacle
from auvsi_suas.models import ServerInfo
from auvsi_suas.models import StationaryObstacle
from auvsi_suas.models import Waypoint
from auvsi_suas.views import logger
from auvsi_suas.views.decorators import require_superuser
from django.contrib.auth.decorators import user_passes_test
from django.core.cache import cache
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views.generic import View
class ClearCache(View):
"""Clears the cache on admin's request."""
@method_decorator(require_superuser)
def dispatch(self, *args, **kwargs):
return super(ClearCache, self).dispatch(*args, **kwargs)
def get(self, request):
logger.info('Admin requested to clear the cache.')
cache.clear()
return HttpResponse("Cache cleared.")
@receiver(post_save, sender=FlyZone)
@receiver(post_save, sender=MissionConfig)
@receiver(post_save, sender=MovingObstacle)
@receiver(post_save, sender=ServerInfo)
@receiver(post_save, sender=StationaryObstacle)
@receiver(post_save, sender=Waypoint)
def clear_cache_on_invalidation(sender, **kwargs):
"""Clears the cache when certain models are updated."""
logging.info('Model saved invalidating caches, clearing them. Model: %s.',
sender)
cache.clear()
| {
"repo_name": "transformation/utatuav-interop",
"path": "auvsi/server/auvsi_suas/views/clear_cache.py",
"copies": "2",
"size": "1573",
"license": "apache-2.0",
"hash": 5609207855693976000,
"line_mean": 34.75,
"line_max": 78,
"alpha_frac": 0.7609663064,
"autogenerated": false,
"ratio": 3.6496519721577725,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5410618278557773,
"avg_score": null,
"num_lines": null
} |
# Admittedly this is just hack-crap-tastic.. so happy to have someone
# contribute a better way to auto-generate regular expressions :)
import re
import difflib
import StringIO
class REMorpher():
''' RE Morpher modifies a regular expression so that it matches the input_seq '''
def __init__(self):
self.reset_re()
self.op_map = {'literal': '%s', 'optional': '(%s)?', 'or': '(%s|%s)'}
def reset_re(self):
self.re_seq = []
self.re_ops = []
def add_sequence(self, input_seq):
# First sequence?
if not self.re_seq:
self.re_seq = input_seq
self.re_ops = ['literal'] * len(input_seq)
# The RE might already match input_seq
re_pattern = self.get_re_pattern()
if re.match(re_pattern, ''.join(input_seq)):
return
# Nope, so make the smallest amount of changes so that it does match
s = difflib.SequenceMatcher(None, self.re_seq, input_seq)
orig_len = len(self.re_seq)
for op_tuple in s.get_opcodes():
# Handles to the opcodes
op, re_start, re_end, in_start, in_end = op_tuple
re_offset = len(self.re_seq) - orig_len
re_start += re_offset
re_end += re_offset
# Do different modifications based on op type
if op == 'replace':
# Okay this logic needs to be fixed, right now just doing a psuedo 'or' with mulitple 'optional's.
self.re_seq = self.re_seq[:re_start] + input_seq[in_start:in_end] + self.re_seq[re_end-1:]
self.re_ops = self.re_ops[:re_start] + ['optional'] * (len(input_seq[in_start:in_end])+1) + self.re_ops[re_end-1:]
if op == 'insert':
self.re_seq = self.re_seq[:re_start] + input_seq[in_start:in_end] + self.re_seq[re_end:]
self.re_ops = self.re_ops[:re_start] + ['optional'] * len(input_seq[in_start:in_end]) + self.re_ops[re_end:]
if op == 'delete':
for i in xrange(re_start, re_end):
self.re_ops[re_start:re_end] = ['optional'] * len(self.re_ops[re_start:re_end])
# Sanity check the RE better match!
re_pattern = self.get_re_pattern()
if not re.match(re_pattern, ''.join(input_seq)):
print 'Critical Error: RE did NOT match! Destroy the Universe!'
print re_pattern
print input_seq
def get_re_pattern(self):
output = StringIO.StringIO()
_re_seq_prep = []
for item, op in zip(self.re_seq, self.re_ops):
buf = self.op_map[op] % item
_re_seq_prep.append(buf)
return ''.join(['^']+_re_seq_prep+['$'])
# Simple test of the re_morpher functionality
def _test():
a = [u'HOST', u'CONNECTION', u'ACCEPT', u'USER_AGENT', u'ACCEPT-ENCODING', u'ACCEPT-LANGUAGE', u'IF-MODIFIED-SINCE']
b = [u'HOST', u'CONNECTION', u'AUTHORIZATION', u'ACCEPT', u'USER_AGENT', u'ACCEPT-ENCODING', u'ACCEPT-LANGUAGE', u'IF-MODIFIED-SINCE']
c = [u'HOST', u'ACCEPT', u'USER_AGENT', u'ACCEPT-ENCODING', u'ACCEPT-LANGUAGE', u'IF-MODIFIED-SINCE']
d = [u'HOST', u'ACCEPT', u'BLAH-BLAH', u'ACCEPT-ENCODING', u'ACCEPT-LANGUAGE', u'IF-MODIFIED-SINCE']
e = [u'HOST', u'ACCEPT', u'BLAH-BLAH', u'ACCEPT-ENCODING', u'ACCEPT-LANGUAGE', u'IF-MODIFIED-SINCE', 'AUTHORIZATION']
my_re_morpher = REMorpher()
my_re_morpher.add_sequence(a)
print my_re_morpher.get_re_pattern()
my_re_morpher.add_sequence(b)
print my_re_morpher.get_re_pattern()
my_re_morpher.add_sequence(c)
print my_re_morpher.get_re_pattern()
my_re_morpher.add_sequence(d)
print my_re_morpher.get_re_pattern()
# It should match all but 'e'
match = [a, b, c, d]
not_match = [e]
re_pattern = my_re_morpher.get_re_pattern()
print '\n' * 3 + 'Testing Results:'
for m in match:
if re.match(re_pattern, ''.join(m)):
print 'Good %s match' % m
else:
print 'FAIL: %s did not match' % m
for m in not_match:
if not re.match(re_pattern, ''.join(m)):
print 'Good %s no-match' % m
else:
print 'FAIL: %s matched' % m
# Additional testing
foo = [[u'CONNECTION', u'COOKIE', u'USER-AGENT', u'TRANSLATE', u'HOST'],
[u'CONNECTION', u'COOKIE', u'USER-AGENT', u'TRANSLATE', u'HOST', u'AUTHORIZATION'],
[u'CONNECTION', u'COOKIE', u'USER-AGENT', u'TRANSLATE', u'HOST', u'AUTHORIZATION'],
[u'CONNECTION', u'COOKIE', u'USER-AGENT', u'DEPTH', u'TRANSLATE', u'CONTENT-LENGTH', u'HOST'],
[u'CONNECTION', u'COOKIE', u'USER-AGENT', u'DEPTH', u'TRANSLATE', u'CONTENT-LENGTH', u'HOST', u'AUTHORIZATION'],
[u'CONNECTION', u'COOKIE', u'USER-AGENT', u'DEPTH', u'TRANSLATE', u'CONTENT-LENGTH', u'HOST', u'AUTHORIZATION'],
[u'CONNECTION', u'USER-AGENT', u'DEPTH', u'TRANSLATE', u'CONTENT-LENGTH', u'HOST', u'COOKIE'],
[u'CONNECTION', u'USER-AGENT', u'DEPTH', u'TRANSLATE', u'CONTENT-LENGTH', u'HOST', u'COOKIE'],
[u'CONNECTION', u'USER-AGENT', u'DEPTH', u'TRANSLATE', u'CONTENT-LENGTH', u'HOST', u'COOKIE'],
[u'CONNECTION', u'USER-AGENT', u'DEPTH', u'TRANSLATE', u'CONTENT-LENGTH', u'HOST', u'COOKIE'],
[u'CONNECTION', u'CONTENT-TYPE', u'USER-AGENT', u'X-VERMEER-CONTENT-TYPE', u'CONTENT-LENGTH', u'HOST', u'COOKIE'],
[u'CONNECTION', u'USER-AGENT', u'DEPTH', u'TRANSLATE', u'CONTENT-LENGTH', u'HOST', u'COOKIE']]
my_re_morpher.reset_re()
for f in foo:
my_re_morpher.add_sequence(f)
print my_re_morpher.get_re_pattern()
if __name__ == "__main__":
_test() | {
"repo_name": "rolando/ClickSecurity-data_hacking",
"path": "browser_fingerprinting/re_morpher.py",
"copies": "6",
"size": "5695",
"license": "mit",
"hash": -2582097067514077000,
"line_mean": 42.8153846154,
"line_max": 138,
"alpha_frac": 0.5792800702,
"autogenerated": false,
"ratio": 3.129120879120879,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0038570919088812793,
"num_lines": 130
} |
"""ADMM CORE ALGORITHM
Copyright (c) 2017 The ADMML Authors.
All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at :
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from copy import copy
import numpy as np
from numpy.linalg import inv, norm
from . import mappers
from . import utils
########################## ADMM STEPS ################################
def ADMM(trndata, algoParam):
"""This is the main engine that implements the ADMM steps.
Parameters
----------
trndata : RDD
RDD with each entry as numpy array [y, **x**]
algoParam : dict
This contains the algorithm parameters for ML/ADMM algorithm.
The default can be set as: ``algoParam = setDefaultAlgoParams()``
Returns
-------
z : numpy.ndarray
Weight vector [w,b] (bias term appended to end)
output : dict
Dictionary of the algorithm outputs
* ``W_k``: each row correspond to w vectors at k_th ADMM iteration
* ``norm_pri``: :math:`\\ell^2`-norm of primal residual
* ``norm_dual``: :math:`\\ell^2`-norm of dual residual
* ``rel_norm_pri``: relative norm of primal residual
* ``rel_norm_dual``: relative norm of dual residual
"""
def rho_initialize(algoParam):
"""This function initializes the algoParam['RHO'] value.
There are several strategies, and this is an ongoing research topic.
Current implementation use a fixed RHO = LAMBDA .
Additional methods to be included later. For further details see:
1. Boyd, Stephen, et al. "Distributed optimization and statistical
learning via the alternating direction method of multipliers."
2. Goldstein, Tom, et al. "Fast alternating direction optimization
methods." SIAM Journal on Imaging Sciences 7.3 (2014): 1588-1623.
3. Ghadimi, Euhanna, et al. "Optimal parameter selection for the
alternating direction method of multipliers (ADMM): quadratic
problems." IEEE Transactions on Automatic Control 60.3 (2015):
644-658.
Parameters
----------
algoParam : dict
This contains the algorithm parameters for ML/ADMM algorithm.
The default can be set as: ``algoParam = setDefaultAlgoParams()``
Returns
-------
algoParam : dict
The ``algoParam`` dict with correctly initialized rho
"""
if algoParam['RHO_INITIAL'] == 0:
algoParam['RHO'] = algoParam['LAMBDA']
else:
raise ValueError('Inconsistent RHO Selection!')
return algoParam
def rho_adjustment(rho, norm_pri, norm_dual):
"""This function defines the adaptive RHO updates.
There are several strategies, and this is an ongoing research topic.
We use the version of the strategy in [Boyd, 2011] pg. 20
1. Boyd, Stephen, et al. "Distributed optimization and statistical
learning via the alternating direction method of multipliers."
Parameters
----------
rho : float
Current RHO value
norm_pri : float
Current normed primal residual
norm_dual : float
Current normed dual residual
Returns
-------
rho : float
Updated RHO
"""
if norm_pri > 10*norm_dual:
rho *= 2
elif norm_dual > 10*norm_pri:
rho /= 2
return rho
def z_update(w, u, algoParam):
"""**z** update steps in ADMM Algorithm. Changes only for different regularizers.
Parameters
----------
w : numpy.ndarray
w-vector obtained from the previous w-update step
u : numpy.ndarray
u-vector (current state)
algoParam : dict
This contains the algorithm parameters for ML/ADMM algorithm.
The default can be set as: ``algoParam = setDefaultAlgoParams()``
Returns
-------
z : numpy.ndarray
z-update step
"""
D = algoParam['D']
z = np.zeros(D)
# PROXIMAL OPERATORS
# ELASTIC-NET REGULARIZER
if algoParam['REG'] == 'elasticnet':
for j in range(D):
if algoParam['RHO']*(w[j]+u[j]) > algoParam['LAMBDA']*algoParam['DELTA'][j]*algoParam['ALPHA']:
z[j] = (algoParam['RHO']*(w[j]+u[j])-algoParam['LAMBDA']*algoParam['DELTA'][j]*algoParam['ALPHA'])/(algoParam['LAMBDA']*algoParam['DELTA'][j]*(1-algoParam['ALPHA'])+algoParam['RHO'])
elif algoParam['RHO']*(w[j]+u[j]) < -algoParam['LAMBDA']*algoParam['DELTA'][j]*algoParam['ALPHA']:
z[j] = (algoParam['RHO']*(w[j]+u[j])+algoParam['LAMBDA']*algoParam['DELTA'][j]*algoParam['ALPHA'])/(algoParam['LAMBDA']*algoParam['DELTA'][j]*(1-algoParam['ALPHA'])+algoParam['RHO'])
# GROUP-REGULARIZER
elif algoParam['REG'] == 'group':
G = algoParam['G']
Gmax = len(G)
for j in range(Gmax):
gind = np.where(algoParam['DELTA'] == j)[0]
wG = w[gind]
uG = u[gind]
zG = max(norm(wG+uG)-(algoParam['LAMBDA']*G[j])/algoParam['RHO'], 0.)*((wG+uG)/norm(wG+uG))
z[gind] = zG
else:
raise ValueError('ERROR: Unsupported Regularizer.')
return z
def w_update(trndata, z, u, algoParam):
"""**w** update steps in ADMM Algorithm. Changes only for different loss functions
Parameters
----------
trndata : RDD
RDD with each entry as numpy array [y,x]
z : numpy.ndarray
z-vector from previous state
u : numpy.ndarray
u-vector from previous state
algoParam : dict
This contains the algorithm parameters for ML/ADMM algorithm.
The default can be set as: ``algoParam = setDefaultAlgoParams()``
Returns
-------
w : numpy.ndarray
w-update step
"""
N = algoParam['N']
D = algoParam['D']
if algoParam['LOSS'] == 'leastsq':
P = trndata.map(lambda x: np.outer(x[1:], x[1:])).reduce(lambda x, y: np.add(x, y))/N + algoParam['RHO']*np.identity(D)
q = trndata.map(lambda x: np.dot(x[0], x[1:])).reduce(lambda x, y: np.add(x, y))/N + algoParam['RHO']*(z - u)
return np.dot(inv(P), q)
# HUBER & PSEUDO-HUBER: initialize with the least-squares solution
if algoParam['LOSS'] in ['huber', 'pseudo_huber'] and algoParam['PROBLEM'] == 'regression':
P = trndata.map(lambda x: np.outer(x[1:], x[1:])).reduce(lambda x, y: np.add(x, y))/N + algoParam['RHO']*np.identity(D)
q = trndata.map(lambda x: np.dot(x[0], x[1:])).reduce(lambda x, y: np.add(x, y))/N + algoParam['RHO']*(z - u)
w = np.dot(inv(P), q)
mu_max = algoParam['MU_MAX'] # GRADUALLY OBTAIN FINAL SOLUTION
else:
w = np.zeros(D)
mu_max = None
# NEWTON UPDATES
for j in range(algoParam['MAX_INNER_ITER']):
if algoParam['LOSS'] in ['huber', 'pseudo_huber'] and algoParam['PROBLEM'] == 'regression':
mu_max = max(mu_max, algoParam['MU'])
H_v = trndata.map(lambda x: mappers.mapHv(algoParam, x, w, mu_max)).reduce(utils.combineHv)
H = H_v[0]/N
v = H_v[1]/N
P = H + algoParam['RHO']*(np.identity(D))
Pinv = inv(P)
q = v + algoParam['RHO']*(w-z+u)
w_old = copy(w)
w = w - np.dot(Pinv, q)
in_residual = norm(w-w_old)/norm(w)
if mu_max is not None:
if in_residual < algoParam['INNER_TOL'] and mu_max-algoParam['MU'] <= 1e-6:
break
else:
mu_max /= 2.
elif in_residual < algoParam['INNER_TOL']:
break
return w
# ADMM ALGORITHM
D = algoParam['D']
z = u = np.zeros(D)
W_k = z
rel_norm_pri = []
rel_norm_dual = []
# INITIALIZE RHO
algoParam = rho_initialize(algoParam)
for k in range(algoParam['MAX_ITER']):
z_old = copy(z)
w = w_update(trndata, z, u, algoParam)
z = z_update(w, u, algoParam)
u = u+w-z
norm_pri = norm(w-z)
norm_dual = norm(z-z_old)
W_k = np.vstack((W_k, z))
rel_norm_pri.append(norm_pri/norm(w))
rel_norm_dual.append(norm_dual/norm(z))
if algoParam['RHO_ADAPTIVE_FLAG']:
algoParam['RHO'] = rho_adjustment(algoParam['RHO'], rel_norm_pri[k], rel_norm_dual[k])
converged = rel_norm_pri[k] < algoParam['PRIM_TOL'] and rel_norm_dual[k] < algoParam['DUAL_TOL']
if converged:
break
elif algoParam['VERBOSE'] == 1:
# print the convergence results
print("Iteration: {0} Current RHO : ({1}) Primal Residual (Rel.): {2}({3}) Dual Residual (Rel.): {4}({5})".format(k+1, algoParam['RHO'], norm_pri, rel_norm_pri[k], norm_dual, rel_norm_dual[k]))
output = {'W_k': W_k,
'norm_pri': norm_pri,
'norm_dual': norm_dual,
'rel_norm_pri': rel_norm_pri,
'rel_norm_dual': rel_norm_dual}
return z, output
| {
"repo_name": "DL-Benchmarks/ADMML",
"path": "admml/admml.py",
"copies": "1",
"size": "9798",
"license": "apache-2.0",
"hash": -7215619511767454000,
"line_mean": 35.1549815498,
"line_max": 206,
"alpha_frac": 0.560420494,
"autogenerated": false,
"ratio": 3.622181146025878,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4682601640025878,
"avg_score": null,
"num_lines": null
} |
"""ADM Router"""
import time
import requests
from typing import Any # noqa
from requests.exceptions import ConnectionError, Timeout
from twisted.internet.threads import deferToThread
from twisted.logger import Logger
from autopush.constants import DEFAULT_ROUTER_TIMEOUT
from autopush.exceptions import RouterException
from autopush.metrics import make_tags
from autopush.router.interface import RouterResponse
from autopush.types import JSONDict # noqa
class ADMAuthError(Exception):
pass
class ADMClient(object):
def __init__(self,
credentials=None,
logger=None,
metrics=None,
endpoint="api.amazon.com",
timeout=DEFAULT_ROUTER_TIMEOUT,
**options
):
self._client_id = credentials["client_id"]
self._client_secret = credentials["client_secret"]
self._token_exp = 0
self._auth_token = None
self._aws_host = endpoint
self._logger = logger
self._metrics = metrics
self._request = requests
self._timeout = timeout
def refresh_key(self):
url = "https://{}/auth/O2/token".format(self._aws_host)
if self._auth_token is None or self._token_exp < time.time():
body = dict(
grant_type="client_credentials",
scope="messaging:push",
client_id=self._client_id,
client_secret=self._client_secret
)
headers = {
"content-type": "application/x-www-form-urlencoded"
}
resp = self._request.post(url, data=body, headers=headers,
timeout=self._timeout)
if resp.status_code != 200:
self._logger.error("Could not get ADM Auth token {}".format(
resp.text
))
raise ADMAuthError("Could not fetch auth token")
reply = resp.json()
self._auth_token = reply['access_token']
self._token_exp = time.time() + reply.get('expires_in', 0)
def send(self, reg_id, payload, ttl=None, collapseKey=None):
self.refresh_key()
headers = {
"Authorization": "Bearer {}".format(self._auth_token),
"Content-Type": "application/json",
"X-Amzn-Type-Version":
"com.amazon.device.messaging.ADMMessage@1.0",
"X-Amzn-Accept-Type":
"com.amazon.device.messaging.ADMSendResult@1.0",
"Accept": "application/json",
}
data = {}
if ttl:
data["expiresAfter"] = ttl
if collapseKey:
data["consolidationKey"] = collapseKey
data["data"] = payload
url = ("https://api.amazon.com/messaging/registrations"
"/{}/messages".format(reg_id))
resp = self._request.post(
url,
json=data,
headers=headers,
timeout=self._timeout,
)
# in fine tradition, the response message can sometimes be less than
# helpful. Still, good idea to include it anyway.
if resp.status_code != 200:
self._logger.error("Could not send ADM message: " + resp.text)
raise RouterException(resp.content)
class ADMRouter(object):
"""Amazon Device Messaging Router Implementation"""
log = Logger()
dryRun = 0
collapseKey = None
MAX_TTL = 2419200
def __init__(self, conf, router_conf, metrics):
"""Create a new ADM router and connect to ADM"""
self.conf = conf
self.router_conf = router_conf
self.metrics = metrics
self.min_ttl = router_conf.get("ttl", 60)
timeout = router_conf.get("timeout", DEFAULT_ROUTER_TIMEOUT)
self.profiles = dict()
for profile in router_conf:
config = router_conf[profile]
if "client_id" not in config or "client_secret" not in config:
raise IOError("Profile info incomplete, missing id or secret")
self.profiles[profile] = ADMClient(
credentials=config,
logger=self.log,
metrics=self.metrics,
timeout=timeout)
self._base_tags = ["platform:adm"]
self.log.debug("Starting ADM router...")
def amend_endpoint_response(self, response, router_data):
# type: (JSONDict, JSONDict) -> None
pass
def register(self, uaid, router_data, app_id, *args, **kwargs):
# type: (str, JSONDict, str, *Any, **Any) -> None
"""Validate that the ADM Registration ID is in the ``router_data``"""
if "token" not in router_data:
raise self._error("connect info missing ADM Instance 'token'",
status=401)
profile_id = app_id
if profile_id not in self.profiles:
raise self._error("Invalid ADM Profile",
status=410, errno=105,
uri=kwargs.get('uri'),
profile_id=profile_id)
# Assign a profile
router_data["creds"] = {"profile": profile_id}
def route_notification(self, notification, uaid_data):
"""Start the ADM notification routing, returns a deferred"""
# Kick the entire notification routing off to a thread
return deferToThread(self._route, notification, uaid_data)
def _route(self, notification, uaid_data):
"""Blocking ADM call to route the notification"""
router_data = uaid_data["router_data"]
# THIS MUST MATCH THE CHANNELID GENERATED BY THE REGISTRATION SERVICE
# Currently this value is in hex form.
data = {"chid": notification.channel_id.hex}
# Payload data is optional. The endpoint handler validates that the
# correct encryption headers are included with the data.
if notification.data:
data['body'] = notification.data
data['con'] = notification.headers['encoding']
if 'encryption' in notification.headers:
data['enc'] = notification.headers.get('encryption')
if 'crypto_key' in notification.headers:
data['cryptokey'] = notification.headers['crypto_key']
# registration_ids are the ADM instance tokens (specified during
# registration.
ttl = min(self.MAX_TTL,
max(notification.ttl or 0, self.min_ttl))
try:
adm = self.profiles[router_data['creds']['profile']]
adm.send(
reg_id=router_data.get("token"),
payload=data,
collapseKey=notification.topic,
ttl=ttl
)
except RouterException:
raise # pragma nocover
except Timeout as e:
self.log.warn("ADM Timeout: %s" % e)
self.metrics.increment("notification.bridge.error",
tags=make_tags(
self._base_tags,
reason="timeout"))
raise RouterException("Server error", status_code=502,
errno=902,
log_exception=False)
except ConnectionError as e:
self.log.warn("ADM Unavailable: %s" % e)
self.metrics.increment("notification.bridge.error",
tags=make_tags(
self._base_tags,
reason="connection_unavailable"))
raise RouterException("Server error", status_code=502,
errno=902,
log_exception=False)
except ADMAuthError as e:
self.log.error("ADM unable to authorize: %s" % e)
self.metrics.increment("notification.bridge.error",
tags=make_tags(
self._base_tags,
reason="auth_failure"
))
raise RouterException("Server error", status_code=502,
errno=901,
log_exception=False)
except Exception as e:
self.log.error("Unhandled exception in ADM Routing: %s" % e)
raise RouterException("Server error", status_code=500)
location = "%s/m/%s" % (self.conf.endpoint_url, notification.version)
return RouterResponse(status_code=201, response_body="",
headers={"TTL": ttl,
"Location": location},
logged_status=200)
def _error(self, err, status, **kwargs):
"""Error handler that raises the RouterException"""
self.log.debug(err, **kwargs)
return RouterException(err, status_code=status, response_body=err,
**kwargs)
| {
"repo_name": "mozilla-services/autopush",
"path": "autopush/router/adm.py",
"copies": "1",
"size": "9092",
"license": "mpl-2.0",
"hash": -6402786372473828000,
"line_mean": 40.1402714932,
"line_max": 78,
"alpha_frac": 0.5394852618,
"autogenerated": false,
"ratio": 4.56425702811245,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.560374228991245,
"avg_score": null,
"num_lines": null
} |
# ADM This code was used to generate Gaia files for testing.
# ADM All that is required is a link to the desitarget GAIA_DIR.
# SJB prevent import from running this code
if __name__ == "__main__":
import os
import fitsio
import numpy as np
from time import time
from pkg_resources import resource_filename
from desitarget.gaiamatch import find_gaia_files
from desitarget.tychomatch import find_tycho_files
from desitarget.uratmatch import find_urat_files
from desitarget import io
start = time()
# ADM choose the Gaia files to cover the same object
# ADM locations as the sweeps/tractor files.
datadir = resource_filename('desitarget.test', 't')
tractorfiles = sorted(io.list_tractorfiles(datadir))
sweepfiles = sorted(io.list_sweepfiles(datadir))
# ADM read in relevant Gaia files.
gaiafiles = []
for fn in sweepfiles + tractorfiles:
objs = fitsio.read(fn, columns=["RA", "DEC"])
gaiafiles.append(find_gaia_files(objs, neighbors=False))
gaiafiles = np.unique(np.concatenate(gaiafiles))
# ADM loop through the Gaia files and write out some rows
# ADM to the "t4" unit test directory.
tychofiles, uratfiles = [], []
if not os.path.exists("t4"):
os.makedirs(os.path.join("t4", "healpix"))
for fn in gaiafiles:
objs, hdr = fitsio.read(fn, 1, header=True)
outfile = os.path.join("t4", "healpix", os.path.basename(fn))
fitsio.write(outfile, objs[:25], header=hdr, clobber=True, extname="GAIAHPX")
# ADM find some Tycho and URAT files that accompany the Gaia files.
tychofiles.append(find_tycho_files(objs[:25], neighbors=False))
uratfiles.append(find_urat_files(objs[:25], neighbors=False))
print("writing {}".format(outfile))
tychofiles = np.unique(np.concatenate(tychofiles))
uratfiles = np.unique(np.concatenate(uratfiles))
# ADM loop through the Gaia files and write out accompanying Tycho
# ADM and URAT objects.
for direc, fns, ext in zip(["tycho", "urat"],
[tychofiles, uratfiles],
["TYCHOHPX", "URATHPX"]):
outdir = os.path.join("t4", direc)
if not os.path.exists(outdir):
os.makedirs(os.path.join("t4", direc, "healpix"))
for fn in fns:
objs, hdr = fitsio.read(fn, 1, header=True)
outfile = os.path.join("t4", direc, "healpix", os.path.basename(fn))
s = set(gaiafiles)
# ADM ensure a match with objects in the Gaia files.
ii = np.array([len(
set(find_gaia_files(i, neighbors=False)).intersection(s)) > 0
for i in objs])
fitsio.write(outfile, objs[ii][:25],
clobber=True, header=hdr, extname=ext)
print("writing {}".format(outfile))
print('Done...t={:.2f}s'.format(time()-start))
| {
"repo_name": "desihub/desitarget",
"path": "py/desitarget/test/make_testgaia.py",
"copies": "1",
"size": "2929",
"license": "bsd-3-clause",
"hash": -3231803707960066000,
"line_mean": 42.7164179104,
"line_max": 85,
"alpha_frac": 0.6261522704,
"autogenerated": false,
"ratio": 3.437793427230047,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9562156624048772,
"avg_score": 0.0003578147162550726,
"num_lines": 67
} |
""" Adobe character mapping (CMap) support.
CMaps provide the mapping between character codes and Unicode
code-points to character ids (CIDs).
More information is available on the Adobe website:
http://opensource.adobe.com/wiki/display/cmap/CMap+Resources
"""
import sys
import os
import os.path
import gzip
import pickle as pickle
import struct
import logging
from .psparser import PSStackParser
from .psparser import PSSyntaxError
from .psparser import PSEOF
from .psparser import PSLiteral
from .psparser import literal_name
from .psparser import KWD
from .encodingdb import name2unicode
from .utils import choplist
from .utils import nunpack
log = logging.getLogger(__name__)
class CMapError(Exception):
pass
class CMapBase:
debug = 0
def __init__(self, **kwargs):
self.attrs = kwargs.copy()
return
def is_vertical(self):
return self.attrs.get('WMode', 0) != 0
def set_attr(self, k, v):
self.attrs[k] = v
return
def add_code2cid(self, code, cid):
return
def add_cid2unichr(self, cid, code):
return
def use_cmap(self, cmap):
return
class CMap(CMapBase):
def __init__(self, **kwargs):
CMapBase.__init__(self, **kwargs)
self.code2cid = {}
return
def __repr__(self):
return '<CMap: %s>' % self.attrs.get('CMapName')
def use_cmap(self, cmap):
assert isinstance(cmap, CMap), str(type(cmap))
def copy(dst, src):
for (k, v) in src.items():
if isinstance(v, dict):
d = {}
dst[k] = d
copy(d, v)
else:
dst[k] = v
copy(self.code2cid, cmap.code2cid)
return
def decode(self, code):
log.debug('decode: %r, %r', self, code)
d = self.code2cid
for i in iter(code):
if i in d:
d = d[i]
if isinstance(d, int):
yield d
d = self.code2cid
else:
d = self.code2cid
return
def dump(self, out=sys.stdout, code2cid=None, code=None):
if code2cid is None:
code2cid = self.code2cid
code = ()
for (k, v) in sorted(code2cid.items()):
c = code+(k,)
if isinstance(v, int):
out.write('code %r = cid %d\n' % (c, v))
else:
self.dump(out=out, code2cid=v, code=c)
return
class IdentityCMap(CMapBase):
def decode(self, code):
n = len(code)//2
if n:
return struct.unpack('>%dH' % n, code)
else:
return ()
class IdentityCMapByte(IdentityCMap):
def decode(self, code):
n = len(code)
if n:
return struct.unpack('>%dB' % n, code)
else:
return ()
class UnicodeMap(CMapBase):
def __init__(self, **kwargs):
CMapBase.__init__(self, **kwargs)
self.cid2unichr = {}
return
def __repr__(self):
return '<UnicodeMap: %s>' % self.attrs.get('CMapName')
def get_unichr(self, cid):
log.debug('get_unichr: %r, %r', self, cid)
return self.cid2unichr[cid]
def dump(self, out=sys.stdout):
for (k, v) in sorted(self.cid2unichr.items()):
out.write('cid %d = unicode %r\n' % (k, v))
return
class FileCMap(CMap):
def add_code2cid(self, code, cid):
assert isinstance(code, str) and isinstance(cid, int),\
str((type(code), type(cid)))
d = self.code2cid
for c in code[:-1]:
c = ord(c)
if c in d:
d = d[c]
else:
t = {}
d[c] = t
d = t
c = ord(code[-1])
d[c] = cid
return
class FileUnicodeMap(UnicodeMap):
def add_cid2unichr(self, cid, code):
assert isinstance(cid, int), str(type(cid))
if isinstance(code, PSLiteral):
# Interpret as an Adobe glyph name.
self.cid2unichr[cid] = name2unicode(code.name)
elif isinstance(code, bytes):
# Interpret as UTF-16BE.
self.cid2unichr[cid] = code.decode('UTF-16BE', 'ignore')
elif isinstance(code, int):
self.cid2unichr[cid] = chr(code)
else:
raise TypeError(code)
return
class PyCMap(CMap):
def __init__(self, name, module):
CMap.__init__(self, CMapName=name)
self.code2cid = module.CODE2CID
if module.IS_VERTICAL:
self.attrs['WMode'] = 1
return
class PyUnicodeMap(UnicodeMap):
def __init__(self, name, module, vertical):
UnicodeMap.__init__(self, CMapName=name)
if vertical:
self.cid2unichr = module.CID2UNICHR_V
self.attrs['WMode'] = 1
else:
self.cid2unichr = module.CID2UNICHR_H
return
class CMapDB:
_cmap_cache = {}
_umap_cache = {}
class CMapNotFound(CMapError):
pass
@classmethod
def _load_data(cls, name):
name = name.replace("\0", "")
filename = '%s.pickle.gz' % name
log.info('loading: %r', name)
cmap_paths = (os.environ.get('CMAP_PATH', '/usr/share/pdfminer/'),
os.path.join(os.path.dirname(__file__), 'cmap'),)
for directory in cmap_paths:
path = os.path.join(directory, filename)
if os.path.exists(path):
gzfile = gzip.open(path)
try:
return type(str(name), (), pickle.loads(gzfile.read()))
finally:
gzfile.close()
else:
raise CMapDB.CMapNotFound(name)
@classmethod
def get_cmap(cls, name):
if name == 'Identity-H':
return IdentityCMap(WMode=0)
elif name == 'Identity-V':
return IdentityCMap(WMode=1)
elif name == 'OneByteIdentityH':
return IdentityCMapByte(WMode=0)
elif name == 'OneByteIdentityV':
return IdentityCMapByte(WMode=1)
try:
return cls._cmap_cache[name]
except KeyError:
pass
data = cls._load_data(name)
cls._cmap_cache[name] = cmap = PyCMap(name, data)
return cmap
@classmethod
def get_unicode_map(cls, name, vertical=False):
try:
return cls._umap_cache[name][vertical]
except KeyError:
pass
data = cls._load_data('to-unicode-%s' % name)
cls._umap_cache[name] = [PyUnicodeMap(name, data, v)
for v in (False, True)]
return cls._umap_cache[name][vertical]
class CMapParser(PSStackParser):
def __init__(self, cmap, fp):
PSStackParser.__init__(self, fp)
self.cmap = cmap
# some ToUnicode maps don't have "begincmap" keyword.
self._in_cmap = True
return
def run(self):
try:
self.nextobject()
except PSEOF:
pass
return
KEYWORD_BEGINCMAP = KWD(b'begincmap')
KEYWORD_ENDCMAP = KWD(b'endcmap')
KEYWORD_USECMAP = KWD(b'usecmap')
KEYWORD_DEF = KWD(b'def')
KEYWORD_BEGINCODESPACERANGE = KWD(b'begincodespacerange')
KEYWORD_ENDCODESPACERANGE = KWD(b'endcodespacerange')
KEYWORD_BEGINCIDRANGE = KWD(b'begincidrange')
KEYWORD_ENDCIDRANGE = KWD(b'endcidrange')
KEYWORD_BEGINCIDCHAR = KWD(b'begincidchar')
KEYWORD_ENDCIDCHAR = KWD(b'endcidchar')
KEYWORD_BEGINBFRANGE = KWD(b'beginbfrange')
KEYWORD_ENDBFRANGE = KWD(b'endbfrange')
KEYWORD_BEGINBFCHAR = KWD(b'beginbfchar')
KEYWORD_ENDBFCHAR = KWD(b'endbfchar')
KEYWORD_BEGINNOTDEFRANGE = KWD(b'beginnotdefrange')
KEYWORD_ENDNOTDEFRANGE = KWD(b'endnotdefrange')
def do_keyword(self, pos, token):
if token is self.KEYWORD_BEGINCMAP:
self._in_cmap = True
self.popall()
return
elif token is self.KEYWORD_ENDCMAP:
self._in_cmap = False
return
if not self._in_cmap:
return
#
if token is self.KEYWORD_DEF:
try:
((_, k), (_, v)) = self.pop(2)
self.cmap.set_attr(literal_name(k), v)
except PSSyntaxError:
pass
return
if token is self.KEYWORD_USECMAP:
try:
((_, cmapname),) = self.pop(1)
self.cmap.use_cmap(CMapDB.get_cmap(literal_name(cmapname)))
except PSSyntaxError:
pass
except CMapDB.CMapNotFound:
pass
return
if token is self.KEYWORD_BEGINCODESPACERANGE:
self.popall()
return
if token is self.KEYWORD_ENDCODESPACERANGE:
self.popall()
return
if token is self.KEYWORD_BEGINCIDRANGE:
self.popall()
return
if token is self.KEYWORD_ENDCIDRANGE:
objs = [obj for (__, obj) in self.popall()]
for (s, e, cid) in choplist(3, objs):
if (not isinstance(s, str) or not isinstance(e, str) or
not isinstance(cid, int) or len(s) != len(e)):
continue
sprefix = s[:-4]
eprefix = e[:-4]
if sprefix != eprefix:
continue
svar = s[-4:]
evar = e[-4:]
s1 = nunpack(svar)
e1 = nunpack(evar)
vlen = len(svar)
for i in range(e1-s1+1):
x = sprefix+struct.pack('>L', s1+i)[-vlen:]
self.cmap.add_code2cid(x, cid+i)
return
if token is self.KEYWORD_BEGINCIDCHAR:
self.popall()
return
if token is self.KEYWORD_ENDCIDCHAR:
objs = [obj for (__, obj) in self.popall()]
for (cid, code) in choplist(2, objs):
if isinstance(code, str) and isinstance(cid, str):
self.cmap.add_code2cid(code, nunpack(cid))
return
if token is self.KEYWORD_BEGINBFRANGE:
self.popall()
return
if token is self.KEYWORD_ENDBFRANGE:
objs = [obj for (__, obj) in self.popall()]
for (s, e, code) in choplist(3, objs):
if (not isinstance(s, bytes) or not isinstance(e, bytes) or
len(s) != len(e)):
continue
s1 = nunpack(s)
e1 = nunpack(e)
if isinstance(code, list):
for i in range(e1-s1+1):
self.cmap.add_cid2unichr(s1+i, code[i])
else:
var = code[-4:]
base = nunpack(var)
prefix = code[:-4]
vlen = len(var)
for i in range(e1-s1+1):
x = prefix+struct.pack('>L', base+i)[-vlen:]
self.cmap.add_cid2unichr(s1+i, x)
return
if token is self.KEYWORD_BEGINBFCHAR:
self.popall()
return
if token is self.KEYWORD_ENDBFCHAR:
objs = [obj for (__, obj) in self.popall()]
for (cid, code) in choplist(2, objs):
if isinstance(cid, bytes) and isinstance(code, bytes):
self.cmap.add_cid2unichr(nunpack(cid), code)
return
if token is self.KEYWORD_BEGINNOTDEFRANGE:
self.popall()
return
if token is self.KEYWORD_ENDNOTDEFRANGE:
self.popall()
return
self.push((pos, token))
return
def main(argv):
args = argv[1:]
for fname in args:
fp = open(fname, 'rb')
cmap = FileUnicodeMap()
CMapParser(cmap, fp).run()
fp.close()
cmap.dump()
return
if __name__ == '__main__':
sys.exit(main(sys.argv))
| {
"repo_name": "goulu/pdfminer",
"path": "pdfminer/cmapdb.py",
"copies": "2",
"size": "12074",
"license": "mit",
"hash": 5952792654249603000,
"line_mean": 27.4094117647,
"line_max": 75,
"alpha_frac": 0.5185522611,
"autogenerated": false,
"ratio": 3.6488365064974313,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5167388767597432,
"avg_score": null,
"num_lines": null
} |
"""A docker-based mininet host"""
import json
import operator
import os
import pty
import select
from subprocess import PIPE, STDOUT
from functools import reduce
# pylint: disable=import-error
# pylint: disable=no-name-in-module
from mininet.log import error, debug
from mininet.node import Host
from mininet.util import quietRun, errRun
from clib.mininet_test_util import DEVNULL
DEFAULT_NETWORK = 'none'
DEFAULT_PREFIX = 'mininet'
STARTUP_TIMEOUT_MS = 20000
# pylint: disable=too-many-instance-attributes
class DockerHost(Host):
"""Mininet host that encapsulates execution in a docker container"""
master = None
shell = None
slave = None
name = None
inNamespace = None
pollOut = None
stdout = None
execed = None
lastCmd = None # pylint: disable=invalid-name
readbuf = None
lastPid = None
pid = None
waiting = None
stdin = None
active_pipe = None
active_pipe_returncode = None
image = None
tmpdir = None
env_vars = None
vol_maps = None
prefix = None
startup_timeout_ms = None
container = None
pollIn = None
active_log = None
ps1 = chr(127)
# pylint: disable=too-many-arguments
def __init__(self, name, image=None, tmpdir=None, prefix=None, env_vars=None, vol_maps=None,
startup_timeout_ms=STARTUP_TIMEOUT_MS, network=None, **kwargs):
self.image = image
self.tmpdir = tmpdir
self.prefix = prefix
if env_vars is None:
env_vars = []
self.env_vars = env_vars
if vol_maps is None:
vol_maps = []
self.vol_maps = vol_maps
self.network = network
self.startup_timeout_ms = startup_timeout_ms
self.name = name
self.pullImage()
Host.__init__(self, name, **kwargs)
def pullImage(self): # pylint: disable=invalid-name
"Pull docker image if necessary"
if self.image not in quietRun('docker images'):
error('%s: docker image' % self.name, self.image,
'not available locally - pulling\n')
_out, err, code = errRun('docker', 'pull', self.image)
if err or code:
error('docker pull failed with error', code, err, '\n')
# pylint: disable=invalid-name
def startShell(self, mnopts=None):
"""Start a shell process for running commands."""
if self.shell:
error('shell is already running')
return
assert mnopts is None, 'mnopts not supported for DockerHost'
self.container = '%s-%s' % (self.prefix, self.name)
debug('Starting container %s with image "%s".' % (self.container, self.image))
self.kill(purge=True)
container_tmp_dir = os.path.join(os.path.abspath(self.tmpdir), 'tmp')
tmp_volume = container_tmp_dir + ':/tmp'
base_cmd = ["docker", "run", "-ti", "--privileged", "--entrypoint", "env",
"-h", self.name, "--name", self.container]
opt_args = ['--net=%s' % self.network]
env_vars = self.env_vars + ["TERM=dumb", "PS1=%s" % self.ps1]
env_args = reduce(operator.add, (['--env', var] for var in env_vars), [])
vol_args = reduce(operator.add, (['-v', var] for var in self.vol_maps), ['-v', tmp_volume])
image_args = [self.image, "bash", "--norc", "-is", "mininet:" + self.name]
cmd = base_cmd + opt_args + env_args + vol_args + image_args
self.master, self.slave = pty.openpty()
debug('docker command "%s", fd %d, fd %d' % (' '.join(cmd), self.master, self.slave))
try:
self.shell = self._popen(cmd, stdin=self.slave, stdout=self.slave, stderr=self.slave)
self.stdin = os.fdopen(self.master, 'r')
self.stdout = self.stdin
self.pollOut = select.poll() # pylint: disable=invalid-name
self.pollOut.register(self.stdout) # pylint: disable=no-member
self.outToNode[self.stdout.fileno()] = self # pylint: disable=no-member
self.pollIn = select.poll() # pylint: disable=invalid-name
self.pollIn.register(self.stdout, select.POLLIN) # pylint: disable=no-member
self.inToNode[self.stdin.fileno()] = self # pylint: disable=no-member
self.execed = False
self.lastCmd = None # pylint: disable=invalid-name
self.lastPid = None # pylint: disable=invalid-name
self.readbuf = ''
self.waiting = True
data = ''
while True:
data = self.read(maxbytes=1)
if data[-1] == self.ps1:
break
self.readbuf = ''
self.waiting = False
except:
error('docker cmd: %s' % ' '.join(cmd))
if self.shell.returncode:
error('returncode: %d' % self.shell.returncode)
if self.shell:
self.shell.poll()
raise
self.pid = self.inspect_pid()
debug("Container %s created pid %s/%s." % (self.container, self.pid, self.shell.pid))
self.cmd('unset HISTFILE; stty -echo; set +m') # pylint: disable=no-member
def kill(self, purge=False):
"""Kill a container."""
debug('killing container %s.' % self.container)
if purge:
kill_cmd = ["docker", "rm", "-f", self.container]
else:
kill_cmd = ["docker", "kill", self.container]
kill_pipe = None
try:
kill_pipe = self._popen(kill_cmd, stdin=DEVNULL, stdout=PIPE, stderr=STDOUT)
kill_pipe.stdout.readlines()
kill_pipe.stdout.close()
except:
if kill_pipe:
kill_pipe.poll()
raise
def inspect_pid(self):
"""Return container PID."""
pid_pipe = None
try:
pid_cmd = ["docker", "inspect", "--format={{ .State.Pid }}", self.container]
pid_pipe = self._popen(pid_cmd, stdin=DEVNULL, stdout=PIPE, stderr=STDOUT)
ps_out = pid_pipe.stdout.readlines()
pid_pipe.stdout.close()
return int(ps_out[0])
except:
if pid_pipe is not None:
pid_pipe.poll()
raise
def open_log(self, log_name='activate.log'):
"""Open a log file for writing and return it."""
return open(os.path.join(self.tmpdir, log_name), 'w')
def activate(self, log_name='activate.log'):
"""Active a container and return STDOUT to it."""
assert not self.active_pipe, 'container %s already activated' % self.container
debug('activating container %s.' % self.container)
inspect_cmd = ["docker", "inspect", "--format={{json .Config}}", self.image]
inspect_pipe = None
try:
inspect_pipe = self._popen(inspect_cmd, stdin=DEVNULL, stdout=PIPE, stderr=STDOUT)
config_json = inspect_pipe.stdout.readlines()
inspect_pipe.stdout.close()
assert len(config_json) == 1, "Expected 1 config line, found %s" % len(config_json)
config = json.loads(config_json[0].decode())
entryconfig = config['Entrypoint']
entrypoint = entryconfig if entryconfig else ['/usr/bin/env']
cmd = config['Cmd'] if 'Cmd' in config else []
docker_cmd = entrypoint + (cmd if cmd else [])
debug('logging to %s for %s' % (log_name, docker_cmd))
if log_name:
stdout = self.open_log(log_name)
self.active_log = stdout
else:
stdout = PIPE
self.active_log = None
except:
if inspect_pipe:
inspect_pipe.poll()
raise
self.active_pipe_returncode = None
self.active_pipe = self.popen(docker_cmd, stdin=DEVNULL, stdout=stdout, stderr=STDOUT)
pipe_out = self.active_pipe.stdout
out_fd = pipe_out.fileno() if pipe_out else None
debug('Active_pipe container %s pid %s fd %s' %
(self.container, self.active_pipe.pid, out_fd))
return self.active_pipe
def wait(self):
"""Wait for an activated container to terminate."""
try:
if self.active_pipe_returncode is not None:
return self.active_pipe_returncode
debug('Waiting for container %s.' % self.container)
assert self.active_pipe, "container not activated"
self.active_pipe.communicate()
self.active_pipe.returncode = self.active_pipe.wait()
self.terminate()
return self.active_pipe_returncode
except Exception as err:
error('Exception waiting for %s: %s' % (self.container, err))
self.terminate()
raise
def read(self, maxbytes=1024):
"""Read from an activated container."""
poll_results = self.pollIn.poll(self.startup_timeout_ms)
data_ready = poll_results and (poll_results[0][1] & select.POLLIN)
assert data_ready, (
'Timeout waiting for read data on %d after %ds' %
(self.stdout.fileno(), self.startup_timeout_ms / 1e3))
return Host.read(self, maxbytes)
def terminate(self):
"""Override Mininet terminate() to partially avoid pty leak."""
debug('Terminating container %s, shell %s, pipe %s' % (
self.container, self.shell, self.active_pipe))
if self.slave:
os.close(self.slave)
self.slave = None
if self.shell is not None:
self.stdin.close()
self.stdin = None
self.master = None
if self.shell.returncode is None:
self.shell.kill()
self.shell.poll()
self.kill()
self.shell = None
if self.active_pipe:
if self.active_pipe.stdout:
self.active_pipe.stdout.close()
if self.active_pipe.returncode is None:
self.active_pipe.kill()
self.active_pipe.poll()
self.active_pipe_returncode = self.active_pipe.returncode
self.active_pipe = None
if self.active_log:
self.active_log.close()
self.active_log = None
self.cleanup() # pylint: disable=no-member
return self.active_pipe_returncode
def popen(self, *args, **kwargs):
"""Return a Popen() object in node's namespace
args: Popen() args, single list, or string
kwargs: Popen() keyword args"""
# -t is necessary to prevent docker from buffering output. It might cause
# problems with some commands like shells that then assume they can output
# all sorts of crazy control characters b/c it's a terminal.
mncmd = ['docker', 'exec', '--env', 'TERM=dumb', '-t', self.container]
pipe = Host.popen(self, mncmd=mncmd, *args, **kwargs)
if pipe:
debug('docker pid %d: %s %s %s' % (pipe.pid, mncmd, args, kwargs))
return pipe
def _popen(self, cmd, **params):
# Docker is different than mininet in that it doesn't handle signals like
# a normal interactive terminal would. So, put it in a separate process group
# so it doesn't receive stray SIGINTs, rather relying on the message sent
# from the owning process through the pty.
if 'preexec_fn' not in params:
params['preexec_fn'] = os.setpgrp
pipe = super(DockerHost, self)._popen(cmd, **params)
if pipe:
stdout = pipe.stdout
out_fd = pipe.stdout.fileno() if stdout else None
debug('docker pid %d: %s, fd %s' % (pipe.pid, cmd, out_fd))
return pipe
def make_docker_host(image, prefix=DEFAULT_PREFIX, network=DEFAULT_NETWORK,
startup_timeout_ms=None):
"""Utility function to create a docker-host class that can be passed to mininet"""
class _ImageHost(DockerHost):
"""Internal class that represents a docker image host"""
def __init__(self, *args, **kwargs):
host_name = args[0]
kwargs['image'] = image
assert kwargs['tmpdir'], 'tmpdir required for docker host'
kwargs['tmpdir'] = os.path.join(kwargs['tmpdir'], host_name)
kwargs['prefix'] = prefix
kwargs['network'] = network
if startup_timeout_ms:
kwargs['startup_timeout_ms'] = startup_timeout_ms
elif 'DOCKER_STARTUP_TIMEOUT_MS' in os.environ:
env_val = os.environ['DOCKER_STARTUP_TIMEOUT_MS']
if env_val:
kwargs['startup_timeout_ms'] = int(env_val)
super(_ImageHost, self).__init__(*args, **kwargs)
return _ImageHost
| {
"repo_name": "REANNZ/faucet",
"path": "clib/docker_host.py",
"copies": "3",
"size": "12807",
"license": "apache-2.0",
"hash": -5206338485011086000,
"line_mean": 39.2735849057,
"line_max": 99,
"alpha_frac": 0.5740610604,
"autogenerated": false,
"ratio": 3.9406153846153846,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0024821509767538135,
"num_lines": 318
} |
"""A document represents the state of an editing document."""
from .selection import Selection, Interval
from .event import Event
from . import commands
from .userinterface import UserInterfaceAPI
from .navigation import center_around_selection, is_position_visible
from .selecting import SelectModes
from .mode import Mode
from logging import error, info, debug
documentlist = []
activedocument = None
class Namespace:
"""
Allow easy namespacing within attributes of an object.
"""
pass
class Document:
"""Contains all objects of one file editing document"""
OnDocumentInit = Event('OnDocumentInit')
OnModeInit = Event('OnModeInit')
create_userinterface = None
_text = ''
_mode = None
expandtab = False
tabwidth = 4
autoindent = True
locked_selection = None
saved = True
def __init__(self, filename=''):
documentlist.append(self)
self.OnTextChanged = Event('OnTextChanged')
self.OnRead = Event('OnRead')
self.OnWrite = Event('OnWrite')
self.OnQuit = Event('OnQuit')
self.OnActivate = Event('OnActivate')
self.OnSelectionChange = Event('OnSelectionChange')
self.filename = filename
if filename:
try:
with open(filename, 'r') as fd:
self._text = fd.read()
except (FileNotFoundError, PermissionError) as e:
error(str(e))
self._selection = Selection(Interval(0, 0))
self.selectmode = SelectModes.normal
if not self.create_userinterface:
raise Exception('No function specified in Document.create_userinterface.')
self.ui = self.create_userinterface(self)
if not isinstance(self.ui, UserInterfaceAPI):
raise Exception('document.ui not an instance of UserInterface.')
self.modes = Namespace()
self.OnModeInit.fire(self)
self.mode = self.modes.normalmode
self.OnDocumentInit.fire(self)
self.OnRead.fire(self)
self.OnTextChanged.fire(self)
def quit(self):
"""Quit document."""
info('Quitting document ' + str(self))
self.OnQuit.fire(self)
global activedocument
index = documentlist.index(self)
if len(documentlist) == 1:
info('Closing the last document by setting activedocument to None')
activedocument = None
return
if index < len(documentlist) - 1:
nextdoc = documentlist[index + 1]
else:
nextdoc = documentlist[index - 1]
nextdoc.activate()
documentlist.remove(self)
def activate(self):
"""Activate this document."""
global activedocument
activedocument = self
self.OnActivate.fire(self)
@property
def mode(self):
return self._mode
@mode.setter
def mode(self, value):
if not isinstance(value, Mode):
raise ValueError('Object {} is not an instance of Mode'.format(value))
self._mode = value
@property
def text(self):
return self._text
@text.setter
def text(self, value):
self._text = value
self.saved = False
self.OnTextChanged.fire(self)
@property
def selection(self):
return self._selection
@selection.setter
def selection(self, value):
if not isinstance(value, Selection):
raise ValueError('Object {} is not an instance of Selection'.format(value))
value.validate(self)
self._selection = value
# Update the userinterface viewport to center around first interval
if not is_position_visible(self, self._selection[-1][1]):
center_around_selection(self)
self.OnSelectionChange.fire(self)
def processinput(self, userinput):
"""This method is called when this document receives userinput."""
if userinput == 'ctrl-\\':
raise KeyboardInterrupt
debug('Mode:' + repr(self.mode))
debug('Input: ' + repr(userinput))
self.mode.processinput(self, userinput)
def next_document(doc):
"""Go to the next document."""
index = documentlist.index(doc)
ndoc = documentlist[(index + 1) % len(documentlist)]
ndoc.activate()
commands.next_document = next_document
def previous_document(doc):
"""Go to the previous document."""
index = documentlist.index(doc)
ndoc = documentlist[(index - 1) % len(documentlist)]
ndoc.activate()
commands.previous_document = previous_document
def goto_document(index):
"""Command constructor to go to the document at given index."""
def wrapper(doc):
documentlist[index].activate()
return wrapper
| {
"repo_name": "Chiel92/fate",
"path": "fate/document.py",
"copies": "1",
"size": "4752",
"license": "mit",
"hash": 7901924875367560000,
"line_mean": 27.4550898204,
"line_max": 87,
"alpha_frac": 0.6294191919,
"autogenerated": false,
"ratio": 4.258064516129032,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0006610486944037064,
"num_lines": 167
} |
"""adodbapi.apibase - A python DB API 2.0 (PEP 249) interface to Microsoft ADO
Copyright (C) 2002 Henrik Ekelund, version 2.1 by Vernon Cole
* http://sourceforge.net/projects/pywin32
* http://sourceforge.net/projects/adodbapi
"""
import sys
import time
import datetime
import decimal
import numbers
# noinspection PyUnresolvedReferences
from . import ado_consts as adc
verbose = False # debugging flag
onIronPython = sys.platform == 'cli'
if onIronPython: # we need type definitions for odd data we may need to convert
# noinspection PyUnresolvedReferences
from System import DBNull, DateTime
NullTypes = (type(None), DBNull)
else:
DateTime = type(NotImplemented) # should never be seen on win32
NullTypes = type(None)
# --- define objects to smooth out Python3 <-> Python 2.x differences
unicodeType = str #this line will be altered by 2to3.py to '= str'
longType = int #this line will be altered by 2to3.py to '= int'
if sys.version[0] >= '3': #python 3.x
StringTypes = str
makeByteBuffer = bytes
memoryViewType = memoryview
_BaseException = Exception
else: #python 2.x
# noinspection PyUnresolvedReferences
from exceptions import Exception as _BaseException
memoryViewType = type(buffer(''))
makeByteBuffer = buffer
StringTypes = (str,str) # will be messed up by 2to3 but never used
try: #jdhardy -- handle bytes under IronPython & Py3
bytes
except NameError:
bytes = str # define it for old Pythons
# ------- Error handlers ------
def standardErrorHandler(connection, cursor, errorclass, errorvalue):
err = (errorclass, errorvalue)
try:
connection.messages.append(err)
except: pass
if cursor is not None:
try:
cursor.messages.append(err)
except: pass
raise errorclass(errorvalue)
# Note: _BaseException is defined differently between Python 2.x and 3.x
class Error(_BaseException):
pass #Exception that is the base class of all other error
#exceptions. You can use this to catch all errors with one
#single 'except' statement. Warnings are not considered
#errors and thus should not use this class as base. It must
#be a subclass of the Python StandardError (defined in the
#module exceptions).
class Warning(_BaseException):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
class InternalError(DatabaseError):
pass
class OperationalError(DatabaseError):
pass
class ProgrammingError(DatabaseError):
pass
class IntegrityError(DatabaseError):
pass
class DataError(DatabaseError):
pass
class NotSupportedError(DatabaseError):
pass
class FetchFailedError(OperationalError):
"""
Error is used by RawStoredProcedureQuerySet to determine when a fetch
failed due to a connection being closed or there is no record set
returned. (Non-standard, added especially for django)
"""
pass
# # # # # ----- Type Objects and Constructors ----- # # # # #
#Many databases need to have the input in a particular format for binding to an operation's input parameters.
#For example, if an input is destined for a DATE column, then it must be bound to the database in a particular
#string format. Similar problems exist for "Row ID" columns or large binary items (e.g. blobs or RAW columns).
#This presents problems for Python since the parameters to the executeXXX() method are untyped.
#When the database module sees a Python string object, it doesn't know if it should be bound as a simple CHAR
#column, as a raw BINARY item, or as a DATE.
#
#To overcome this problem, a module must provide the constructors defined below to create objects that can
#hold special values. When passed to the cursor methods, the module can then detect the proper type of
#the input parameter and bind it accordingly.
#A Cursor Object's description attribute returns information about each of the result columns of a query.
#The type_code must compare equal to one of Type Objects defined below. Type Objects may be equal to more than
#one type code (e.g. DATETIME could be equal to the type codes for date, time and timestamp columns;
#see the Implementation Hints below for details).
#SQL NULL values are represented by the Python None singleton on input and output.
#Note: Usage of Unix ticks for database interfacing can cause troubles because of the limited date range they cover.
# def Date(year,month,day):
# "This function constructs an object holding a date value. "
# return dateconverter.date(year,month,day) #dateconverter.Date(year,month,day)
#
# def Time(hour,minute,second):
# "This function constructs an object holding a time value. "
# return dateconverter.time(hour, minute, second) # dateconverter.Time(hour,minute,second)
#
# def Timestamp(year,month,day,hour,minute,second):
# "This function constructs an object holding a time stamp value. "
# return dateconverter.datetime(year,month,day,hour,minute,second)
#
# def DateFromTicks(ticks):
# """This function constructs an object holding a date value from the given ticks value
# (number of seconds since the epoch; see the documentation of the standard Python time module for details). """
# return Date(*time.gmtime(ticks)[:3])
#
# def TimeFromTicks(ticks):
# """This function constructs an object holding a time value from the given ticks value
# (number of seconds since the epoch; see the documentation of the standard Python time module for details). """
# return Time(*time.gmtime(ticks)[3:6])
#
# def TimestampFromTicks(ticks):
# """This function constructs an object holding a time stamp value from the given
# ticks value (number of seconds since the epoch;
# see the documentation of the standard Python time module for details). """
# return Timestamp(*time.gmtime(ticks)[:6])
#
# def Binary(aString):
# """This function constructs an object capable of holding a binary (long) string value. """
# b = makeByteBuffer(aString)
# return b
# ----- Time converters ----------------------------------------------
class TimeConverter(object): # this is a generic time converter skeleton
def __init__(self): # the details will be filled in by instances
self._ordinal_1899_12_31=datetime.date(1899,12,31).toordinal()-1
# Use cls.types to compare if an input parameter is a datetime
self.types = {type(self.Date(2000,1,1)),
type(self.Time(12,1,1)),
type(self.Timestamp(2000,1,1,12,1,1)),
datetime.datetime,
datetime.time,
datetime.date}
def COMDate(self,obj):
'''Returns a ComDate from a date-time'''
try: # most likely a datetime
tt=obj.timetuple()
try:
ms=obj.microsecond
except:
ms=0
return self.ComDateFromTuple(tt, ms)
except: # might be a tuple
try:
return self.ComDateFromTuple(obj)
except: # try an mxdate
try:
return obj.COMDate()
except:
raise ValueError('Cannot convert "%s" to COMdate.' % repr(obj))
def ComDateFromTuple(self, t, microseconds=0):
d = datetime.date(t[0],t[1],t[2])
integerPart = d.toordinal() - self._ordinal_1899_12_31
ms = (t[3]*3600 + t[4]*60 + t[5]) * 1000000 + microseconds
fractPart = float(ms) / 86400000000.0
return integerPart + fractPart
def DateObjectFromCOMDate(self,comDate):
'Returns an object of the wanted type from a ComDate'
raise NotImplementedError #"Abstract class"
def Date(self,year,month,day):
"This function constructs an object holding a date value. "
raise NotImplementedError #"Abstract class"
def Time(self,hour,minute,second):
"This function constructs an object holding a time value. "
raise NotImplementedError #"Abstract class"
def Timestamp(self,year,month,day,hour,minute,second):
"This function constructs an object holding a time stamp value. "
raise NotImplementedError #"Abstract class"
# all purpose date to ISO format converter
def DateObjectToIsoFormatString(self, obj):
"This function should return a string in the format 'YYYY-MM-dd HH:MM:SS:ms' (ms optional) "
try: # most likely, a datetime.datetime
s = obj.isoformat(' ')
except (TypeError, AttributeError):
if isinstance(obj, datetime.date):
s = obj.isoformat() + ' 00:00:00' # return exact midnight
else:
try: # maybe it has a strftime method, like mx
s = obj.strftime('%Y-%m-%d %H:%M:%S')
except AttributeError:
try: #but may be time.struct_time
s = time.strftime('%Y-%m-%d %H:%M:%S', obj)
except:
raise ValueError('Cannot convert "%s" to isoformat' % repr(obj))
return s
# -- Optional: if mx extensions are installed you may use mxDateTime ----
try:
import mx.DateTime
mxDateTime = True
except:
mxDateTime = False
if mxDateTime:
class mxDateTimeConverter(TimeConverter): # used optionally if installed
def __init__(self):
TimeConverter.__init__(self)
self.types.add(type(mx.DateTime))
def DateObjectFromCOMDate(self,comDate):
return mx.DateTime.DateTimeFromCOMDate(comDate)
def Date(self,year,month,day):
return mx.DateTime.Date(year,month,day)
def Time(self,hour,minute,second):
return mx.DateTime.Time(hour,minute,second)
def Timestamp(self,year,month,day,hour,minute,second):
return mx.DateTime.Timestamp(year,month,day,hour,minute,second)
else:
class mxDateTimeConverter(TimeConverter):
pass # if no mx is installed
class pythonDateTimeConverter(TimeConverter): # standard since Python 2.3
def __init__(self):
TimeConverter.__init__(self)
def DateObjectFromCOMDate(self, comDate):
if isinstance(comDate, datetime.datetime):
odn = comDate.toordinal()
tim = comDate.time()
new = datetime.datetime.combine(datetime.datetime.fromordinal(odn), tim)
return new
# return comDate.replace(tzinfo=None) # make non aware
elif isinstance(comDate, DateTime):
fComDate = comDate.ToOADate() # ironPython clr Date/Time
else:
fComDate=float(comDate) #ComDate is number of days since 1899-12-31
integerPart = int(fComDate)
floatpart=fComDate-integerPart
##if floatpart == 0.0:
## return datetime.date.fromordinal(integerPart + self._ordinal_1899_12_31)
dte=datetime.datetime.fromordinal(integerPart + self._ordinal_1899_12_31) \
+ datetime.timedelta(milliseconds=floatpart*86400000)
# millisecondsperday=86400000 # 24*60*60*1000
return dte
def Date(self,year,month,day):
return datetime.date(year,month,day)
def Time(self,hour,minute,second):
return datetime.time(hour,minute,second)
def Timestamp(self,year,month,day,hour,minute,second):
return datetime.datetime(year,month,day,hour,minute,second)
class pythonTimeConverter(TimeConverter): # the old, ?nix type date and time
def __init__(self): #caution: this Class gets confised by timezones and DST
TimeConverter.__init__(self)
self.types.add(time.struct_time)
def DateObjectFromCOMDate(self,comDate):
'Returns ticks since 1970'
if isinstance(comDate,datetime.datetime):
return comDate.timetuple()
elif isinstance(comDate, DateTime): # ironPython clr date/time
fcomDate = comDate.ToOADate()
else:
fcomDate = float(comDate)
secondsperday=86400 # 24*60*60
#ComDate is number of days since 1899-12-31, gmtime epoch is 1970-1-1 = 25569 days
t=time.gmtime(secondsperday*(fcomDate-25569.0))
return t #year,month,day,hour,minute,second,weekday,julianday,daylightsaving=t
def Date(self,year,month,day):
return self.Timestamp(year,month,day,0,0,0)
def Time(self,hour,minute,second):
return time.gmtime((hour*60+minute)*60 + second)
def Timestamp(self,year,month,day,hour,minute,second):
return time.localtime(time.mktime((year,month,day,hour,minute,second,0,0,-1)))
base_dateconverter = pythonDateTimeConverter()
# ------ DB API required module attributes ---------------------
threadsafety=1 # TODO -- find out whether this module is actually BETTER than 1.
apilevel='2.0' #String constant stating the supported DB API level.
paramstyle='qmark' # the default parameter style
# ------ control for an extension which may become part of DB API 3.0 ---
accepted_paramstyles = ('qmark', 'named', 'format', 'pyformat', 'dynamic')
#------------------------------------------------------------------------------------------
# define similar types for generic conversion routines
adoIntegerTypes=(adc.adInteger,adc.adSmallInt,adc.adTinyInt,adc.adUnsignedInt,
adc.adUnsignedSmallInt,adc.adUnsignedTinyInt,
adc.adBoolean,adc.adError) #max 32 bits
adoRowIdTypes=(adc.adChapter,) #v2.1 Rose
adoLongTypes=(adc.adBigInt,adc.adFileTime,adc.adUnsignedBigInt)
adoExactNumericTypes=(adc.adDecimal,adc.adNumeric,adc.adVarNumeric,adc.adCurrency) #v2.3 Cole
adoApproximateNumericTypes=(adc.adDouble,adc.adSingle) #v2.1 Cole
adoStringTypes=(adc.adBSTR,adc.adChar,adc.adLongVarChar,adc.adLongVarWChar,
adc.adVarChar,adc.adVarWChar,adc.adWChar)
adoBinaryTypes=(adc.adBinary,adc.adLongVarBinary,adc.adVarBinary)
adoDateTimeTypes=(adc.adDBTime, adc.adDBTimeStamp, adc.adDate, adc.adDBDate)
adoRemainingTypes=(adc.adEmpty,adc.adIDispatch,adc.adIUnknown,
adc.adPropVariant,adc.adArray,adc.adUserDefined,
adc.adVariant,adc.adGUID)
# this class is a trick to determine whether a type is a member of a related group of types. see PEP notes
class DBAPITypeObject(object):
def __init__(self,valuesTuple):
self.values = frozenset(valuesTuple)
def __eq__(self,other):
return other in self.values
def __ne__(self, other):
return other not in self.values
"""This type object is used to describe columns in a database that are string-based (e.g. CHAR). """
STRING = DBAPITypeObject(adoStringTypes)
"""This type object is used to describe (long) binary columns in a database (e.g. LONG, RAW, BLOBs). """
BINARY = DBAPITypeObject(adoBinaryTypes)
"""This type object is used to describe numeric columns in a database. """
NUMBER = DBAPITypeObject(adoIntegerTypes + adoLongTypes + \
adoExactNumericTypes + adoApproximateNumericTypes)
"""This type object is used to describe date/time columns in a database. """
DATETIME = DBAPITypeObject(adoDateTimeTypes)
"""This type object is used to describe the "Row ID" column in a database. """
ROWID = DBAPITypeObject(adoRowIdTypes)
OTHER = DBAPITypeObject(adoRemainingTypes)
# ------- utilities for translating python data types to ADO data types ---------------------------------
typeMap = { memoryViewType : adc.adVarBinary,
float : adc.adDouble,
type(None) : adc.adEmpty,
str : adc.adBSTR, # this line will be altered by 2to3 to 'str:'
bool :adc.adBoolean, #v2.1 Cole
decimal.Decimal : adc.adDecimal }
if longType != int: #not Python 3
typeMap[longType] = adc.adBigInt #works in python 2.x
typeMap[int] = adc.adInteger
typeMap[bytes] = adc.adBSTR # 2.x string type
else: #python 3.0 integrated integers
## Should this differentiate between an int that fits in a long and one that requires 64 bit datatype?
typeMap[int] = adc.adBigInt
typeMap[bytes] = adc.adVarBinary
def pyTypeToADOType(d):
tp=type(d)
try:
return typeMap[tp]
except KeyError: # The type was not defined in the pre-computed Type table
from . import dateconverter
if tp in dateconverter.types: # maybe it is one of our supported Date/Time types
return adc.adDate
# otherwise, attempt to discern the type by probing the data object itself -- to handle duck typing
if isinstance(d, StringTypes):
return adc.adBSTR
if isinstance(d, numbers.Integral):
return adc.adBigInt
if isinstance(d, numbers.Real):
return adc.adDouble
raise DataError('cannot convert "%s" (type=%s) to ADO'%(repr(d),tp))
# # # # # # # # # # # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# functions to convert database values to Python objects
#------------------------------------------------------------------------
# variant type : function converting variant to Python value
def variantConvertDate(v):
from . import dateconverter # this function only called when adodbapi is running
return dateconverter.DateObjectFromCOMDate(v)
def cvtString(variant): # use to get old action of adodbapi v1 if desired
if onIronPython:
try:
return variant.ToString()
except:
pass
return str(variant)
def cvtDecimal(variant): #better name
return _convertNumberWithCulture(variant, decimal.Decimal)
def cvtNumeric(variant): #older name - don't break old code
return cvtDecimal(variant)
def cvtFloat(variant):
return _convertNumberWithCulture(variant, float)
def _convertNumberWithCulture(variant, f):
try:
return f(variant)
except (ValueError,TypeError,decimal.InvalidOperation):
try:
europeVsUS = str(variant).replace(",",".")
return f(europeVsUS)
except (ValueError,TypeError,decimal.InvalidOperation): pass
def cvtInt(variant):
return int(variant)
def cvtLong(variant): # only important in old versions where long and int differ
return int(variant)
def cvtBuffer(variant):
return bytes(variant)
def cvtUnicode(variant):
return str(variant) # will be altered by 2to3 to 'str(variant)'
def identity(x): return x
def cvtUnusual(variant):
if verbose > 1:
sys.stderr.write('Conversion called for Unusual data=%s\n' % repr(variant))
if isinstance(variant, DateTime): # COMdate or System.Date
from .adodbapi import dateconverter # this will only be called when adodbapi is in use, and very rarely
return dateconverter.DateObjectFromCOMDate(variant)
return variant # cannot find conversion function -- just give the data to the user
def convert_to_python(variant, func): # convert DB value into Python value
if isinstance(variant, NullTypes): # IronPython Null or None
return None
return func(variant) # call the appropriate conversion function
class MultiMap(dict): #builds a dictionary from {(sequence,of,keys) : function}
"""A dictionary of ado.type : function -- but you can set multiple items by passing a sequence of keys"""
#useful for defining conversion functions for groups of similar data types.
def __init__(self, aDict):
for k, v in list(aDict.items()):
self[k] = v # we must call __setitem__
def __setitem__(self, adoType, cvtFn):
"set a single item, or a whole sequence of items"
try: # user passed us a sequence, set them individually
for type in adoType:
dict.__setitem__(self, type, cvtFn)
except TypeError: # a single value fails attempt to iterate
dict.__setitem__(self, adoType, cvtFn)
#initialize variantConversions dictionary used to convert SQL to Python
# this is the dictionary of default conversion functions, built by the class above.
# this becomes a class attribute for the Connection, and that attribute is used
# to build the list of column conversion functions for the Cursor
variantConversions = MultiMap( {
adoDateTimeTypes : variantConvertDate,
adoApproximateNumericTypes: cvtFloat,
adoExactNumericTypes: cvtDecimal, # use to force decimal rather than unicode
adoLongTypes : cvtLong,
adoIntegerTypes: cvtInt,
adoRowIdTypes: cvtInt,
adoStringTypes: identity,
adoBinaryTypes: cvtBuffer,
adoRemainingTypes: cvtUnusual })
# # # # # classes to emulate the result of cursor.fetchxxx() as a sequence of sequences # # # # #
# "an ENUM of how my low level records are laid out"
RS_WIN_32, RS_ARRAY, RS_REMOTE = list(range(1,4))
class SQLrow(object): # a single database row
# class to emulate a sequence, so that a column may be retrieved by either number or name
def __init__(self, rows, index): # "rows" is an _SQLrows object, index is which row
self.rows = rows # parent 'fetch' container object
self.index = index # my row number within parent
def __getattr__(self, name): # used for row.columnName type of value access
try:
return self._getValue(self.rows.columnNames[name.lower()])
except KeyError:
raise AttributeError('Unknown column name "{}"'.format(name))
def _getValue(self,key): # key must be an integer
if self.rows.recordset_format == RS_ARRAY: # retrieve from two-dimensional array
v = self.rows.ado_results[key,self.index]
elif self.rows.recordset_format == RS_REMOTE:
v = self.rows.ado_results[self.index][key]
else:# pywin32 - retrieve from tuple of tuples
v = self.rows.ado_results[key][self.index]
if self.rows.converters is NotImplemented:
return v
return convert_to_python(v, self.rows.converters[key])
def __len__(self):
return self.rows.numberOfColumns
def __getitem__(self,key): # used for row[key] type of value access
if isinstance(key,int): # normal row[1] designation
try:
return self._getValue(key)
except IndexError:
raise
if isinstance(key, slice):
indices = key.indices(self.rows.numberOfColumns)
vl = [self._getValue(i) for i in range(*indices)]
return tuple(vl)
try:
return self._getValue(self.rows.columnNames[key.lower()]) # extension row[columnName] designation
except (KeyError, TypeError):
er, st, tr = sys.exc_info()
raise er('No such key as "%s" in %s'%(repr(key),self.__repr__())).with_traceback(tr)
def __iter__(self):
return iter(self.__next__())
def __next__(self):
for n in range(self.rows.numberOfColumns):
yield self._getValue(n)
def __repr__(self): # create a human readable representation
taglist = sorted(list(self.rows.columnNames.items()), key=lambda x: x[1])
s = "<SQLrow={"
for name, i in taglist:
s += name + ':' + repr(self._getValue(i)) + ', '
return s[:-2] + '}>'
def __str__(self): # create a pretty human readable representation
return str(tuple(str(self._getValue(i)) for i in range(self.rows.numberOfColumns)))
# TO-DO implement pickling an SQLrow directly
#def __getstate__(self): return self.__dict__
#def __setstate__(self, d): self.__dict__.update(d)
# which basically tell pickle to treat your class just like a normal one,
# taking self.__dict__ as representing the whole of the instance state,
# despite the existence of the __getattr__.
# # # #
class SQLrows(object):
# class to emulate a sequence for multiple rows using a container object
def __init__(self, ado_results, numberOfRows, cursor):
self.ado_results = ado_results # raw result of SQL get
try:
self.recordset_format = cursor.recordset_format
self.numberOfColumns = cursor.numberOfColumns
self.converters = cursor.converters
self.columnNames = cursor.columnNames
except AttributeError:
self.recordset_format = RS_ARRAY
self.numberOfColumns = 0
self.converters = []
self.columnNames = {}
self.numberOfRows = numberOfRows
def __len__(self):
return self.numberOfRows
def __getitem__(self, item): # used for row or row,column access
if not self.ado_results:
return []
if isinstance(item, slice): # will return a list of row objects
indices = item.indices(self.numberOfRows)
return [SQLrow(self, k) for k in range(*indices)]
elif isinstance(item, tuple) and len(item)==2:
# d = some_rowsObject[i,j] will return a datum from a two-dimension address
i, j = item
if not isinstance(j, int):
try:
j = self.columnNames[j.lower()] # convert named column to numeric
except KeyError:
raise KeyError('adodbapi: no such column name as "%s"'%repr(j))
if self.recordset_format == RS_ARRAY: # retrieve from two-dimensional array
v = self.ado_results[j,i]
elif self.recordset_format == RS_REMOTE:
v = self.ado_results[i][j]
else: # pywin32 - retrieve from tuple of tuples
v = self.ado_results[j][i]
if self.converters is NotImplemented:
return v
return convert_to_python(v, self.converters[j])
else:
row = SQLrow(self, item) # new row descriptor
return row
def __iter__(self):
return iter(self.__next__())
def __next__(self):
for n in range(self.numberOfRows):
row = SQLrow(self, n)
yield row
# # # # #
# # # # # functions to re-format SQL requests to other paramstyle requirements # # # # # # # # # #
def changeNamedToQmark(op): #convert from 'named' paramstyle to ADO required '?'mark parameters
outOp = ''
outparms=[]
chunks = op.split("'") #quote all literals -- odd numbered list results are literals.
inQuotes = False
for chunk in chunks:
if inQuotes: # this is inside a quote
if chunk == '': # double apostrophe to quote one apostrophe
outOp = outOp[:-1] # so take one away
else:
outOp += "'"+chunk+"'" # else pass the quoted string as is.
else: # is SQL code -- look for a :namedParameter
while chunk: # some SQL string remains
sp = chunk.split(':',1)
outOp += sp[0] # concat the part up to the :
s = ''
try:
chunk = sp[1]
except IndexError:
chunk = None
if chunk: # there was a parameter - parse it out
i = 0
c = chunk[0]
while c.isalnum() or c == '_':
i += 1
try:
c = chunk[i]
except IndexError:
break
s = chunk[:i]
chunk = chunk[i:]
if s:
outparms.append(s) # list the parameters in order
outOp += '?' # put in the Qmark
inQuotes = not inQuotes
return outOp, outparms
def changeFormatToQmark(op): #convert from 'format' paramstyle to ADO required '?'mark parameters
outOp = ''
outparams = []
chunks = op.split("'") #quote all literals -- odd numbered list results are literals.
inQuotes = False
for chunk in chunks:
if inQuotes:
if outOp != '' and chunk=='': # he used a double apostrophe to quote one apostrophe
outOp = outOp[:-1] # so take one away
else:
outOp += "'"+chunk+"'" # else pass the quoted string as is.
else: # is SQL code -- look for a %s parameter
if '%(' in chunk: # ugh! pyformat!
while chunk: # some SQL string remains
sp = chunk.split('%(', 1)
outOp += sp[0] # concat the part up to the %
if len(sp) > 1:
try:
s, chunk = sp[1].split(')s', 1) # find the ')s'
except ValueError:
raise ProgrammingError('Pyformat SQL has incorrect format near "%s"' % chunk)
outparams.append(s)
outOp += '?' # put in the Qmark
else:
chunk = None
else: # proper '%s' format
sp = chunk.split('%s') # make each %s
outOp += "?".join(sp) # into ?
inQuotes = not inQuotes # every other chunk is a quoted string
return outOp, outparams
| {
"repo_name": "sserrot/champion_relationships",
"path": "venv/Lib/site-packages/adodbapi/apibase.py",
"copies": "1",
"size": "29103",
"license": "mit",
"hash": 2531246055567988000,
"line_mean": 43.5681470138,
"line_max": 116,
"alpha_frac": 0.6316874549,
"autogenerated": false,
"ratio": 3.9801695842450764,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5111857039145076,
"avg_score": null,
"num_lines": null
} |
# ADO enumerated constants documented on MSDN:
# http://msdn.microsoft.com/en-us/library/ms678353(VS.85).aspx
# IsolationLevelEnum
adXactUnspecified = -1
adXactBrowse = 0x100
adXactChaos = 0x10
adXactCursorStability = 0x1000
adXactIsolated = 0x100000
adXactReadCommitted = 0x1000
adXactReadUncommitted = 0x100
adXactRepeatableRead = 0x10000
adXactSerializable = 0x100000
# CursorLocationEnum
adUseClient = 3
adUseServer = 2
# CursorTypeEnum
adOpenDynamic = 2
adOpenForwardOnly = 0
adOpenKeyset = 1
adOpenStatic = 3
adOpenUnspecified = -1
# CommandTypeEnum
adCmdText = 1
adCmdStoredProc = 4
adSchemaTables = 20
# ParameterDirectionEnum
adParamInput = 1
adParamInputOutput = 3
adParamOutput = 2
adParamReturnValue = 4
adParamUnknown = 0
directions = {
0: 'Unknown',
1: 'Input',
2: 'Output',
3: 'InputOutput',
4: 'Return',
}
def ado_direction_name(ado_dir):
try:
return 'adParam' + directions[ado_dir]
except:
return 'unknown direction ('+str(ado_dir)+')'
# ObjectStateEnum
adStateClosed = 0
adStateOpen = 1
adStateConnecting = 2
adStateExecuting = 4
adStateFetching = 8
# FieldAttributeEnum
adFldMayBeNull = 0x40
# ConnectModeEnum
adModeUnknown = 0
adModeRead = 1
adModeWrite = 2
adModeReadWrite = 3
adModeShareDenyRead = 4
adModeShareDenyWrite = 8
adModeShareExclusive = 12
adModeShareDenyNone = 16
adModeRecursive = 0x400000
# XactAttributeEnum
adXactCommitRetaining = 131072
adXactAbortRetaining = 262144
ado_error_TIMEOUT = -2147217871
# DataTypeEnum - ADO Data types documented at:
# http://msdn2.microsoft.com/en-us/library/ms675318.aspx
adArray = 0x2000
adEmpty = 0x0
adBSTR = 0x8
adBigInt = 0x14
adBinary = 0x80
adBoolean = 0xb
adChapter = 0x88
adChar = 0x81
adCurrency = 0x6
adDBDate = 0x85
adDBTime = 0x86
adDBTimeStamp = 0x87
adDate = 0x7
adDecimal = 0xe
adDouble = 0x5
adError = 0xa
adFileTime = 0x40
adGUID = 0x48
adIDispatch = 0x9
adIUnknown = 0xd
adInteger = 0x3
adLongVarBinary = 0xcd
adLongVarChar = 0xc9
adLongVarWChar = 0xcb
adNumeric = 0x83
adPropVariant = 0x8a
adSingle = 0x4
adSmallInt = 0x2
adTinyInt = 0x10
adUnsignedBigInt = 0x15
adUnsignedInt = 0x13
adUnsignedSmallInt = 0x12
adUnsignedTinyInt = 0x11
adUserDefined = 0x84
adVarBinary = 0xCC
adVarChar = 0xC8
adVarNumeric = 0x8B
adVarWChar = 0xCA
adVariant = 0xC
adWChar = 0x82
# Additional constants used by introspection but not ADO itself
AUTO_FIELD_MARKER = -1000
adTypeNames = {
adBSTR: 'adBSTR',
adBigInt: 'adBigInt',
adBinary: 'adBinary',
adBoolean: 'adBoolean',
adChapter: 'adChapter',
adChar: 'adChar',
adCurrency: 'adCurrency',
adDBDate: 'adDBDate',
adDBTime: 'adDBTime',
adDBTimeStamp: 'adDBTimeStamp',
adDate: 'adDate',
adDecimal: 'adDecimal',
adDouble: 'adDouble',
adEmpty: 'adEmpty',
adError: 'adError',
adFileTime: 'adFileTime',
adGUID: 'adGUID',
adIDispatch: 'adIDispatch',
adIUnknown: 'adIUnknown',
adInteger: 'adInteger',
adLongVarBinary: 'adLongVarBinary',
adLongVarChar: 'adLongVarChar',
adLongVarWChar: 'adLongVarWChar',
adNumeric: 'adNumeric',
adPropVariant: 'adPropVariant',
adSingle: 'adSingle',
adSmallInt: 'adSmallInt',
adTinyInt: 'adTinyInt',
adUnsignedBigInt: 'adUnsignedBigInt',
adUnsignedInt: 'adUnsignedInt',
adUnsignedSmallInt: 'adUnsignedSmallInt',
adUnsignedTinyInt: 'adUnsignedTinyInt',
adUserDefined: 'adUserDefined',
adVarBinary: 'adVarBinary',
adVarChar: 'adVarChar',
adVarNumeric: 'adVarNumeric',
adVarWChar: 'adVarWChar',
adVariant: 'adVariant',
adWChar: 'adWChar',
}
def ado_type_name(ado_type):
return adTypeNames.get(ado_type, 'unknown type ('+str(ado_type)+')')
# here in decimal, sorted by value
#adEmpty 0 Specifies no value (DBTYPE_EMPTY).
#adSmallInt 2 Indicates a two-byte signed integer (DBTYPE_I2).
#adInteger 3 Indicates a four-byte signed integer (DBTYPE_I4).
#adSingle 4 Indicates a single-precision floating-point value (DBTYPE_R4).
#adDouble 5 Indicates a double-precision floating-point value (DBTYPE_R8).
#adCurrency 6 Indicates a currency value (DBTYPE_CY). Currency is a fixed-point number
# with four digits to the right of the decimal point. It is stored in an eight-byte signed integer scaled by 10,000.
#adDate 7 Indicates a date value (DBTYPE_DATE). A date is stored as a double, the whole part of which is
# the number of days since December 30, 1899, and the fractional part of which is the fraction of a day.
#adBSTR 8 Indicates a null-terminated character string (Unicode) (DBTYPE_BSTR).
#adIDispatch 9 Indicates a pointer to an IDispatch interface on a COM object (DBTYPE_IDISPATCH).
#adError 10 Indicates a 32-bit error code (DBTYPE_ERROR).
#adBoolean 11 Indicates a boolean value (DBTYPE_BOOL).
#adVariant 12 Indicates an Automation Variant (DBTYPE_VARIANT).
#adIUnknown 13 Indicates a pointer to an IUnknown interface on a COM object (DBTYPE_IUNKNOWN).
#adDecimal 14 Indicates an exact numeric value with a fixed precision and scale (DBTYPE_DECIMAL).
#adTinyInt 16 Indicates a one-byte signed integer (DBTYPE_I1).
#adUnsignedTinyInt 17 Indicates a one-byte unsigned integer (DBTYPE_UI1).
#adUnsignedSmallInt 18 Indicates a two-byte unsigned integer (DBTYPE_UI2).
#adUnsignedInt 19 Indicates a four-byte unsigned integer (DBTYPE_UI4).
#adBigInt 20 Indicates an eight-byte signed integer (DBTYPE_I8).
#adUnsignedBigInt 21 Indicates an eight-byte unsigned integer (DBTYPE_UI8).
#adFileTime 64 Indicates a 64-bit value representing the number of 100-nanosecond intervals since
# January 1, 1601 (DBTYPE_FILETIME).
#adGUID 72 Indicates a globally unique identifier (GUID) (DBTYPE_GUID).
#adBinary 128 Indicates a binary value (DBTYPE_BYTES).
#adChar 129 Indicates a string value (DBTYPE_STR).
#adWChar 130 Indicates a null-terminated Unicode character string (DBTYPE_WSTR).
#adNumeric 131 Indicates an exact numeric value with a fixed precision and scale (DBTYPE_NUMERIC).
# adUserDefined 132 Indicates a user-defined variable (DBTYPE_UDT).
#adUserDefined 132 Indicates a user-defined variable (DBTYPE_UDT).
#adDBDate 133 Indicates a date value (yyyymmdd) (DBTYPE_DBDATE).
#adDBTime 134 Indicates a time value (hhmmss) (DBTYPE_DBTIME).
#adDBTimeStamp 135 Indicates a date/time stamp (yyyymmddhhmmss plus a fraction in billionths) (DBTYPE_DBTIMESTAMP).
#adChapter 136 Indicates a four-byte chapter value that identifies rows in a child rowset (DBTYPE_HCHAPTER).
#adPropVariant 138 Indicates an Automation PROPVARIANT (DBTYPE_PROP_VARIANT).
#adVarNumeric 139 Indicates a numeric value (Parameter object only).
#adVarChar 200 Indicates a string value (Parameter object only).
#adLongVarChar 201 Indicates a long string value (Parameter object only).
#adVarWChar 202 Indicates a null-terminated Unicode character string (Parameter object only).
#adLongVarWChar 203 Indicates a long null-terminated Unicode string value (Parameter object only).
#adVarBinary 204 Indicates a binary value (Parameter object only).
#adLongVarBinary 205 Indicates a long binary value (Parameter object only).
#adArray (Does not apply to ADOX.) 0x2000 A flag value, always combined with another data type constant,
# that indicates an array of that other data type.
# Error codes to names
adoErrors= {
0xe7b :'adErrBoundToCommand',
0xe94 :'adErrCannotComplete',
0xea4 :'adErrCantChangeConnection',
0xc94 :'adErrCantChangeProvider',
0xe8c :'adErrCantConvertvalue',
0xe8d :'adErrCantCreate',
0xea3 :'adErrCatalogNotSet',
0xe8e :'adErrColumnNotOnThisRow',
0xd5d :'adErrDataConversion',
0xe89 :'adErrDataOverflow',
0xe9a :'adErrDelResOutOfScope',
0xea6 :'adErrDenyNotSupported',
0xea7 :'adErrDenyTypeNotSupported',
0xcb3 :'adErrFeatureNotAvailable',
0xea5 :'adErrFieldsUpdateFailed',
0xc93 :'adErrIllegalOperation',
0xcae :'adErrInTransaction',
0xe87 :'adErrIntegrityViolation',
0xbb9 :'adErrInvalidArgument',
0xe7d :'adErrInvalidConnection',
0xe7c :'adErrInvalidParamInfo',
0xe82 :'adErrInvalidTransaction',
0xe91 :'adErrInvalidURL',
0xcc1 :'adErrItemNotFound',
0xbcd :'adErrNoCurrentRecord',
0xe83 :'adErrNotExecuting',
0xe7e :'adErrNotReentrant',
0xe78 :'adErrObjectClosed',
0xd27 :'adErrObjectInCollection',
0xd5c :'adErrObjectNotSet',
0xe79 :'adErrObjectOpen',
0xbba :'adErrOpeningFile',
0xe80 :'adErrOperationCancelled',
0xe96 :'adErrOutOfSpace',
0xe88 :'adErrPermissionDenied',
0xe9e :'adErrPropConflicting',
0xe9b :'adErrPropInvalidColumn',
0xe9c :'adErrPropInvalidOption',
0xe9d :'adErrPropInvalidValue',
0xe9f :'adErrPropNotAllSettable',
0xea0 :'adErrPropNotSet',
0xea1 :'adErrPropNotSettable',
0xea2 :'adErrPropNotSupported',
0xbb8 :'adErrProviderFailed',
0xe7a :'adErrProviderNotFound',
0xbbb :'adErrReadFile',
0xe93 :'adErrResourceExists',
0xe92 :'adErrResourceLocked',
0xe97 :'adErrResourceOutOfScope',
0xe8a :'adErrSchemaViolation',
0xe8b :'adErrSignMismatch',
0xe81 :'adErrStillConnecting',
0xe7f :'adErrStillExecuting',
0xe90 :'adErrTreePermissionDenied',
0xe8f :'adErrURLDoesNotExist',
0xe99 :'adErrURLNamedRowDoesNotExist',
0xe98 :'adErrUnavailable',
0xe84 :'adErrUnsafeOperation',
0xe95 :'adErrVolumeNotFound',
0xbbc :'adErrWriteFile'
}
| {
"repo_name": "int19h/PTVS",
"path": "Python/Product/Miniconda/Miniconda3-x64/Lib/site-packages/adodbapi/ado_consts.py",
"copies": "15",
"size": "10615",
"license": "apache-2.0",
"hash": 7872660788779031000,
"line_mean": 37.4601449275,
"line_max": 118,
"alpha_frac": 0.6601036269,
"autogenerated": false,
"ratio": 3.3506944444444446,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.024285232128037945,
"num_lines": 276
} |
# A DoIt script for building the course materials
import yaml
import os
import os.path
from doit.task import clean_targets
with open("course.yaml", "r") as fcourse:
course = yaml.safe_load(fcourse)
note_template = "note_template.tex"
slide_template = "slide_template.tex"
if not os.path.isdir("notes"):
os.mkdir("notes")
if not os.path.isdir("slides"):
os.mkdir("slides")
def task_lectures():
"""Build lecture materials"""
lectures = course['lectures']
for lec in lectures:
pre = lec['pre']
src = lec["src"]
title = pre + '_' + lec['name']
sourcefiles = [os.path.join(pre, "%s_%s.md" % (pre, s)) for s in src]
srcseq = ' '.join(sourcefiles)
for fmt in ["notes", "slides"]:
outdir = fmt
# format-specific options
if fmt == "notes":
outfname = "%s.pdf" % title
tfmt = 'latex'
templatefile = "notes_template.tex"
elif fmt == "slides":
outfname = "%s_slides.pdf" % title
tfmt = 'beamer'
templatefile = "slides_template.tex"
# decide output file and command
outpath = os.path.join(outdir, outfname)
cmd = "cat {srcs} | pandoc -t {tfmt} --template={templ} -o {output}".format(
srcs=srcseq,
tfmt=tfmt,
templ=templatefile,
output=outpath)
# yield task
yield {
'name': "{title} [{fmt}]".format(title=title, fmt=fmt),
'actions': [cmd],
'file_dep': [templatefile] + sourcefiles,
'targets' : [outpath],
'clean': [clean_targets],
'verbosity': 2
}
| {
"repo_name": "turinglife/MLPI",
"path": "lectures/dodo.py",
"copies": "1",
"size": "1805",
"license": "cc0-1.0",
"hash": -7514640466479641000,
"line_mean": 24.0694444444,
"line_max": 88,
"alpha_frac": 0.5069252078,
"autogenerated": false,
"ratio": 3.729338842975207,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9664258704893456,
"avg_score": 0.014401069176350074,
"num_lines": 72
} |
'''A domain specific language for timeseries analysis and manipulation.
Created using ply (http://www.dabeaz.com/ply/) a pure Python implementation
of the popular compiler construction tools lex and yacc.
'''
from ccy import todate
from ..conf import settings
from ..exc import ExpressionError, CouldNotParse
from ..api.timeseries import is_timeseries, ts_merge
from ..api.scatter import is_scatter
from ..data import providers
from .functions import function_registry
from .rules import parsefunc
def parse(timeseries_expression, method=None, functions=None, debug=False):
'''Function for parsing :ref:`timeseries expressions <dsl-script>`.
If succesful, it returns an instance of :class:`dynts.dsl.Expr` which
can be used to to populate timeseries or scatters once data is available.
Parsing is implemented using the ply_ module,
an implementation of lex and yacc parsing tools for Python.
:parameter expression: A :ref:`timeseries expressions <dsl-script>` string.
:parameter method: Not yet used.
:parameter functions: dictionary of functions to use when parsing.
If not provided the :data:`dynts.function_registry`
will be used.
Default ``None``.
:parameter debug: debug flag for ply_. Default ``False``.
For examples and usage check the :ref:`dsl documentation <dsl>`.
.. _ply: http://www.dabeaz.com/ply/
'''
if not parsefunc:
raise ExpressionError('Could not parse. No parser installed.')
functions = functions if functions is not None else function_registry
expr_str = str(timeseries_expression).lower()
return parsefunc(expr_str, functions, method, debug)
def evaluate(expression, start=None, end=None, loader=None, logger=None,
backend=None, **kwargs):
'''Evaluate a timeseries ``expression`` into
an instance of :class:`dynts.dsl.dslresult` which can be used
to obtain timeseries and/or scatters.
This is probably the most used function of the library.
:parameter expression: A timeseries expression string or an instance
of :class:`dynts.dsl.Expr` obtained using the :func:`~.parse`
function.
:parameter start: Start date or ``None``.
:parameter end: End date or ``None``. If not provided today values is used.
:parameter loader: Optional :class:`dynts.data.TimeSerieLoader`
class or instance to use.
Default ``None``.
:parameter logger: Optional python logging instance, used if you required
logging.
Default ``None``.
:parameter backend: :class:`dynts.TimeSeries` backend name or ``None``.
The ``expression`` is parsed and the :class:`~.Symbol` are sent to the
:class:`dynts.data.TimeSerieLoader` instance for retrieving
actual timeseries data.
It returns an instance of :class:`~.DSLResult`.
Typical usage::
>>> from dynts import api
>>> r = api.evaluate('min(GS,window=30)')
>>> r
min(GS,window=30)
>>> ts = r.ts()
'''
if isinstance(expression, str):
expression = parse(expression)
if not expression or expression.malformed():
raise CouldNotParse(expression)
symbols = expression.symbols()
start = start if not start else todate(start)
end = end if not end else todate(end)
data = providers.load(symbols, start, end, loader=loader,
logger=logger, backend=backend, **kwargs)
return DSLResult(expression, data, backend=backend)
class DSLResult:
'''Class holding the results of an interpreted expression.
Instances of this class are returned when invoking the
:func:`dynts.evaluate` high level function.
.. attribute:: expression
An instance of :class:`dynts.dsl.Expr` obtained when interpreting a
timesries expression string via :func:`dynts.parse`.
.. attribute:: data
data which is used to populate timeseries or scatters.
.. attribute:: backend
backend used when populating timeseries.
'''
def __init__(self, expression, data, backend = None):
self.expression = expression
self.data = data
self.backend = backend or settings.backend
def __repr__(self):
return self.expression.__repr__()
def __str__(self):
return self.__repr__()
def unwind(self):
if not hasattr(self, '_ts'):
self._unwind()
return self
def ts(self):
'''The associated timeseries, if available.'''
self.unwind()
return self._ts
def xy(self):
'''The associated scatters, if available.'''
self.unwind()
return self._xy
def _unwind(self):
res = self.expression.unwind(self.data, self.backend)
self._ts = None
self._xy = None
if is_timeseries(res):
self._ts = res
elif res and isinstance(res,list):
tss = []
xys = []
for v in res:
if is_timeseries(v):
tss.append(v)
elif is_scatter(v):
xys.append(v)
if tss:
self._ts = ts_merge(tss)
if xys:
self._xy = xys
elif is_scatter(res):
self._xy = res
def dump(self, format, **kwargs):
ts = self.ts()
xy = self.xy()
if is_timeseries(ts):
ts = ts.dump(format, **kwargs)
else:
ts = None
if xy:
if is_scatter(xy):
xy = [xy]
for el in xy:
ts = el.dump(format, container=ts, **kwargs)
return ts
| {
"repo_name": "quantmind/dynts",
"path": "dynts/dsl/__init__.py",
"copies": "1",
"size": "5817",
"license": "bsd-3-clause",
"hash": -7630535903210554000,
"line_mean": 32.2176470588,
"line_max": 79,
"alpha_frac": 0.6064981949,
"autogenerated": false,
"ratio": 4.249086924762601,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.53555851196626,
"avg_score": null,
"num_lines": null
} |
"""A Doozer plugin to interact with S3."""
import os as _os
from boto3.session import Session
from botocore.exceptions import ClientError
from doozer import Extension
import pkg_resources as _pkg_resources
__all__ = ("S3",)
try:
_dist = _pkg_resources.get_distribution(__name__)
if not __file__.startswith(_os.path.join(_dist.location, __name__)):
# Manually raise the exception if there is a distribution but
# it's installed from elsewhere.
raise _pkg_resources.DistributionNotFound
except _pkg_resources.DistributionNotFound:
__version__ = "development"
else:
__version__ = _dist.version
class S3(Extension):
"""A class to interact with S3."""
DEFAULT_SETTINGS = {
"AWS_ACCESS_KEY_ID": None,
"AWS_SECRET_ACCESS_KEY": None,
"AWS_BUCKET_NAME": None,
"AWS_REGION_NAME": None,
}
def init_app(self, app):
"""Initialize an ``Application`` instance.
Args:
app (doozer.base.Application): The application instance to
be initialized.
"""
super().init_app(app)
self._session = Session(
aws_access_key_id=app.settings["AWS_ACCESS_KEY_ID"],
aws_secret_access_key=app.settings["AWS_SECRET_ACCESS_KEY"],
region_name=app.settings["AWS_REGION_NAME"],
)
app.startup(self._connect)
async def check(self, key, *, bucket=None):
"""Check to see if a file exists in an S3 bucket.
Args:
key (str): The name of the file for which to check.
bucket (~typing.Optional[str]): THe name of the bucket in
which to check for the file. If no value is provided,
the ``AWS_BUCKET_NAME`` setting will be used.
Returns:
bool: True if the file exists.
Raises:
ValueError: If no bucket name is specified.
"""
bucket = bucket or self.app.settings["AWS_BUCKET_NAME"]
if not bucket:
raise ValueError("A bucket name is required.")
try:
self._client.head_object(Bucket=bucket, Key=key)
except ClientError:
return False
else:
return True
async def download(self, key, *, bucket=None):
"""Return the contents of a file in an S3 bucket.
Args:
key (str): The name of the file to download.
bucket (~typing.Optional[str]): The name of the bucket from
which to download the file. If no value is provided, the
``AWS_BUCKET_NAME`` setting will be used.
Returns:
bytes: The contents of the file.
Raises:
FileNotFoundError: If the key isn't found.
ValueError: If no bucket name is specified.
"""
bucket = bucket or self.app.settings["AWS_BUCKET_NAME"]
if not bucket:
raise ValueError("A bucket name is required.")
try:
file = self._client.get_object(Bucket=bucket, Key=key)
except ClientError:
raise FileNotFoundError("'{}' was not found in '{}'".format(key, bucket))
return file["Body"].read()
# TODO: Support other S3 settings (e.g., ACL, CacheControl).
async def upload(self, key, file, *, bucket=None):
"""Upload a file to an S3 bucket.
Args:
key (str): The name of the file to upload.
file (bytes): The contents of the file.
bucket (~typing.Optional[str]): The name of the bucket to
which to upload the file. If no value is provided, the
``AWS_BUCKET_NAME`` setting will be used.
Raises:
ValueError: If no bucket name is specified.
"""
bucket = bucket or self.app.settings["AWS_BUCKET_NAME"]
if not bucket:
raise ValueError("A bucket name is required.")
self._client.put_object(Body=file, Bucket=bucket, Key=key)
async def _connect(self, app):
"""Create an S3 client.
Args:
app (doozer.base.Application): The application instance
against which to register the client.
"""
self._client = self._session.client("s3")
| {
"repo_name": "dirn/Henson-S3",
"path": "doozer_s3.py",
"copies": "1",
"size": "4245",
"license": "mit",
"hash": -2542398090310632400,
"line_mean": 31.6538461538,
"line_max": 85,
"alpha_frac": 0.5830388693,
"autogenerated": false,
"ratio": 4.2749244712990935,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5357963340599093,
"avg_score": null,
"num_lines": null
} |
# Adopted form SfePy project, see http://sfepy.org
# Thanks to Robert Cimrman
import numpy as nm
import os
import os.path as op
import fnmatch
import shutil
from .base import output, Struct, basestr
try:
import tables as pt
except:
pt = None
class InDir(Struct):
"""
Store the directory name a file is in, and prepend this name to other
files.
Examples
--------
>>> indir = InDir('output/file1')
>>> print indir('file2')
"""
def __init__(self, filename):
self.dir = op.split(op.join(os.getcwd(), filename))[0]
def __call__(self, filename):
return op.join(self.dir, filename)
def ensure_path(filename):
"""
Check if path to `filename` exists and if not, create the necessary
intermediate directories.
"""
dirname = os.path.dirname(filename)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
def locate_files(pattern, root_dir=os.curdir):
"""
Locate all files matching fiven filename pattern in and below
supplied root directory.
"""
for dirpath, dirnames, filenames in os.walk(os.path.abspath(root_dir)):
for filename in fnmatch.filter(filenames, pattern):
yield os.path.join(dirpath, filename)
def remove_files(root_dir):
"""
Remove all files and directories in supplied root directory.
"""
for dirpath, dirnames, filenames in os.walk(os.path.abspath(root_dir)):
for filename in filenames:
os.remove(os.path.join(root_dir, filename))
for dirname in dirnames:
shutil.rmtree(os.path.join(root_dir, dirname))
##
# 27.04.2006, c
def get_trunk(filename):
return op.splitext(op.basename(filename))[0]
def edit_filename(filename, prefix="", suffix="", new_ext=None):
"""
Edit a file name by add a prefix, inserting a suffix in front of a file
name extension or replacing the extension.
Parameters
----------
filename : str
The file name.
prefix : str
The prefix to be added.
suffix : str
The suffix to be inserted.
new_ext : str, optional
If not None, it replaces the original file name extension.
Returns
-------
new_filename : str
The new file name.
"""
base, ext = os.path.splitext(filename)
if new_ext is None:
new_filename = base + suffix + ext
else:
new_filename = base + suffix + new_ext
return new_filename
def get_print_info(n_step, fill=None):
"""
Returns the max. number of digits in range(n_step) and the corresponding
format string.
Examples:
>>> get_print_info(11)
(2, '%2d')
>>> get_print_info(8)
(1, '%1d')
>>> get_print_info(100)
(2, '%2d')
>>> get_print_info(101)
(3, '%3d')
>>> get_print_info(101, fill='0')
(3, '%03d')
"""
if n_step > 1:
n_digit = int(nm.log10(n_step - 1) + 1)
if fill is None:
format = "%%%dd" % n_digit
else:
format = "%%%s%dd" % (fill, n_digit)
else:
n_digit, format = 0, None
return n_digit, format
def skip_read_line(fd, no_eof=False):
"""
Read the first non-empty line (if any) from the given file
object. Return an empty string at EOF, if `no_eof` is False. If it
is True, raise the EOFError instead.
"""
ls = ""
while 1:
try:
line = fd.readline()
except EOFError:
break
if not line:
if no_eof:
raise EOFError
else:
break
ls = line.strip()
if ls and (ls[0] != "#"):
break
return ls
def read_token(fd):
"""
Read a single token (sequence of non-whitespace characters) from the
given file object.
Notes
-----
Consumes the first whitespace character after the token.
"""
out = ""
# Skip initial whitespace.
while 1:
ch = fd.read(1)
if ch.isspace():
continue
elif len(ch) == 0:
return out
else:
break
while not ch.isspace():
out = out + ch
ch = fd.read(1)
if len(ch) == 0:
break
return out
def read_array(fd, n_row, n_col, dtype):
"""
Read a NumPy array of shape `(n_row, n_col)` from the given file
object and cast it to type `dtype`.
If `n_col` is None, determine the number of columns automatically.
"""
if n_col is None:
idx = fd.tell()
row = fd.readline().split()
fd.seek(idx)
n_col = len(row)
count = n_row * n_col
val = nm.fromfile(fd, sep=" ", count=count)
if val.shape[0] < count:
raise ValueError("(%d, %d) array reading failed!" % (n_row, n_col))
val = nm.asarray(val, dtype=dtype)
val.shape = (n_row, n_col)
return val
##
# c: 05.02.2008, r: 05.02.2008
def read_list(fd, n_item, dtype):
vals = []
ii = 0
while ii < n_item:
line = [dtype(ic) for ic in fd.readline().split()]
vals.append(line)
ii += len(line)
if ii > n_item:
output("corrupted row?", line, ii, n_item)
raise ValueError
return vals
def write_dict_hdf5(filename, adict, level=0, group=None, fd=None):
if level == 0:
fd = pt.openFile(filename, mode="w", title="Recursive dict dump")
group = "/"
for key, val in adict.iteritems():
if isinstance(val, dict):
group2 = fd.createGroup(group, "_" + str(key), "%s group" % key)
write_dict_hdf5(filename, val, level + 1, group2, fd)
else:
fd.createArray(group, "_" + str(key), val, "%s data" % key)
if level == 0:
fd.close()
def read_dict_hdf5(filename, level=0, group=None, fd=None):
out = {}
if level == 0:
fd = pt.openFile(filename, mode="r")
group = fd.root
for name, gr in group._v_groups.iteritems():
name = name.replace("_", "", 1)
out[name] = read_dict_hdf5(filename, level + 1, gr, fd)
for name, data in group._v_leaves.iteritems():
name = name.replace("_", "", 1)
out[name] = data.read()
if level == 0:
fd.close()
return out
##
# 02.07.2007, c
def write_sparse_matrix_hdf5(filename, mtx, name="a sparse matrix"):
"""Assume CSR/CSC."""
fd = pt.openFile(filename, mode="w", title=name)
try:
info = fd.createGroup("/", "info")
fd.createArray(info, "dtype", mtx.dtype.str)
fd.createArray(info, "shape", mtx.shape)
fd.createArray(info, "format", mtx.format)
data = fd.createGroup("/", "data")
fd.createArray(data, "data", mtx.data)
fd.createArray(data, "indptr", mtx.indptr)
fd.createArray(data, "indices", mtx.indices)
except:
print("matrix must be in SciPy sparse CSR/CSC format!")
print(mtx.__repr__())
raise
fd.close()
##
# 02.07.2007, c
# 08.10.2007
def read_sparse_matrix_hdf5(filename, output_format=None):
import scipy.sparse as sp
constructors = {"csr": sp.csr_matrix, "csc": sp.csc_matrix}
fd = pt.openFile(filename, mode="r")
info = fd.root.info
data = fd.root.data
format = info.format.read()
if not isinstance(format, basestr):
format = format[0]
dtype = info.dtype.read()
if not isinstance(dtype, basestr):
dtype = dtype[0]
if output_format is None:
constructor = constructors[format]
else:
constructor = constructors[output_format]
if format in ["csc", "csr"]:
mtx = constructor(
(data.data.read(), data.indices.read(), data.indptr.read()),
shape=info.shape.read(),
dtype=dtype,
)
elif format == "coo":
mtx = constructor(
(data.data.read(), nm.c_[data.rows.read(), data.cols.read()].T),
shape=info.shape.read(),
dtype=dtype,
)
else:
print(format)
raise ValueError
fd.close()
if output_format in ["csc", "csr"]:
mtx.sort_indices()
return mtx
| {
"repo_name": "mjirik/dicom2fem",
"path": "dicom2fem/ioutils.py",
"copies": "1",
"size": "8117",
"license": "bsd-3-clause",
"hash": -564301982416128900,
"line_mean": 22.8735294118,
"line_max": 76,
"alpha_frac": 0.5647406677,
"autogenerated": false,
"ratio": 3.544541484716157,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4609282152416157,
"avg_score": null,
"num_lines": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.