def index(request): select_detailed_source = SelecrSourceForm() source_points = Source.objects.exclude(point=None) searchform = SearchForm(request.GET) tagcloud = Tag.objects.cloud_for_model(Resource) qs = Resource.objects.filter(enabled=True).exclude(status="rejected") query = request.GET.get("q", None) if query != None: if query != "": qs = qs.filter(search_query_set(query)) else: blankquery = True objects = [] [objects.append(item) for item in qsfiltered] # treat querystring, remove page querystring = QueryDict(request.META.get("QUERY_STRING")) # handle pagination if "page" in request.GET: pageid = request.GET.get("page") if pageid: querystring._mutable = True del querystring["page"] querystring_nopage = querystring.urlencode() else: pageid = 1 querystring_nopage = request.META.get("QUERY_STRING") paginator = Paginator(objects, CONTENT_PER_PAGE) try: page_obj = paginator.page(pageid) except TypeError: page_obj = paginator.page(1) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) object_list = page_obj.object_list return render_to_response("index.html", locals(), context_instance=RequestContext(request)) else: # browse mode # featured list curricular_grades = CurricularGrade.objects.filter(parent=None) featured_list = ( qs.filter( # category__code='video', thumbnails__gt=0 ) .order_by("?") .all()[0:2] ) if featured_list.count() > 0: featured_list = featured_list.all() # tags tags_to_cloud = Tag.objects.usage_for_queryset(qs, counts=True) # [0:20] calculate_cloud(tags_to_cloud, steps=5, distribution=LOGARITHMIC) query = "" # latest additions latest_additions = Resource.objects.filter(status="installed").order_by("-created")[0:5] return render_to_response("index.html", locals(), context_instance=RequestContext(request))
def get_context_data(self, **kwargs): tags = DjangoPerson.skilltags.cloud(steps=5) calculate_cloud(tags, 5) context = super().get_context_data(**kwargs) context.update({ 'tags': tags, }) return context
def annotationview(request, asset_id, annot_id): annotation = get_object_or_404(SherdNote, pk=annot_id, asset=asset_id, asset__course=request.course) user = request.user if user.is_staff and request.GET.has_key('as'): user = get_object_or_404(User,username=request.GET['as']) if request.method in ("DELETE", "POST"): if request.method == "DELETE": redirect_to = reverse('asset-view', args=[asset_id]) elif request.method == "POST": redirect_to = '.' form = request.GET.copy() form['next'] = redirect_to request.GET = form return annotation_dispatcher(request, annot_id) readonly = False if annotation.author != request.user: readonly = True asset = annotation.asset global_annotation = asset.global_annotation(user) if global_annotation == annotation: return HttpResponseRedirect( reverse('asset-view', args=[asset_id])) form = AnnotationForm(instance=annotation, prefix="annotation") tags = calculate_cloud( Tag.objects.usage_for_queryset( asset.sherdnote_set.all(), counts=True)) user_tags = calculate_cloud( Tag.objects.usage_for_queryset( user.sherdnote_set.filter( asset__course=request.course), counts=True)) comments = Comment and Comment.objects.for_model(asset) or None return { 'annotation_form': form, 'asset': asset, 'comments': comments, 'annotation': annotation, 'global_annotation': global_annotation, 'global_annotation_form': GlobalAnnotationForm( instance=global_annotation, prefix="annotation"), 'tags': tags, 'space_viewer':user, 'user_tags': user_tags, 'readonly': readonly, }
def country_skill_cloud(request, country_code): country = get_object_or_404(Country, iso_code = country_code.upper()) tags = Tag.objects.cloud_for_model(DjangoPerson, steps=5, filters={ 'country': country }) calculate_cloud(tags, 5) return render(request, 'skills.html', { 'tags': tags, 'country': country })
def test_invalid_distribution(self): try: calculate_cloud(self.tags, steps=5, distribution='cheese') except ValueError as ve: self.assertEqual(str(ve), 'Invalid distribution algorithm specified: cheese.') except Exception as e: raise self.failureException('the wrong type of exception was raised: type [%s] value [%s]' %\ (str(type(e)), str(e))) else: raise self.failureException('a ValueError exception was supposed to be raised!')
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) tags = Tag.objects.cloud_for_model(DjangoPerson, steps=5, filters={ 'country': self.object, }) calculate_cloud(tags, 5) context.update({ 'tags': tags, }) return context
def document_view(request, document_id): if request.user.get_profile().is_lecturer: document = get_object_or_404(Document, Q(pk=document_id, is_lecturer_visible=True)) else: document = get_object_or_404(Document, Q(pk=document_id)) course = get_object_or_404(Course.objects.distinct('pk'), Q(pk=document.course.pk), Q(scopes__users__id=request.user.pk)) category = Category.objects.get(Q(pk=course.category.pk)) if document.is_etherpad: return HttpResponseRedirect(reverse("etherpad", args=[document.id])) comments = DocumentComment.objects.filter(document=document).order_by('pub_date') revisions = DocumentRevision.objects.filter(document=document).order_by('-pub_date')[1:] tags_raw = Tag.objects.usage_for_model(Document, counts=True) cloud_raw = calculate_cloud(tags_raw, steps=2) tags = document.get_tags() cloud = [] for tag in tags_raw: if tag in tags: cloud.insert(len(cloud) + 1, tag) if 'HTTP_USER_AGENT' in request.META: if request.META['HTTP_USER_AGENT'].find('MSIE') > 0: internet_explorer_warning = True return render_to_response("document.html", locals(), context_instance=RequestContext(request))
def pluginbrowser(request): if request.method == 'POST': #This form actually should not be submitted via POST. It is done by javascript function with AJAX call. #So this block of code will not be executed. form = PluginSearchForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/') else: _dbobjects = get_my_plugins(request.user) | get_shared_plugins(request.user) #get newest 10 plugins newest_plugin_list = _dbobjects.order_by('-created')[:10] #get recently updated 10 plugins #updated_plugin_list = _dbobjects.order_by('-lastmodified')[:10] updated_plugin_list = _dbobjects.exclude(created__gte=F('lastmodified')).order_by('-lastmodified')[:10] #^^^^^when a new plugin is saved, "created" is slightly newer than "lastmodified" popular_plugin_list = _dbobjects.filter(popularity__score__isnull=False).order_by('-popularity__score')[:10] form = PluginSearchForm() plugin_tags = calculate_cloud(Tag.objects.usage_for_queryset(_dbobjects, counts=True, min_count=2)) d = {'form': form, 'newest_plist': newest_plugin_list, 'updated_plist': updated_plugin_list, 'popular_plist': popular_plugin_list, 'anonymous_user': request.user.is_anonymous(), 'plugin_tags': plugin_tags, } return render_to_response('plugin/pluginlibrary.html', d)
def cloud_for_model(self, model, steps=4, distribution=LOGARITHMIC, filters=None, min_count=None): """ Obtain a list of tags associated with instances of the given Model, giving each tag a ``count`` attribute indicating how many times it has been used and a ``font_size`` attribute for use in displaying a tag cloud. ``steps`` defines the range of font sizes - ``font_size`` will be an integer between 1 and ``steps`` (inclusive). ``distribution`` defines the type of font size distribution algorithm which will be used - logarithmic or linear. It must be either ``tagging.utils.LOGARITHMIC`` or ``tagging.utils.LINEAR``. To limit the tags displayed in the cloud to those associated with a subset of the Model's instances, pass a dictionary of field lookups to be applied to the given Model as the ``filters`` argument. To limit the tags displayed in the cloud to those with a ``count`` greater than or equal to ``min_count``, pass a value for the ``min_count`` argument. """ tags = list(self.usage_for_model(model, counts=True, filters=filters, min_count=min_count)) return calculate_cloud(tags, steps, distribution)
def tag_index(request, template_name="tagging_ext/index.html", min_size=0, limit=100): query = """ SELECT tag_item.tag_id as tag_id, COUNT(tag_item.tag_id) as counter FROM tagging_taggeditem as tag_item INNER JOIN tagging_tag as tag ON (tag.id = tag_item.tag_id) GROUP BY tag.name,tag_id HAVING COUNT(tag.name) > %s ORDER BY tag.name LIMIT %s """ cursor = connection.cursor() cursor.execute(query, [min_size, limit]) tags = [] for row in cursor.fetchall(): try: tag = Tag.objects.get(id=row[0]) except ObjectDoesNotExist: continue if ' ' in tag.name: continue tag.count = row[1] tags.append(tag) tags = calculate_cloud(tags, steps=5, distribution=LOGARITHMIC) return render_to_response(template_name, {'tags': tags}, context_instance=RequestContext(request))
def get_tagcloud_intersection(agree_issues, disagree_issues): try : agree_tags = Tag.objects.usage_for_model(Issue, counts=True, filters=dict(id__in=agree_issues)) except EmptyResultSet: agree_tags = [] try: disagree_tags = Tag.objects.usage_for_model(Issue, counts=True, filters=dict(id__in=disagree_issues)) except EmptyResultSet: disagree_tags = [] tags_dagree= dict((tag.name, tag) for tag in disagree_tags) all_tags = [] # loop over al for tags, look if tag also exists in disagree tag # if so add a status with 'conflict' to the tag. # agree_tags have 'agree' status # disagree_tags have no status. for a_tag in agree_tags: a_tag.status = 'agree' if tags_dagree.has_key(a_tag.name): d_tag = tags_dagree[a_tag.name] d_tag.count = d_tag.count + a_tag.count d_tag.status = 'conflict' all_tags.append(d_tag) tags_dagree.pop(a_tag.name) else: all_tags.append(a_tag) all_tags.extend(tags_dagree.values()) return calculate_cloud(all_tags)
def render(self, djp, wrapper, prefix, for_model = None, steps = 4, min_count = None, **kwargs): try: formodel = ContentType.objects.get(id = int(for_model)).model_class() except: return u'' steps = int(steps) if min_count: min_count = int(min_count) site = get_site(djp.request.path) appmodel = site.for_model(formodel) tags = self.get_tags(**kwargs) if tags: query = TaggedItem.objects.get_by_model(formodel,tags) query = self.model.objects.usage_for_queryset(query, counts=True) tags = calculate_cloud(query) else: tags = Tag.objects.cloud_for_model(formodel, steps = steps, min_count = min_count) request = djp.request for tag in tags: try: tag.url = appmodel.tagurl(request, tag.name) except: tag.url = None if tag.count == 1: tag.times = 'time' else: tag.times = 'times' c = {'tags': tags} return loader.render_to_string(['bits/tag_cloud.html', 'djpcms/bits/tag_cloud.html'],c)
def tags(request): all_tags = {} # Want 2.7 for the collections.Counter :( def update_tags(tag): existing = all_tags.get(tag.name, None) if existing: existing.count += tag.count else: all_tags[tag.name] = tag scraper_tags = Tag.objects.usage_for_model(Scraper, counts=True, filters={'privacy_status':'public', 'privacy_status':'visible'}) view_tags = Tag.objects.usage_for_model(View, counts=True, filters={'privacy_status':'public', 'privacy_status':'visible'}) for tag in itertools.chain(scraper_tags, view_tags): update_tags(tag) # Use UserCodeRole objects to get code objects that are private but # accessible to this user and then use update_tags to update the # dictionary if request.user.is_authenticated(): privatescraper_ids = [u.code.id for u in UserCodeRole.objects.filter(code__privacy_status='private', user=request.user)] qs = Code.objects.filter(pk__in=privatescraper_ids) extra_tags = Tag.objects.usage_for_queryset(qs, counts=True) for tag in extra_tags: update_tags(tag) tags = calculate_cloud(all_tags.values(), steps=4, distribution=LOGARITHMIC) return render_to_response('frontend/tags.html', {'tags':tags}, context_instance=RequestContext(request))
def get_tag_cloud(context, steps=6, template='zinnia/tags/tag_cloud.html'): """Return a cloud of published tags""" tags = Tag.objects.usage_for_queryset( Entry.published.all(), counts=True) return {'template': template, 'tags': calculate_cloud(tags, steps), 'context_tag': context.get('tag')}
def container_view(request): assets = [a for a in Asset.objects.filter(course=request.course).order_by('title') if a not in request.course.asset_set.archives()] from tagging.models import Tag all_tags = Tag.objects.usage_for_queryset( SherdNote.objects.filter( asset__course=request.course), counts=True) all_tags.sort(lambda a,b:cmp(a.name.lower(),b.name.lower())) all_tags = calculate_cloud(all_tags) for fil in filter_by: filter_value = request.GET.get(fil) if filter_value: assets = [asset for asset in assets if filter_by[fil](asset, filter_value)] active_filters = dict((filter, request.GET.get(filter)) for filter in filter_by if filter in request.GET) return { 'assets':assets, 'tags': all_tags, 'active_filters': active_filters, 'space_viewer':request.user, }
def tag_cloud(self): "Returns instance tags annotated with tag cloud weights" # Just using self.tags doesn't aggregate properly (the only # matching item is self) tags = (Tag.objects .filter(pk__in=[t.pk for t in self.tags]) .annotate(count=Count('items'))) return calculate_cloud(tags)
def get_tag_cloud(context, steps=6, template='zinnia/tags/tag_cloud.html'): """Return a cloud of published tags""" tags = Tag.objects.usage_for_queryset(Entry.published.all(), counts=True) return { 'template': template, 'tags': calculate_cloud(tags, steps), 'context_tag': context.get('tag') }
def container_view(request): """for all class assets view at /asset/ OPTIMIZATION: What we need: asset: primary label, thumb.url tags {name} project: collaboration.get_parent, feedback_discussion status (from collaboration) attribution """ #extra() is case-insensitive order hack #http://scottbarnham.com/blog/2007/11/20/case-insensitive-ordering-with-django-and-postgresql/ archives = list(request.course.asset_set.archives()) assets = [ a for a in Asset.objects.filter(course=request.course).extra( select={ 'lower_title': 'lower(assetmgr_asset.title)' }).select_related().order_by('lower_title') if a not in archives ] asset_ids = [a.id for a in assets] thumbs = dict([ (th.asset_id, th.url) for th in Source.objects.filter(label='thumb', asset__in=asset_ids) ]) primaries = dict([ (p.asset_id, p) for p in Source.objects.filter(primary=True, asset__in=asset_ids) ]) #import pdb;pdb.set_trace() for a in assets: a._primary_cache = primaries[a.id] a._thumb_url = thumbs.get(a.id, None) from tagging.models import Tag all_tags = Tag.objects.usage_for_queryset( SherdNote.objects.filter(asset__course=request.course), counts=True) all_tags.sort(lambda a, b: cmp(a.name.lower(), b.name.lower())) all_tags = calculate_cloud(all_tags) for fil in filter_by: filter_value = request.GET.get(fil) if filter_value: assets = [ asset for asset in assets if filter_by[fil](asset, filter_value) ] active_filters = get_active_filters(request) return { 'assets': assets, 'tags': all_tags, 'active_filters': active_filters, 'space_viewer': request.user, 'space_owner': None, 'is_faculty': request.course.is_faculty(request.user), }
def cloud_for_queryset(self, queryset, steps=2, distribution=LOGARITHMIC, min_count=None): """ returns the tag cloud for the given queryset See: https://code.google.com/p/django-tagging/issues/detail?id=137 """ tags = list( Tag.objects.usage_for_queryset(queryset, counts=True, min_count=min_count) ) return calculate_cloud(tags, steps, distribution)
def get_tagcloud_issues(issues): id_issues = issues.values('id') issue_tags = Tag.objects.usage_for_model(Issue, counts=True, filters=dict(id__in=id_issues)) return calculate_cloud( issue_tags, steps=7, )
def cloud_for_queryset(self, queryset, steps=4, distribution=LOGARITHMIC, min_count=None): tags = list( self.usage_for_queryset(queryset, counts=True, min_count=min_count)) return calculate_cloud(tags, steps, distribution)
def get_user_tag_cloud(user): votes = Vote.objects.get_user_votes(user, Model=Issue) votes = votes.values_list('object_id') try : tags = Tag.objects.usage_for_model(Issue, counts=True, filters=dict(id__in=votes)) except EmptyResultSet: tags = [] return calculate_cloud(tags)
def get_member_data(self, member): bills_tags = Tag.objects.usage_for_queryset(member.bills.all(),counts=True) tag_cloud = map(lambda x: dict(size=x.font_size, count=x.count, name=x.name), calculate_cloud(bills_tags)) bills = map(lambda b: dict(title=b.full_title, url=b.get_absolute_url(), stage=b.stage, stage_text=b.get_stage_display()), member.bills.all()) return DictStruct(id=member.id, tag_cloud=tag_cloud,bills=bills)
def tagged_items(request, slug, tags=None): """ View items tagged in project """ project = get_object_or_404(Project, slug=slug) project_type = ContentType.objects.get_for_model(project) tag_list = tags.split("+") querysets = [ Task.objects.select_related().filter(project=project), Thread.objects.filter(content_type__pk=project_type.pk, object_id=project.id) ] all_tags = [] qs_items = [] for query in querysets: qs = TaggedItem.objects.get_intersection_by_model(query, tag_list) if qs: qs_tags = Tag.objects.usage_for_queryset(qs, counts=True) all_tags.extend(qs_tags) qs_items.extend(qs) # Order items and put in cloud all_tags = reduce(lambda l, x: x not in l and l.append(x) or l, all_tags, []) tags = calculate_cloud(all_tags, 4, LOGARITHMIC) # Tagged items tagged_items = [] for item in qs_items: item.type = item._meta.module_name if hasattr(item, "created_at"): item.sort = item.created_at else: item.sort = item.latest_message_time tagged_items.append(item) tagged_items.sort(key=lambda x: x.sort) # Complile tags selected_tags = [] tag_url = '' for item in tag_list: tag_url += item + '+' name = Tag.objects.get(name=item) tags.remove(name) selected_tags.append(name) return direct_to_template(request, template='blproject/tagged_item_list.html', extra_context={ 'tag_cloud': tags, 'tag_url': tag_url, 'selected_tags': selected_tags, 'tagged_items': tagged_items, 'project': project })
def get_context_data(self, **kwargs): kwargs = super(AlbumTagRessourcesView, self).get_context_data(**kwargs) tags_q = Tag.objects.usage_for_queryset(self.get_ressources_queryset(), min_count=1) tags_q = calculate_cloud(tags_q, steps=6) kwargs.update({ 'tag_object': self.tag_object, 'ressources_tags': tags_q, }) return kwargs
def test_linear_distribution(self): sizes = {} for tag in calculate_cloud(self.tags, steps=5, distribution=LINEAR): sizes[tag.font_size] = sizes.get(tag.font_size, 0) + 1 # This isn't a pre-calculated test, just making sure it's consistent self.assertEquals(sizes[1], 97) self.assertEquals(sizes[2], 12) self.assertEquals(sizes[3], 7) self.assertEquals(sizes[4], 2) self.assertEquals(sizes[5], 4)
def test_default_distribution(self): sizes = {} for tag in calculate_cloud(self.tags, steps=5): sizes[tag.font_size] = sizes.get(tag.font_size, 0) + 1 # This isn't a pre-calculated test, just making sure it's consistent self.assertEquals(sizes[1], 48) self.assertEquals(sizes[2], 30) self.assertEquals(sizes[3], 19) self.assertEquals(sizes[4], 15) self.assertEquals(sizes[5], 10)
def index(request): if request.user.is_authenticated(): #User should have that after authorisation #request.user.user_permissions.add('User') pass #latest_addons = Addon.objects.all().order_by('-pub_date')[:5] recomended_addons = Addon.objects.all().order_by('-rating')[:4] categories = Category.objects.all() tags = Tag.objects.usage_for_model(Addon, counts=True) tag_cloud = utils.calculate_cloud(tags, steps=5, distribution=utils.LOGARITHMIC) return render_to_response('main/index.html', {'tag_cloud': tag_cloud, 'recomended_addons': recomended_addons, 'categories': categories, 'user': request.user, 'site_name': Site.objects.get_current().name})
def get_user_tag_cloud(user): votes = Vote.objects.get_user_votes(user, Model=Issue) votes = votes.values_list('object_id') try: tags = Tag.objects.usage_for_model(Issue, counts=True, filters=dict(id__in=votes)) except EmptyResultSet: tags = [] return calculate_cloud(tags)
def get_context_data(self, **kwargs): kwargs = super(AlbumDetailView, self).get_context_data(**kwargs) tags_q = Tag.objects.usage_for_queryset(self.object_list, min_count=1) tags_q = calculate_cloud(tags_q, steps=6) kwargs.update({ # Filter ressource tags from the ressource list queryset # Behavior to watch, maybe at this step, the queryset has been limited by the paginator 'ressources_tags': tags_q, }) return kwargs
def get_member_data(self, member): bills_tags = Tag.objects.usage_for_queryset(member.bills.all(), counts=True) tag_cloud = map( lambda x: dict(size=x.font_size, count=x.count, name=x.name), calculate_cloud(bills_tags)) bills = map( lambda b: dict(title=b.full_title, url=b.get_absolute_url(), stage=b.stage, stage_text=b.get_stage_display()), member.bills.all()) return DictStruct(id=member.id, tag_cloud=tag_cloud, bills=bills)
def core_get_tag_cloud(context, steps=6, min_count=None, max_num_tags=2, template='zinnia/tags/tag_cloud.html'): """ Return a cloud of published tags. """ tags = Tag.objects.usage_for_queryset( Entry.published.all(), counts=True, min_count=min_count) tags = sorted(tags, key=lambda t: t.count, reverse=True) tags = list(islice(tags, max_num_tags)) return {'template': template, 'tags': calculate_cloud(tags, steps), 'context_tag': context.get('tag')}
def asset_workspace(request, asset_id): asset = get_object_or_404(Asset, pk=asset_id, course=request.course) user = request.user if user.is_staff and request.GET.has_key('as'): user = get_object_or_404(User,username=request.GET['as']) global_annotation = asset.global_annotation(user) tags = calculate_cloud( Tag.objects.usage_for_queryset( asset.sherdnote_set.all(), counts=True)) user_tags = calculate_cloud( Tag.objects.usage_for_queryset( user.sherdnote_set.filter( asset__course=request.course ), counts=True)) comments = Comment.objects.for_model(asset) discussions = Clumper(DiscussionIndex.with_permission( request, #order, to be easily groupable by discussion DiscussionIndex.objects.filter(asset=asset).order_by('-modified') ), group_by='discussion') return { 'asset': asset, 'comments': comments, 'global_annotation': global_annotation, 'tags': tags, 'space_viewer':user, 'user_tags': user_tags, 'annotation_form': AnnotationForm(prefix="annotation"), 'global_annotation_form': GlobalAnnotationForm(instance=global_annotation, prefix="annotation"), 'discussions' : discussions }
def your_records(request, user_name): c = request.course in_course_or_404(user_name, c) today = datetime.date.today() user = get_object_or_404(User, username=user_name) editable = (user==request.user) assets = annotated_by(Asset.objects.filter(course=c), user, include_archives=c.is_faculty(user) ) projects = Project.get_user_projects(user, c) if not editable: projects = projects.filter(submitted=True) projects = projects.order_by('-modified') for fil in filter_by: filter_value = request.GET.get(fil) if filter_value: assets = [asset for asset in assets if filter_by[fil](asset, filter_value, user)] tags = calculate_cloud(Tag.objects.usage_for_queryset( user.sherdnote_set.filter( asset__course=c), counts=True)) active_filters = dict((filter, request.GET.get(filter)) for filter in filter_by if filter in request.GET) #bad language, we should change this to user_of_assets or something space_viewer = user if request.GET.has_key('as') and request.user.is_staff: space_viewer = get_object_or_404(User, username=request.GET['as']) return { 'assets' : assets, 'projects' : projects, 'tags' : tags, 'dates' : {'today':'today', 'yesterday':'yesterday', 'lastweek':'within the last week'}, 'space_owner' : user, 'space_viewer' : space_viewer, 'editable' : editable, 'active_filters': active_filters, }
def container_view(request): """for all class assets view at /asset/ OPTIMIZATION: What we need: asset: primary label, thumb.url tags {name} project: collaboration.get_parent, feedback_discussion status (from collaboration) attribution """ #extra() is case-insensitive order hack #http://scottbarnham.com/blog/2007/11/20/case-insensitive-ordering-with-django-and-postgresql/ archives = list(request.course.asset_set.archives()) assets = [a for a in Asset.objects.filter(course=request.course).extra( select={'lower_title': 'lower(assetmgr_asset.title)'} ).select_related().order_by('lower_title') if a not in archives] asset_ids = [a.id for a in assets] thumbs = dict([(th.asset_id,th.url) for th in Source.objects.filter(label='thumb', asset__in=asset_ids)]) primaries = dict([(p.asset_id,p) for p in Source.objects.filter(primary=True, asset__in=asset_ids)]) #import pdb;pdb.set_trace() for a in assets: a._primary_cache = primaries[a.id] a._thumb_url = thumbs.get(a.id,None) from tagging.models import Tag all_tags = Tag.objects.usage_for_queryset( SherdNote.objects.filter( asset__course=request.course), counts=True) all_tags.sort(lambda a,b:cmp(a.name.lower(),b.name.lower())) all_tags = calculate_cloud(all_tags) for fil in filter_by: filter_value = request.GET.get(fil) if filter_value: assets = [asset for asset in assets if filter_by[fil](asset, filter_value)] active_filters = get_active_filters(request) return { 'assets':assets, 'tags': all_tags, 'active_filters': active_filters, 'space_viewer':request.user, 'space_owner':None, 'is_faculty':request.course.is_faculty(request.user), }
def testTagClouds(self): tags = [] for line in open(os.path.join(os.path.dirname(__file__), 'tags.txt')).readlines(): name, count = line.rstrip().split() tag = Tag(name=name) tag.count = int(count) tags.append(tag) sizes = {} for tag in calculate_cloud(tags, steps=5): sizes[tag.font_size] = sizes.get(tag.font_size, 0) + 1 # This isn't a pre-calculated test, just making sure it's consistent self.assertEqual({1: 48, 2: 30, 3: 19, 4: 15, 5: 10}, sizes) sizes = {} for tag in calculate_cloud(tags, steps=5, distribution=LINEAR): sizes[tag.font_size] = sizes.get(tag.font_size, 0) + 1 # This isn't a pre-calculated test, just making sure it's consistent self.assertEqual({1: 97, 2: 12, 3: 7, 4: 2, 5: 4}, sizes) self.assertRaises(ValueError, calculate_cloud, tags, steps=5, distribution='cheese')
def blog_index(request, blog, page=1): """ Blog front page. Displays latest blog posts, excluding future posts. Paginated. """ blog_tags = Tag.objects.usage_for_model(Entry, counts=True, filters=dict(blog__slug=blog)) cloud = calculate_cloud(blog_tags) blog_obj = get_object_or_404(Blog, slug=blog) qs = Entry.objects.published_on_blog(blog).order_by('-pub_date') c = {'blog': blog_obj, 'blog_tags': cloud} return object_list(request, queryset=qs, paginate_by=10, allow_empty=False, page=page, extra_context=c)
def cloud_for_queryset(self, queryset, steps=2, distribution=LOGARITHMIC, min_count=None): """ returns the tag cloud for the given queryset See: https://code.google.com/p/django-tagging/issues/detail?id=137 """ tags = list( Tag.objects.usage_for_queryset(queryset, counts=True, min_count=min_count)) return calculate_cloud(tags, steps, distribution)
def asset_accoutrements(request, asset, user, annotation_form): global_annotation = asset.global_annotation(user, auto_create=False) if global_annotation: global_annotation_form = GlobalAnnotationForm( instance=global_annotation, prefix="annotation") else: global_annotation_form = GlobalAnnotationForm(prefix="annotation") tags = calculate_cloud( Tag.objects.usage_for_queryset(asset.sherdnote_set.all(), counts=True)) user_tags = calculate_cloud( Tag.objects.usage_for_queryset( user.sherdnote_set.filter(asset__course=request.course), counts=True)) comments = Comment and Comment.objects.for_model(asset) or None discussions = Clumper( DiscussionIndex.with_permission( request, #order, to be easily groupable by discussion DiscussionIndex.objects.filter(asset=asset).order_by('-modified')), group_by='discussion') return { 'asset': asset, 'comments': comments, 'global_annotation': global_annotation, 'tags': tags, 'space_viewer': user, 'user_tags': user_tags, 'annotation_form': annotation_form, 'global_annotation_form': global_annotation_form, 'discussions': discussions }
def get_tag_cloud_su_sensitive(context, steps=6, min_count=None, template='zinnia/tags/tag_cloud.html'): if context['request'].user.is_superuser: queryset = Entry.objects.all() else: queryset = Entry.published.all() tags = Tag.objects.usage_for_queryset(queryset, counts=True, min_count=min_count) return { 'template': template, 'tags': calculate_cloud(tags, steps), 'context_tag': context.get('tag') }
def get_member_data(self, member): bills_tags = Tag.objects.usage_for_queryset(member.bills.all(), counts=True) # we'll use getattr for font_size, as it might not always be there # This prevents the need of using a forked django-tagging, and go # upstream tag_cloud = [{ 'size': getattr(x, 'font_size', 1), 'count':x.count, 'name':x.name} for x in calculate_cloud(bills_tags)] bills = map(lambda b: dict(title=b.full_title, url=b.get_absolute_url(), stage=b.stage, stage_text=b.get_stage_display()), member.bills.all()) return DictStruct(id=member.id, tag_cloud=tag_cloud,bills=bills)
def tag_index(request, template_name="tagging_ext/index.html", *args, **kw): query = """ SELECT tag.name as name, COUNT(tag_item.tag_id) as counter, tag_item.tag_id as tag_id FROM tagging_taggeditem as tag_item INNER JOIN tagging_tag as tag ON (tag.id = tag_item.tag_id) GROUP BY tag.name, tag_id ORDER BY tag.name """ cursor = connection.cursor() cursor.execute(query) tags = calculate_cloud([TagInTheCloud(*row) for row in cursor], steps=5, distribution=LOGARITHMIC) return render_to_response(template_name, {'tags': tags}, context_instance=RequestContext(request))
def dashboard(request): """ Brief snippets of all interesting site features """ all_subscriptions = SubscriptionUser.objects.filter(user=request.user) subscriptions = all_subscriptions.filter(active=True) inactive_subscriptions = all_subscriptions.filter(active=False) for subscription in subscriptions: subscription.count = max(1, subscription.is_fresh(request.user)) subscriptions = calculate_cloud(subscriptions) return render( request, "subscriptions/dashboard.html", { "subscriptions": subscriptions, "inactive_subscriptions": inactive_subscriptions, "feed": get_hits(request.user), })
def annotations_collection_fragment(request,username=None): """username is WAY overloaded username='******' : just give me the selection menu username=None : give me all assets for the class username=<username> : all username assets """ rv = {'space_viewer':request.user, 'space_owner':False, #indicates we want the whole class (None is no one) 'page_in_edit_mode': request.GET.has_key('edit_mode'), } if username != 'none': if username \ and (request.user.username != username or request.course.is_true_member(request.user)): rv['space_owner'] = in_course_or_404(username, request.course) #assets = annotated_by(Asset.objects.filter(course=request.course), # space_owner) note_query = rv['space_owner'].sherdnote_set.filter(asset__course=request.course) else: #assets = Asset.objects.filter(course=request.course) note_query = SherdNote.objects.filter(asset__course=request.course) rv['tags'] = calculate_cloud(Tag.objects.usage_for_queryset(note_query, counts=True)) #all_tags.sort(lambda a,b:cmp(a.name.lower(),b.name.lower())) #all_tags = calculate_cloud(all_tags) filter_by = ('tag','modified') for fil in filter_by: filter_value = request.GET.get(fil) if filter_value: s_filter = getattr(SherdNote.objects,'%s_filter'%fil) note_query = s_filter(filter_value,note_query) #until asset_table.html can work off the notes objects instead of the assets list rv['assets'] = Asset.objects.filter(id__in = note_query.values_list('asset',flat=True)) rv['active_filters'] = get_active_filters(request) rv['dates'] = (('today','today'), ('yesterday','yesterday'), ('lastweek','within the last week'), ) return rv
def cloud_for_model( self, model, steps=4, distribution=LOGARITHMIC, filters=None, min_count=None, limit=None, ): """ Obtain a list of tags associated with instances of the given Model, giving each tag a ``count`` attribute indicating how many times it has been used and a ``font_size`` attribute for use in displaying a tag cloud. ``steps`` defines the range of font sizes - ``font_size`` will be an integer between 1 and ``steps`` (inclusive). ``distribution`` defines the type of font size distribution algorithm which will be used - logarithmic or linear. It must be either ``tagging.utils.LOGARITHMIC`` or ``tagging.utils.LINEAR``. To limit the tags displayed in the cloud to those associated with a subset of the Model's instances, pass a dictionary of field lookups to be applied to the given Model as the ``filters`` argument. To limit the tags displayed in the cloud to those with a ``count`` greater than or equal to ``min_count``, pass a value for the ``min_count`` argument. To limite the amount of tags displayed in the cloud, pass a value for the ``limit`` argument. """ tags = list( self.usage_for_model( model, counts=True, filters=filters, min_count=min_count, limit=limit, ), ) return calculate_cloud(tags, steps, distribution)
def render(self, context): object = self.object.resolve(context) user = self.user.resolve(context) if self.include: if not user.is_anonymous(): ownedwrapper = OwnedWrapper.objects.get_for_object( user, object) context[self.var_name] = Tag.objects.get_for_object( ownedwrapper) else: qs = OwnedWrapper.objects.filter(object_id=object.id, content_type=OwnedWrapper.t( object.__class__)) if not user.is_anonymous(): qs = qs.exclude(user=user) tags = list(Tag.objects.usage_for_queryset(qs, counts=True)) context[self.var_name] = calculate_cloud(tags) return ''
def website_detail(request, slug): w = get_object_or_404(Website, slug=slug) if w.tags: try: related_tags = Tag.objects.related_for_model(w.tags, Website, counts=True) tag_cloud = calculate_cloud(related_tags) except: tag_cloud = [] else: tag_cloud = [] return render_to_response( 'websites/website_detail.html', RequestContext(request, { 'object': w, 'related_tag_cloud': tag_cloud, }))
def index(request): if request.user.is_authenticated(): #User should have that after authorisation #request.user.user_permissions.add('User') pass #latest_addons = Addon.objects.all().order_by('-pub_date')[:5] recomended_addons = Addon.objects.all().order_by('-rating')[:4] categories = Category.objects.all() tags = Tag.objects.usage_for_model(Addon, counts=True) tag_cloud = utils.calculate_cloud(tags, steps=5, distribution=utils.LOGARITHMIC) return render_to_response( 'main/index.html', { 'tag_cloud': tag_cloud, 'recomended_addons': recomended_addons, 'categories': categories, 'user': request.user, 'site_name': Site.objects.get_current().name })
def get_tag_cloud(cls, user): """Get current tags available to user. @param user: user to get current items for @type user: auth.models.user @return: current tags available to user @rtype: list of tagging.Tag """ # without if-construct sqlite3 barfs on AnonymousUser if user.id: qs = (Q(user=user) | Q(is_public=True)) & Q(is_current=True) else: qs = Q(is_public=True) & Q(is_current=True) if cls: tags = Tag.objects.usage_for_queryset(cls.objects.filter(qs), counts=True) else: tags = Tag.objects.usage_for_queryset( repository.models.Data.objects.filter(qs & Q(is_approved=True)), counts=True) tags.extend(Tag.objects.usage_for_queryset( repository.models.Task.objects.filter(qs), counts=True)) tags.extend(Tag.objects.usage_for_queryset( repository.models.Method.objects.filter(qs), counts=True)) current = {} for t in tags: if not t.name in current: current[t.name] = t else: current[t.name].count += t.count tags = current.values() if tags: cloud = calculate_cloud(tags, steps=2) random.seed(hash(cls)+len(tags)) random.shuffle(cloud) else: cloud = None return cloud
def tags(request): all_tags = {} # Python 2.7 would clean this up by using collections.Counter def update_tags(tag): existing = all_tags.get(tag.name, None) if existing: existing.count += tag.count else: all_tags[tag.name] = tag scraper_tags = Tag.objects.usage_for_model(Scraper, counts=True, filters={'privacy_status':'public'}) view_tags = Tag.objects.usage_for_model(View, counts=True, filters={'privacy_status':'public'}) for tag in itertools.chain(scraper_tags, view_tags): update_tags(tag) tags = calculate_cloud(all_tags.values(), steps=4, distribution=LOGARITHMIC) return render_to_response('frontend/tags.html', {'tags':tags}, context_instance=RequestContext(request))
def mock_analysis_space(request): user_tags = calculate_cloud( Tag.objects.usage_for_queryset( request.user.sherdnote_set.filter(asset__course=request.course), counts=True)) sources = sources_from_args(request) title = getattr(request, request.method).get('title', '') mock_asset = dict( title=title, source_set={'all': sources.values()}, html_source={'url': request.GET.get('url', None)}, ) return { 'mock': True, 'asset': mock_asset, 'user_tags': user_tags, 'annotation_form': AnnotationForm(prefix="annotation"), 'global_annotation_form': GlobalAnnotationForm(prefix="annotation"), }
def render(self, context): tags = Tag.objects.annotate(count=Count("items")).exclude(count=0) context[self.context_var] = calculate_cloud(tags, **self.kwargs) return ''
def blogcloud(): tags = Tag.objects.usage_for_model(Entry, counts=True) tags = tagutils.calculate_cloud(tags) return {'tags': tags}
def test_invalid_distribution(self): try: calculate_cloud(self.tags, steps=5, distribution='cheese') except ValueError, ve: self.assertEquals( str(ve), 'Invalid distribution algorithm specified: cheese.')
def get_tag_cloud(steps=6, template='objectapp/tags/tag_cloud.html'): """Return a cloud of published tags""" tags = Tag.objects.usage_for_queryset(Gbobject.published.all(), counts=True) return {'template': template, 'tags': calculate_cloud(tags, steps)}