_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q26700
|
EntryAdmin.get_sites
|
train
|
def get_sites(self, entry):
"""
Return the sites linked in HTML.
"""
try:
index_url = reverse('zinnia:entry_archive_index')
except NoReverseMatch:
index_url = ''
return format_html_join(
', ', '<a href="{}://{}{}" target="blank">{}</a>',
[(settings.PROTOCOL, site.domain, index_url,
conditional_escape(site.name)) for site in entry.sites.all()])
|
python
|
{
"resource": ""
}
|
q26701
|
EntryAdmin.get_short_url
|
train
|
def get_short_url(self, entry):
"""
Return the short url in HTML.
"""
try:
short_url = entry.short_url
except NoReverseMatch:
short_url = entry.get_absolute_url()
return format_html('<a href="{url}" target="blank">{url}</a>',
url=short_url)
|
python
|
{
"resource": ""
}
|
q26702
|
EntryAdmin.get_queryset
|
train
|
def get_queryset(self, request):
"""
Make special filtering by user's permissions.
"""
if not request.user.has_perm('zinnia.can_view_all'):
queryset = self.model.objects.filter(authors__pk=request.user.pk)
else:
queryset = super(EntryAdmin, self).get_queryset(request)
return queryset.prefetch_related('categories', 'authors', 'sites')
|
python
|
{
"resource": ""
}
|
q26703
|
EntryAdmin.get_changeform_initial_data
|
train
|
def get_changeform_initial_data(self, request):
"""
Provide initial datas when creating an entry.
"""
get_data = super(EntryAdmin, self).get_changeform_initial_data(request)
return get_data or {
'sites': [Site.objects.get_current().pk],
'authors': [request.user.pk]
}
|
python
|
{
"resource": ""
}
|
q26704
|
EntryAdmin.formfield_for_manytomany
|
train
|
def formfield_for_manytomany(self, db_field, request, **kwargs):
"""
Filter the disposable authors.
"""
if db_field.name == 'authors':
kwargs['queryset'] = Author.objects.filter(
Q(is_staff=True) | Q(entries__isnull=False)
).distinct()
return super(EntryAdmin, self).formfield_for_manytomany(
db_field, request, **kwargs)
|
python
|
{
"resource": ""
}
|
q26705
|
EntryAdmin.get_readonly_fields
|
train
|
def get_readonly_fields(self, request, obj=None):
"""
Return readonly fields by user's permissions.
"""
readonly_fields = list(super(EntryAdmin, self).get_readonly_fields(
request, obj))
if not request.user.has_perm('zinnia.can_change_status'):
readonly_fields.append('status')
if not request.user.has_perm('zinnia.can_change_author'):
readonly_fields.append('authors')
return readonly_fields
|
python
|
{
"resource": ""
}
|
q26706
|
EntryAdmin.get_actions
|
train
|
def get_actions(self, request):
"""
Define actions by user's permissions.
"""
actions = super(EntryAdmin, self).get_actions(request)
if not actions:
return actions
if (not request.user.has_perm('zinnia.can_change_author') or
not request.user.has_perm('zinnia.can_view_all')):
del actions['make_mine']
if not request.user.has_perm('zinnia.can_change_status'):
del actions['make_hidden']
del actions['make_published']
if not settings.PING_DIRECTORIES:
del actions['ping_directories']
return actions
|
python
|
{
"resource": ""
}
|
q26707
|
EntryAdmin.make_mine
|
train
|
def make_mine(self, request, queryset):
"""
Set the entries to the current user.
"""
author = Author.objects.get(pk=request.user.pk)
for entry in queryset:
if author not in entry.authors.all():
entry.authors.add(author)
self.message_user(
request, _('The selected entries now belong to you.'))
|
python
|
{
"resource": ""
}
|
q26708
|
EntryAdmin.make_published
|
train
|
def make_published(self, request, queryset):
"""
Set entries selected as published.
"""
queryset.update(status=PUBLISHED)
EntryPublishedVectorBuilder().cache_flush()
self.ping_directories(request, queryset, messages=False)
self.message_user(
request, _('The selected entries are now marked as published.'))
|
python
|
{
"resource": ""
}
|
q26709
|
EntryAdmin.make_hidden
|
train
|
def make_hidden(self, request, queryset):
"""
Set entries selected as hidden.
"""
queryset.update(status=HIDDEN)
EntryPublishedVectorBuilder().cache_flush()
self.message_user(
request, _('The selected entries are now marked as hidden.'))
|
python
|
{
"resource": ""
}
|
q26710
|
EntryAdmin.close_comments
|
train
|
def close_comments(self, request, queryset):
"""
Close the comments for selected entries.
"""
queryset.update(comment_enabled=False)
self.message_user(
request, _('Comments are now closed for selected entries.'))
|
python
|
{
"resource": ""
}
|
q26711
|
EntryAdmin.close_pingbacks
|
train
|
def close_pingbacks(self, request, queryset):
"""
Close the pingbacks for selected entries.
"""
queryset.update(pingback_enabled=False)
self.message_user(
request, _('Pingbacks are now closed for selected entries.'))
|
python
|
{
"resource": ""
}
|
q26712
|
EntryAdmin.close_trackbacks
|
train
|
def close_trackbacks(self, request, queryset):
"""
Close the trackbacks for selected entries.
"""
queryset.update(trackback_enabled=False)
self.message_user(
request, _('Trackbacks are now closed for selected entries.'))
|
python
|
{
"resource": ""
}
|
q26713
|
EntryAdmin.put_on_top
|
train
|
def put_on_top(self, request, queryset):
"""
Put the selected entries on top at the current date.
"""
queryset.update(publication_date=timezone.now())
self.ping_directories(request, queryset, messages=False)
self.message_user(request, _(
'The selected entries are now set at the current date.'))
|
python
|
{
"resource": ""
}
|
q26714
|
EntryAdmin.mark_featured
|
train
|
def mark_featured(self, request, queryset):
"""
Mark selected as featured post.
"""
queryset.update(featured=True)
self.message_user(
request, _('Selected entries are now marked as featured.'))
|
python
|
{
"resource": ""
}
|
q26715
|
EntryAdmin.unmark_featured
|
train
|
def unmark_featured(self, request, queryset):
"""
Un-Mark selected featured posts.
"""
queryset.update(featured=False)
self.message_user(
request, _('Selected entries are no longer marked as featured.'))
|
python
|
{
"resource": ""
}
|
q26716
|
EntryAdmin.ping_directories
|
train
|
def ping_directories(self, request, queryset, messages=True):
"""
Ping web directories for selected entries.
"""
for directory in settings.PING_DIRECTORIES:
pinger = DirectoryPinger(directory, queryset)
pinger.join()
if messages:
success = 0
for result in pinger.results:
if not result.get('flerror', True):
success += 1
else:
self.message_user(request,
'%s : %s' % (directory,
result['message']))
if success:
self.message_user(
request,
_('%(directory)s directory succesfully '
'pinged %(success)d entries.') %
{'directory': directory, 'success': success})
|
python
|
{
"resource": ""
}
|
q26717
|
MPTTModelChoiceIterator.choice
|
train
|
def choice(self, obj):
"""
Overloads the choice method to add the position
of the object in the tree for future sorting.
"""
tree_id = getattr(obj, self.queryset.model._mptt_meta.tree_id_attr, 0)
left = getattr(obj, self.queryset.model._mptt_meta.left_attr, 0)
return super(MPTTModelChoiceIterator,
self).choice(obj) + ((tree_id, left),)
|
python
|
{
"resource": ""
}
|
q26718
|
MPTTModelMultipleChoiceField.label_from_instance
|
train
|
def label_from_instance(self, obj):
"""
Create labels which represent the tree level of each node
when generating option labels.
"""
label = smart_text(obj)
prefix = self.level_indicator * getattr(obj, obj._mptt_meta.level_attr)
if prefix:
return '%s %s' % (prefix, label)
return label
|
python
|
{
"resource": ""
}
|
q26719
|
CapabilityView.get_context_data
|
train
|
def get_context_data(self, **kwargs):
"""
Populate the context of the template
with technical informations for building urls.
"""
context = super(CapabilityView, self).get_context_data(**kwargs)
context.update({'protocol': PROTOCOL,
'copyright': COPYRIGHT,
'feeds_format': FEEDS_FORMAT,
'site': Site.objects.get_current()})
return context
|
python
|
{
"resource": ""
}
|
q26720
|
get_user_flagger
|
train
|
def get_user_flagger():
"""
Return an User instance used by the system
when flagging a comment as trackback or pingback.
"""
user_klass = get_user_model()
try:
user = user_klass.objects.get(pk=COMMENT_FLAG_USER_ID)
except user_klass.DoesNotExist:
try:
user = user_klass.objects.get(
**{user_klass.USERNAME_FIELD: FLAGGER_USERNAME})
except user_klass.DoesNotExist:
user = user_klass.objects.create_user(FLAGGER_USERNAME)
return user
|
python
|
{
"resource": ""
}
|
q26721
|
EntryQuerysetTemplateResponseMixin.get_model_type
|
train
|
def get_model_type(self):
"""
Return the model type for templates.
"""
if self.model_type is None:
raise ImproperlyConfigured(
"%s requires either a definition of "
"'model_type' or an implementation of 'get_model_type()'" %
self.__class__.__name__)
return self.model_type
|
python
|
{
"resource": ""
}
|
q26722
|
EntryQuerysetTemplateResponseMixin.get_model_name
|
train
|
def get_model_name(self):
"""
Return the model name for templates.
"""
if self.model_name is None:
raise ImproperlyConfigured(
"%s requires either a definition of "
"'model_name' or an implementation of 'get_model_name()'" %
self.__class__.__name__)
return self.model_name
|
python
|
{
"resource": ""
}
|
q26723
|
EntryQuerysetArchiveTodayTemplateResponseMixin.get_archive_part_value
|
train
|
def get_archive_part_value(self, part):
"""Return archive part for today"""
parts_dict = {'year': '%Y',
'month': self.month_format,
'week': self.week_format,
'day': '%d'}
if self.today is None:
today = timezone.now()
if timezone.is_aware(today):
today = timezone.localtime(today)
self.today = today
return self.today.strftime(parts_dict[part])
|
python
|
{
"resource": ""
}
|
q26724
|
EntryArchiveTemplateResponseMixin.get_default_base_template_names
|
train
|
def get_default_base_template_names(self):
"""
Return the Entry.template value.
"""
return [self.object.detail_template,
'%s.html' % self.object.slug,
'%s_%s' % (self.object.slug, self.object.detail_template)]
|
python
|
{
"resource": ""
}
|
q26725
|
DiscussionsEntry.discussions
|
train
|
def discussions(self):
"""
Returns a queryset of the published discussions.
"""
return comments.get_model().objects.for_model(
self).filter(is_public=True, is_removed=False)
|
python
|
{
"resource": ""
}
|
q26726
|
DiscussionsEntry.comments
|
train
|
def comments(self):
"""
Returns a queryset of the published comments.
"""
return self.discussions.filter(Q(flags=None) | Q(
flags__flag=CommentFlag.MODERATOR_APPROVAL))
|
python
|
{
"resource": ""
}
|
q26727
|
DiscussionsEntry.discussion_is_still_open
|
train
|
def discussion_is_still_open(self, discussion_type, auto_close_after):
"""
Checks if a type of discussion is still open
are a certain number of days.
"""
discussion_enabled = getattr(self, discussion_type)
if (discussion_enabled and isinstance(auto_close_after, int) and
auto_close_after >= 0):
return (timezone.now() - (
self.start_publication or self.publication_date)).days < \
auto_close_after
return discussion_enabled
|
python
|
{
"resource": ""
}
|
q26728
|
ExcerptEntry.save
|
train
|
def save(self, *args, **kwargs):
"""
Overrides the save method to create an excerpt
from the content field if void.
"""
if not self.excerpt and self.status == PUBLISHED:
self.excerpt = Truncator(strip_tags(
getattr(self, 'content', ''))).words(50)
super(ExcerptEntry, self).save(*args, **kwargs)
|
python
|
{
"resource": ""
}
|
q26729
|
ImageEntry.image_upload_to
|
train
|
def image_upload_to(self, filename):
"""
Compute the upload path for the image field.
"""
now = timezone.now()
filename, extension = os.path.splitext(filename)
return os.path.join(
UPLOAD_TO,
now.strftime('%Y'),
now.strftime('%m'),
now.strftime('%d'),
'%s%s' % (slugify(filename), extension))
|
python
|
{
"resource": ""
}
|
q26730
|
get_category_or_404
|
train
|
def get_category_or_404(path):
"""
Retrieve a Category instance by a path.
"""
path_bits = [p for p in path.split('/') if p]
return get_object_or_404(Category, slug=path_bits[-1])
|
python
|
{
"resource": ""
}
|
q26731
|
BaseCategoryDetail.get_queryset
|
train
|
def get_queryset(self):
"""
Retrieve the category by his path and
build a queryset of her published entries.
"""
self.category = get_category_or_404(self.kwargs['path'])
return self.category.entries_published()
|
python
|
{
"resource": ""
}
|
q26732
|
BaseCategoryDetail.get_context_data
|
train
|
def get_context_data(self, **kwargs):
"""
Add the current category in context.
"""
context = super(BaseCategoryDetail, self).get_context_data(**kwargs)
context['category'] = self.category
return context
|
python
|
{
"resource": ""
}
|
q26733
|
EntryFeed.item_author_name
|
train
|
def item_author_name(self, item):
"""
Return the first author of an entry.
"""
if item.authors.count():
self.item_author = item.authors.all()[0]
return self.item_author.__str__()
|
python
|
{
"resource": ""
}
|
q26734
|
EntryFeed.item_author_link
|
train
|
def item_author_link(self, item):
"""
Return the author's URL.
Should not be called if self.item_author_name has returned None.
"""
try:
author_url = self.item_author.get_absolute_url()
return self.site_url + author_url
except NoReverseMatch:
return self.site_url
|
python
|
{
"resource": ""
}
|
q26735
|
EntryFeed.item_enclosure_url
|
train
|
def item_enclosure_url(self, item):
"""
Return an image for enclosure.
"""
try:
url = item.image.url
except (AttributeError, ValueError):
img = BeautifulSoup(item.html_content, 'html.parser').find('img')
url = img.get('src') if img else None
self.cached_enclosure_url = url
if url:
url = urljoin(self.site_url, url)
if self.feed_format == 'rss':
url = url.replace('https://', 'http://')
return url
|
python
|
{
"resource": ""
}
|
q26736
|
TagEntries.items
|
train
|
def items(self, obj):
"""
Items are the published entries of the tag.
"""
return TaggedItem.objects.get_by_model(
Entry.published.all(), obj)[:self.limit]
|
python
|
{
"resource": ""
}
|
q26737
|
SearchEntries.get_object
|
train
|
def get_object(self, request):
"""
The GET parameter 'pattern' is the object.
"""
pattern = request.GET.get('pattern', '')
if len(pattern) < 3:
raise ObjectDoesNotExist
return pattern
|
python
|
{
"resource": ""
}
|
q26738
|
LastDiscussions.items
|
train
|
def items(self):
"""
Items are the discussions on the entries.
"""
content_type = ContentType.objects.get_for_model(Entry)
return comments.get_model().objects.filter(
content_type=content_type, is_public=True).order_by(
'-submit_date')[:self.limit]
|
python
|
{
"resource": ""
}
|
q26739
|
EntryDiscussions.get_object
|
train
|
def get_object(self, request, year, month, day, slug):
"""
Retrieve the discussions by entry's slug.
"""
return get_object_or_404(Entry, slug=slug,
publication_date__year=year,
publication_date__month=month,
publication_date__day=day)
|
python
|
{
"resource": ""
}
|
q26740
|
textile
|
train
|
def textile(value):
"""
Textile processing.
"""
try:
import textile
except ImportError:
warnings.warn("The Python textile library isn't installed.",
RuntimeWarning)
return value
return textile.textile(force_text(value))
|
python
|
{
"resource": ""
}
|
q26741
|
markdown
|
train
|
def markdown(value, extensions=MARKDOWN_EXTENSIONS):
"""
Markdown processing with optionally using various extensions
that python-markdown supports.
`extensions` is an iterable of either markdown.Extension instances
or extension paths.
"""
try:
import markdown
except ImportError:
warnings.warn("The Python markdown library isn't installed.",
RuntimeWarning)
return value
return markdown.markdown(force_text(value), extensions=extensions)
|
python
|
{
"resource": ""
}
|
q26742
|
restructuredtext
|
train
|
def restructuredtext(value, settings=RESTRUCTUREDTEXT_SETTINGS):
"""
RestructuredText processing with optionnally custom settings.
"""
try:
from docutils.core import publish_parts
except ImportError:
warnings.warn("The Python docutils library isn't installed.",
RuntimeWarning)
return value
parts = publish_parts(source=force_bytes(value),
writer_name='html4css1',
settings_overrides=settings)
return force_text(parts['fragment'])
|
python
|
{
"resource": ""
}
|
q26743
|
html_format
|
train
|
def html_format(value):
"""
Returns the value formatted in HTML,
depends on MARKUP_LANGUAGE setting.
"""
if not value:
return ''
elif MARKUP_LANGUAGE == 'markdown':
return markdown(value)
elif MARKUP_LANGUAGE == 'textile':
return textile(value)
elif MARKUP_LANGUAGE == 'restructuredtext':
return restructuredtext(value)
elif '</p>' not in value:
return linebreaks(value)
return value
|
python
|
{
"resource": ""
}
|
q26744
|
CategoryAdminForm.clean_parent
|
train
|
def clean_parent(self):
"""
Check if category parent is not selfish.
"""
data = self.cleaned_data['parent']
if data == self.instance:
raise forms.ValidationError(
_('A category cannot be parent of itself.'),
code='self_parenting')
return data
|
python
|
{
"resource": ""
}
|
q26745
|
pearson_score
|
train
|
def pearson_score(list1, list2):
"""
Compute the Pearson' score between 2 lists of vectors.
"""
size = len(list1)
sum1 = sum(list1)
sum2 = sum(list2)
sum_sq1 = sum([pow(l, 2) for l in list1])
sum_sq2 = sum([pow(l, 2) for l in list2])
prod_sum = sum([list1[i] * list2[i] for i in range(size)])
num = prod_sum - (sum1 * sum2 / float(size))
den = sqrt((sum_sq1 - pow(sum1, 2.0) / size) *
(sum_sq2 - pow(sum2, 2.0) / size))
return num / den
|
python
|
{
"resource": ""
}
|
q26746
|
ModelVectorBuilder.get_related
|
train
|
def get_related(self, instance, number):
"""
Return a list of the most related objects to instance.
"""
related_pks = self.compute_related(instance.pk)[:number]
related_pks = [pk for pk, score in related_pks]
related_objects = sorted(
self.queryset.model.objects.filter(pk__in=related_pks),
key=lambda x: related_pks.index(x.pk))
return related_objects
|
python
|
{
"resource": ""
}
|
q26747
|
ModelVectorBuilder.compute_related
|
train
|
def compute_related(self, object_id, score=pearson_score):
"""
Compute the most related pks to an object's pk.
"""
dataset = self.dataset
object_vector = dataset.get(object_id)
if not object_vector:
return []
object_related = {}
for o_id, o_vector in dataset.items():
if o_id != object_id:
try:
object_related[o_id] = score(object_vector, o_vector)
except ZeroDivisionError:
pass
related = sorted(object_related.items(),
key=lambda k_v: (k_v[1], k_v[0]), reverse=True)
return related
|
python
|
{
"resource": ""
}
|
q26748
|
ModelVectorBuilder.raw_dataset
|
train
|
def raw_dataset(self):
"""
Generate a raw dataset based on the queryset
and the specified fields.
"""
dataset = {}
queryset = self.queryset.values_list(*(['pk'] + self.fields))
if self.limit:
queryset = queryset[:self.limit]
for item in queryset:
item = list(item)
item_pk = item.pop(0)
datas = ' '.join(map(six.text_type, item))
dataset[item_pk] = self.raw_clean(datas)
return dataset
|
python
|
{
"resource": ""
}
|
q26749
|
ModelVectorBuilder.raw_clean
|
train
|
def raw_clean(self, datas):
"""
Apply a cleaning on raw datas.
"""
datas = strip_tags(datas) # Remove HTML
datas = STOP_WORDS.rebase(datas, '') # Remove STOP WORDS
datas = PUNCTUATION.sub('', datas) # Remove punctuation
datas = datas.lower()
return [d for d in datas.split() if len(d) > 1]
|
python
|
{
"resource": ""
}
|
q26750
|
ModelVectorBuilder.columns_dataset
|
train
|
def columns_dataset(self):
"""
Generate the columns and the whole dataset.
"""
data = {}
words_total = {}
for instance, words in self.raw_dataset.items():
words_item_total = {}
for word in words:
words_total.setdefault(word, 0)
words_item_total.setdefault(word, 0)
words_total[word] += 1
words_item_total[word] += 1
data[instance] = words_item_total
columns = sorted(words_total.keys(),
key=lambda w: words_total[w],
reverse=True)[:250]
columns = sorted(columns)
dataset = {}
for instance in data.keys():
dataset[instance] = [data[instance].get(word, 0)
for word in columns]
return columns, dataset
|
python
|
{
"resource": ""
}
|
q26751
|
CachedModelVectorBuilder.set_cache
|
train
|
def set_cache(self, value):
"""
Assign the cache in cache.
"""
value.update(self.cache)
return self.cache_backend.set(self.cache_key, value)
|
python
|
{
"resource": ""
}
|
q26752
|
CachedModelVectorBuilder.get_related
|
train
|
def get_related(self, instance, number):
"""
Implement high level cache system for get_related.
"""
cache = self.cache
cache_key = '%s:%s' % (instance.pk, number)
if cache_key not in cache:
related_objects = super(CachedModelVectorBuilder,
self).get_related(instance, number)
cache[cache_key] = related_objects
self.cache = cache
return cache[cache_key]
|
python
|
{
"resource": ""
}
|
q26753
|
CachedModelVectorBuilder.columns_dataset
|
train
|
def columns_dataset(self):
"""
Implement high level cache system for columns and dataset.
"""
cache = self.cache
cache_key = 'columns_dataset'
if cache_key not in cache:
columns_dataset = super(CachedModelVectorBuilder, self
).columns_dataset
cache[cache_key] = columns_dataset
self.cache = cache
return cache[cache_key]
|
python
|
{
"resource": ""
}
|
q26754
|
EntryPublishedVectorBuilder.cache_key
|
train
|
def cache_key(self):
"""
Key for the cache handling current site.
"""
return '%s:%s' % (super(EntryPublishedVectorBuilder, self).cache_key,
Site.objects.get_current().pk)
|
python
|
{
"resource": ""
}
|
q26755
|
EntryPreviewMixin.get_object
|
train
|
def get_object(self, queryset=None):
"""
If the status of the entry is not PUBLISHED,
a preview is requested, so we check if the user
has the 'zinnia.can_view_all' permission or if
it's an author of the entry.
"""
obj = super(EntryPreviewMixin, self).get_object(queryset)
if obj.is_visible:
return obj
if (self.request.user.has_perm('zinnia.can_view_all') or
self.request.user.pk in [
author.pk for author in obj.authors.all()]):
return obj
raise Http404(_('No entry found matching the query'))
|
python
|
{
"resource": ""
}
|
q26756
|
EntryShortLink.get_redirect_url
|
train
|
def get_redirect_url(self, **kwargs):
"""
Get entry corresponding to 'pk' encoded in base36
in the 'token' variable and return the get_absolute_url
of the entry.
"""
entry = get_object_or_404(Entry.published, pk=int(kwargs['token'], 36))
return entry.get_absolute_url()
|
python
|
{
"resource": ""
}
|
q26757
|
advanced_search
|
train
|
def advanced_search(pattern):
"""
Parse the grammar of a pattern and build a queryset with it.
"""
query_parsed = QUERY.parseString(pattern)
return Entry.published.filter(query_parsed[0]).distinct()
|
python
|
{
"resource": ""
}
|
q26758
|
CategoryAdmin.get_tree_path
|
train
|
def get_tree_path(self, category):
"""
Return the category's tree path in HTML.
"""
try:
return format_html(
'<a href="{}" target="blank">/{}/</a>',
category.get_absolute_url(), category.tree_path)
except NoReverseMatch:
return '/%s/' % category.tree_path
|
python
|
{
"resource": ""
}
|
q26759
|
Command.write_out
|
train
|
def write_out(self, message, verbosity_level=1):
"""
Convenient method for outputing.
"""
if self.verbosity and self.verbosity >= verbosity_level:
sys.stdout.write(smart_str(message))
sys.stdout.flush()
|
python
|
{
"resource": ""
}
|
q26760
|
RelatedPublishedFilter.lookups
|
train
|
def lookups(self, request, model_admin):
"""
Return published objects with the number of entries.
"""
active_objects = self.model.published.all().annotate(
count_entries_published=Count('entries')).order_by(
'-count_entries_published', '-pk')
for active_object in active_objects:
yield (
str(active_object.pk), ungettext_lazy(
'%(item)s (%(count)i entry)',
'%(item)s (%(count)i entries)',
active_object.count_entries_published) % {
'item': smart_text(active_object),
'count': active_object.count_entries_published})
|
python
|
{
"resource": ""
}
|
q26761
|
RelatedPublishedFilter.queryset
|
train
|
def queryset(self, request, queryset):
"""
Return the object's entries if a value is set.
"""
if self.value():
params = {self.lookup_key: self.value()}
return queryset.filter(**params)
|
python
|
{
"resource": ""
}
|
q26762
|
year_crumb
|
train
|
def year_crumb(date):
"""
Crumb for a year.
"""
year = date.strftime('%Y')
return Crumb(year, reverse('zinnia:entry_archive_year',
args=[year]))
|
python
|
{
"resource": ""
}
|
q26763
|
month_crumb
|
train
|
def month_crumb(date):
"""
Crumb for a month.
"""
year = date.strftime('%Y')
month = date.strftime('%m')
month_text = DateFormat(date).format('F').capitalize()
return Crumb(month_text, reverse('zinnia:entry_archive_month',
args=[year, month]))
|
python
|
{
"resource": ""
}
|
q26764
|
day_crumb
|
train
|
def day_crumb(date):
"""
Crumb for a day.
"""
year = date.strftime('%Y')
month = date.strftime('%m')
day = date.strftime('%d')
return Crumb(day, reverse('zinnia:entry_archive_day',
args=[year, month, day]))
|
python
|
{
"resource": ""
}
|
q26765
|
entry_breadcrumbs
|
train
|
def entry_breadcrumbs(entry):
"""
Breadcrumbs for an Entry.
"""
date = entry.publication_date
if is_aware(date):
date = localtime(date)
return [year_crumb(date), month_crumb(date),
day_crumb(date), Crumb(entry.title)]
|
python
|
{
"resource": ""
}
|
q26766
|
handle_page_crumb
|
train
|
def handle_page_crumb(func):
"""
Decorator for handling the current page in the breadcrumbs.
"""
@wraps(func)
def wrapper(path, model, page, root_name):
path = PAGE_REGEXP.sub('', path)
breadcrumbs = func(path, model, root_name)
if page:
if page.number > 1:
breadcrumbs[-1].url = path
page_crumb = Crumb(_('Page %s') % page.number)
breadcrumbs.append(page_crumb)
return breadcrumbs
return wrapper
|
python
|
{
"resource": ""
}
|
q26767
|
retrieve_breadcrumbs
|
train
|
def retrieve_breadcrumbs(path, model_instance, root_name=''):
"""
Build a semi-hardcoded breadcrumbs
based of the model's url handled by Zinnia.
"""
breadcrumbs = []
zinnia_root_path = reverse('zinnia:entry_archive_index')
if root_name:
breadcrumbs.append(Crumb(root_name, zinnia_root_path))
if model_instance is not None:
key = model_instance.__class__.__name__
if key in MODEL_BREADCRUMBS:
breadcrumbs.extend(MODEL_BREADCRUMBS[key](model_instance))
return breadcrumbs
date_match = ARCHIVE_WEEK_REGEXP.match(path)
if date_match:
year, week = date_match.groups()
year_date = datetime(int(year), 1, 1)
date_breadcrumbs = [year_crumb(year_date),
Crumb(_('Week %s') % week)]
breadcrumbs.extend(date_breadcrumbs)
return breadcrumbs
date_match = ARCHIVE_REGEXP.match(path)
if date_match:
date_dict = date_match.groupdict()
path_date = datetime(
int(date_dict['year']),
date_dict.get('month') is not None and
int(date_dict.get('month')) or 1,
date_dict.get('day') is not None and
int(date_dict.get('day')) or 1)
date_breadcrumbs = [year_crumb(path_date)]
if date_dict['month']:
date_breadcrumbs.append(month_crumb(path_date))
if date_dict['day']:
date_breadcrumbs.append(day_crumb(path_date))
breadcrumbs.extend(date_breadcrumbs)
breadcrumbs[-1].url = None
return breadcrumbs
url_components = [comp for comp in
path.replace(zinnia_root_path, '', 1).split('/')
if comp]
if len(url_components):
breadcrumbs.append(Crumb(_(url_components[-1].capitalize())))
return breadcrumbs
|
python
|
{
"resource": ""
}
|
q26768
|
authenticate
|
train
|
def authenticate(username, password, permission=None):
"""
Authenticate staff_user with permission.
"""
try:
author = Author.objects.get(
**{'%s__exact' % Author.USERNAME_FIELD: username})
except Author.DoesNotExist:
raise Fault(LOGIN_ERROR, _('Username is incorrect.'))
if not author.check_password(password):
raise Fault(LOGIN_ERROR, _('Password is invalid.'))
if not author.is_staff or not author.is_active:
raise Fault(PERMISSION_DENIED, _('User account unavailable.'))
if permission:
if not author.has_perm(permission):
raise Fault(PERMISSION_DENIED, _('User cannot %s.') % permission)
return author
|
python
|
{
"resource": ""
}
|
q26769
|
blog_structure
|
train
|
def blog_structure(site):
"""
A blog structure.
"""
return {'blogid': settings.SITE_ID,
'blogName': site.name,
'url': '%s://%s%s' % (
PROTOCOL, site.domain,
reverse('zinnia:entry_archive_index'))}
|
python
|
{
"resource": ""
}
|
q26770
|
user_structure
|
train
|
def user_structure(user, site):
"""
An user structure.
"""
full_name = user.get_full_name().split()
first_name = full_name[0]
try:
last_name = full_name[1]
except IndexError:
last_name = ''
return {'userid': user.pk,
'email': user.email,
'nickname': user.get_username(),
'lastname': last_name,
'firstname': first_name,
'url': '%s://%s%s' % (
PROTOCOL, site.domain,
user.get_absolute_url())}
|
python
|
{
"resource": ""
}
|
q26771
|
author_structure
|
train
|
def author_structure(user):
"""
An author structure.
"""
return {'user_id': user.pk,
'user_login': user.get_username(),
'display_name': user.__str__(),
'user_email': user.email}
|
python
|
{
"resource": ""
}
|
q26772
|
category_structure
|
train
|
def category_structure(category, site):
"""
A category structure.
"""
return {'description': category.title,
'htmlUrl': '%s://%s%s' % (
PROTOCOL, site.domain,
category.get_absolute_url()),
'rssUrl': '%s://%s%s' % (
PROTOCOL, site.domain,
reverse('zinnia:category_feed', args=[category.tree_path])),
# Useful Wordpress Extensions
'categoryId': category.pk,
'parentId': category.parent and category.parent.pk or 0,
'categoryDescription': category.description,
'categoryName': category.title}
|
python
|
{
"resource": ""
}
|
q26773
|
tag_structure
|
train
|
def tag_structure(tag, site):
"""
A tag structure.
"""
return {'tag_id': tag.pk,
'name': tag.name,
'count': tag.count,
'slug': tag.name,
'html_url': '%s://%s%s' % (
PROTOCOL, site.domain,
reverse('zinnia:tag_detail', args=[tag.name])),
'rss_url': '%s://%s%s' % (
PROTOCOL, site.domain,
reverse('zinnia:tag_feed', args=[tag.name]))
}
|
python
|
{
"resource": ""
}
|
q26774
|
post_structure
|
train
|
def post_structure(entry, site):
"""
A post structure with extensions.
"""
author = entry.authors.all()[0]
return {'title': entry.title,
'description': six.text_type(entry.html_content),
'link': '%s://%s%s' % (PROTOCOL, site.domain,
entry.get_absolute_url()),
# Basic Extensions
'permaLink': '%s://%s%s' % (PROTOCOL, site.domain,
entry.get_absolute_url()),
'categories': [cat.title for cat in entry.categories.all()],
'dateCreated': DateTime(entry.creation_date.isoformat()),
'postid': entry.pk,
'userid': author.get_username(),
# Useful Movable Type Extensions
'mt_excerpt': entry.excerpt,
'mt_allow_comments': int(entry.comment_enabled),
'mt_allow_pings': (int(entry.pingback_enabled) or
int(entry.trackback_enabled)),
'mt_keywords': entry.tags,
# Useful Wordpress Extensions
'wp_author': author.get_username(),
'wp_author_id': author.pk,
'wp_author_display_name': author.__str__(),
'wp_password': entry.password,
'wp_slug': entry.slug,
'sticky': entry.featured}
|
python
|
{
"resource": ""
}
|
q26775
|
EntryRandom.get_redirect_url
|
train
|
def get_redirect_url(self, **kwargs):
"""
Get entry corresponding to 'pk' and
return the get_absolute_url of the entry.
"""
entry = Entry.published.all().order_by('?')[0]
return entry.get_absolute_url()
|
python
|
{
"resource": ""
}
|
q26776
|
MPTTFilteredSelectMultiple.media
|
train
|
def media(self):
"""
MPTTFilteredSelectMultiple's Media.
"""
js = ['admin/js/core.js',
'zinnia/admin/mptt/js/mptt_m2m_selectbox.js',
'admin/js/SelectFilter2.js']
return Media(js=[staticfiles_storage.url(path) for path in js])
|
python
|
{
"resource": ""
}
|
q26777
|
TagAutoComplete.render
|
train
|
def render(self, name, value, attrs=None, renderer=None):
"""
Render the default widget and initialize select2.
"""
output = [super(TagAutoComplete, self).render(name, value, attrs)]
output.append('<script type="text/javascript">')
output.append('(function($) {')
output.append(' $(document).ready(function() {')
output.append(' $("#id_%s").select2({' % name)
output.append(' width: "element",')
output.append(' maximumInputLength: 50,')
output.append(' tokenSeparators: [",", " "],')
output.append(' tags: %s' % json.dumps(self.get_tags()))
output.append(' });')
output.append(' });')
output.append('}(django.jQuery));')
output.append('</script>')
return mark_safe('\n'.join(output))
|
python
|
{
"resource": ""
}
|
q26778
|
TagAutoComplete.media
|
train
|
def media(self):
"""
TagAutoComplete's Media.
"""
def static(path):
return staticfiles_storage.url(
'zinnia/admin/select2/%s' % path)
return Media(
css={'all': (static('css/select2.css'),)},
js=(static('js/select2.js'),)
)
|
python
|
{
"resource": ""
}
|
q26779
|
PrefetchRelatedMixin.get_queryset
|
train
|
def get_queryset(self):
"""
Check if relation_names is correctly set and
do a prefetch related on the queryset with it.
"""
if self.relation_names is None:
raise ImproperlyConfigured(
"'%s' must define 'relation_names'" %
self.__class__.__name__)
if not isinstance(self.relation_names, (tuple, list)):
raise ImproperlyConfigured(
"%s's relation_names property must be a tuple or list." %
self.__class__.__name__)
return super(PrefetchRelatedMixin, self
).get_queryset().prefetch_related(*self.relation_names)
|
python
|
{
"resource": ""
}
|
q26780
|
get_context_first_matching_object
|
train
|
def get_context_first_matching_object(context, context_lookups):
"""
Return the first object found in the context,
from a list of keys, with the matching key.
"""
for key in context_lookups:
context_object = context.get(key)
if context_object:
return key, context_object
return None, None
|
python
|
{
"resource": ""
}
|
q26781
|
get_context_loop_positions
|
train
|
def get_context_loop_positions(context):
"""
Return the paginated current position within a loop,
and the non-paginated position.
"""
try:
loop_counter = context['forloop']['counter']
except KeyError:
return 0, 0
try:
page = context['page_obj']
except KeyError:
return loop_counter, loop_counter
total_loop_counter = ((page.number - 1) * page.paginator.per_page +
loop_counter)
return total_loop_counter, loop_counter
|
python
|
{
"resource": ""
}
|
q26782
|
CallableQuerysetMixin.get_queryset
|
train
|
def get_queryset(self):
"""
Check that the queryset is defined and call it.
"""
if self.queryset is None:
raise ImproperlyConfigured(
"'%s' must define 'queryset'" % self.__class__.__name__)
return self.queryset()
|
python
|
{
"resource": ""
}
|
q26783
|
base36
|
train
|
def base36(value):
"""
Encode int to base 36.
"""
result = ''
while value:
value, i = divmod(value, 36)
result = BASE36_ALPHABET[i] + result
return result
|
python
|
{
"resource": ""
}
|
q26784
|
backend
|
train
|
def backend(entry):
"""
Default URL shortener backend for Zinnia.
"""
return '%s://%s%s' % (
PROTOCOL, Site.objects.get_current().domain,
reverse('zinnia:entry_shortlink', args=[base36(entry.pk)]))
|
python
|
{
"resource": ""
}
|
q26785
|
BaseEntryChannel.get_context_data
|
train
|
def get_context_data(self, **kwargs):
"""
Add query in context.
"""
context = super(BaseEntryChannel, self).get_context_data(**kwargs)
context.update({'query': self.query})
return context
|
python
|
{
"resource": ""
}
|
q26786
|
tags_published
|
train
|
def tags_published():
"""
Return the published tags.
"""
from tagging.models import Tag
from zinnia.models.entry import Entry
tags_entry_published = Tag.objects.usage_for_queryset(
Entry.published.all())
# Need to do that until the issue #44 of django-tagging is fixed
return Tag.objects.filter(name__in=[t.name for t in tags_entry_published])
|
python
|
{
"resource": ""
}
|
q26787
|
entries_published
|
train
|
def entries_published(queryset):
"""
Return only the entries published.
"""
now = timezone.now()
return queryset.filter(
models.Q(start_publication__lte=now) |
models.Q(start_publication=None),
models.Q(end_publication__gt=now) |
models.Q(end_publication=None),
status=PUBLISHED, sites=Site.objects.get_current())
|
python
|
{
"resource": ""
}
|
q26788
|
EntryPublishedManager.on_site
|
train
|
def on_site(self):
"""
Return entries published on current site.
"""
return super(EntryPublishedManager, self).get_queryset().filter(
sites=Site.objects.get_current())
|
python
|
{
"resource": ""
}
|
q26789
|
EntryPublishedManager.search
|
train
|
def search(self, pattern):
"""
Top level search method on entries.
"""
try:
return self.advanced_search(pattern)
except Exception:
return self.basic_search(pattern)
|
python
|
{
"resource": ""
}
|
q26790
|
EntryPublishedManager.basic_search
|
train
|
def basic_search(self, pattern):
"""
Basic search on entries.
"""
lookup = None
for pattern in pattern.split():
query_part = models.Q()
for field in SEARCH_FIELDS:
query_part |= models.Q(**{'%s__icontains' % field: pattern})
if lookup is None:
lookup = query_part
else:
lookup |= query_part
return self.get_queryset().filter(lookup)
|
python
|
{
"resource": ""
}
|
q26791
|
EntryRelatedPublishedManager.get_queryset
|
train
|
def get_queryset(self):
"""
Return a queryset containing published entries.
"""
now = timezone.now()
return super(
EntryRelatedPublishedManager, self).get_queryset().filter(
models.Q(entries__start_publication__lte=now) |
models.Q(entries__start_publication=None),
models.Q(entries__end_publication__gt=now) |
models.Q(entries__end_publication=None),
entries__status=PUBLISHED,
entries__sites=Site.objects.get_current()
).distinct()
|
python
|
{
"resource": ""
}
|
q26792
|
EntryRelatedSitemap.items
|
train
|
def items(self):
"""
Get a queryset, cache infos for standardized access to them later
then compute the maximum of entries to define the priority
of each items.
"""
queryset = self.get_queryset()
self.cache_infos(queryset)
self.set_max_entries()
return queryset
|
python
|
{
"resource": ""
}
|
q26793
|
EntryRelatedSitemap.get_queryset
|
train
|
def get_queryset(self):
"""
Build a queryset of items with published entries and annotated
with the number of entries and the latest modification date.
"""
return self.model.published.annotate(
count_entries_published=Count('entries')).annotate(
last_update=Max('entries__last_update')).order_by(
'-count_entries_published', '-last_update', '-pk')
|
python
|
{
"resource": ""
}
|
q26794
|
EntryRelatedSitemap.cache_infos
|
train
|
def cache_infos(self, queryset):
"""
Cache infos like the number of entries published and
the last modification date for standardized access later.
"""
self.cache = {}
for item in queryset:
self.cache[item.pk] = (item.count_entries_published,
item.last_update)
|
python
|
{
"resource": ""
}
|
q26795
|
EntryRelatedSitemap.set_max_entries
|
train
|
def set_max_entries(self):
"""
Define the maximum of entries for computing the priority
of each items later.
"""
if self.cache:
self.max_entries = float(max([i[0] for i in self.cache.values()]))
|
python
|
{
"resource": ""
}
|
q26796
|
EntryRelatedSitemap.priority
|
train
|
def priority(self, item):
"""
The priority of the item depends of the number of entries published
in the cache divided by the maximum of entries.
"""
return '%.1f' % max(self.cache[item.pk][0] / self.max_entries, 0.1)
|
python
|
{
"resource": ""
}
|
q26797
|
TagSitemap.get_queryset
|
train
|
def get_queryset(self):
"""
Return the published Tags with option counts.
"""
self.entries_qs = Entry.published.all()
return Tag.objects.usage_for_queryset(
self.entries_qs, counts=True)
|
python
|
{
"resource": ""
}
|
q26798
|
TagSitemap.cache_infos
|
train
|
def cache_infos(self, queryset):
"""
Cache the number of entries published and the last
modification date under each tag.
"""
self.cache = {}
for item in queryset:
# If the sitemap is too slow, don't hesitate to do this :
# self.cache[item.pk] = (item.count, None)
self.cache[item.pk] = (
item.count, TaggedItem.objects.get_by_model(
self.entries_qs, item)[0].last_update)
|
python
|
{
"resource": ""
}
|
q26799
|
DirectoryPinger.run
|
train
|
def run(self):
"""
Ping entries to a directory in a thread.
"""
logger = getLogger('zinnia.ping.directory')
socket.setdefaulttimeout(self.timeout)
for entry in self.entries:
reply = self.ping_entry(entry)
self.results.append(reply)
logger.info('%s : %s', self.server_name, reply['message'])
socket.setdefaulttimeout(None)
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.