Category x Rater -> #
485349
public static Map<Object, int[]> countAnnotationsPerCategory(
			final ICodingAnnotationStudy study) {
		Map<Object, int[]> result = new HashMap<Object, int[]>();
		for (ICodingAnnotationItem item : study.getItems()) {
            for (IAnnotationUnit unit : item.getUnits()) {
				Object category = unit.getCategory();
				if (category == null) {
                    continue;
                }

				int[] counts = result.get(category);
				if (counts == null) {
                    counts = new int[study.getRaterCount()];
                }
				counts[unit.getRaterIdx()]++;
				result.put(category, counts);
			}
        }
		return result;
	}
993287
def get_scores(self, *args):
		'''
		
		'''
		if self.tdf_ is None:
			raise Exception("Use set_category_name('category name', ['not category name', ...]) " +
			                "to set the category of interest")

		avgdl = self.tdf_.sum(axis=0).mean()

		def idf(cat):
			# Number of categories with term
			n_q = (self.tdf_ > 0).astype(int).max(axis=1).sum()
			N = len(self.tdf_)
			return (N - n_q + 0.5) / (n_q + 0.5)

		def length_adjusted_tf(cat):
			tf = self.tdf_[cat]
			dl = self.tdf_[cat].sum()
			return ((tf * (self.k1 + 1))
			        / (tf + self.k1 * (1 - self.b + self.b * (dl / avgdl))))

		def bm25_score(cat):
			return - length_adjusted_tf(cat) * np.log(idf(cat))

		scores = bm25_score('cat') - bm25_score('ncat')
		return scores
750554
def get_scores_and_p_values(self, tdm, category):
		'''
		
		'''
		X = tdm._X
		y = self._make_response_variable_1_or_negative_1(category, tdm)
		pX = X / X.sum(axis=1)
		ansX = self._anscombe_transform(pX.copy())
		B, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var\
			= lsqr(A=ansX, b=y, calc_var=True)
1293002
def get_rating_for_user(self, user, ip_address=None, cookies={}):
        """"""
        kwargs = dict(
            content_type    = self.get_content_type(),
            object_id       = self.instance.pk,
            key             = self.field.key,
        )

        if not (user and user.is_authenticated()):
            if not ip_address:
                raise ValueError('``user`` or ``ip_address`` must be present.')
            kwargs['user__isnull'] = True
            kwargs['ip_address'] = ip_address
        else:
            kwargs['user'] = user
        
        use_cookies = (self.field.allow_anonymous and self.field.use_cookies)
        if use_cookies:
            # TODO: move 'vote-%d.%d.%s' to settings or something
            cookie_name = 'vote-%d.%d.%s' % (kwargs['content_type'].pk, kwargs['object_id'], kwargs['key'][:6],) # -> md5_hexdigest?
            cookie = cookies.get(cookie_name)
            if cookie:    
                kwargs['cookie'] = cookie
            else:
                kwargs['cookie__isnull'] = True
            
        try:
            rating = Vote.objects.get(**kwargs)
            return rating.score
        except Vote.MultipleObjectsReturned:
            pass
        except Vote.DoesNotExist:
            pass
        return
1350553
def category_links(categories)
      base_dir = @context.registers[:site].config['category_dir']
      categories = categories.sort!.map do |category|
        category_dir = GenerateCategories.category_dir(base_dir, category)
        # Make sure the category directory begins with a slash.
        category_dir = "/#{category_dir}" unless category_dir =~ /^\//
        "<a class='category' href='#{category_dir}/'>#{category}</a>"
      end

      case categories.length
      when 0
        ""
      when 1
        categories[0].to_s
      else
        categories.join(', ')
      end
    end
251187
def rate(self, rating):
        
        parameters = {
            'voterid': self._current_user_id,
            'target_userid': self.id,
            'type': 'vote',
            'cf': 'profile2',
            'target_objectid': 0,
            'vote_type': 'personality',
            'score': rating,
        }
        response = self._session.okc_post('vote_handler',
                                          data=parameters)
        response_json = response.json()
        log_function = log.info if response_json.get('status', False) \
                       else log.error
        log_function(simplejson.dumps({'rate_response': response_json,
                                       'sent_parameters': parameters,
                                       'headers': dict(self._session.headers)}))
        self.refresh(reload=False)
897426
def rank(idx, dim):
    """"""
    idxm = multi_index(idx, dim)
    out = 0
    while idxm[-1:] == (0,):
        out += 1
        idxm = idxm[:-1]
    return out
892085
def get_top_level_categories(parser, token):
    
    bits = token.split_contents()
    usage = 'Usage: {%% %s [using "app.Model"] as <variable> %%}' % bits[0]
    if len(bits) == 3:
        if bits[1] != 'as':
            raise template.TemplateSyntaxError(usage)
        varname = bits[2]
        model = "categories.category"
    elif len(bits) == 5:
        if bits[1] not in ('as', 'using') and bits[3] not in ('as', 'using'):
            raise template.TemplateSyntaxError(usage)
        if bits[1] == 'using':
            model = bits[2].strip("'\"")
            varname = bits[4].strip("'\"")
        else:
            model = bits[4].strip("'\"")
            varname = bits[2].strip("'\"")

    return TopLevelCategoriesNode(varname, model)
1021621
def index(self, category):
        
        index = 0
        for this_category in self._categories:
            if category is this_category:
                return index
            index += this_category.leaf_count
        raise ValueError('category not in top-level categories')
1334861
def get_ratings(self):
        """"""
        return Vote.objects.filter(content_type=self.get_content_type(), object_id=self.instance.pk, key=self.field.key)
852975
def load_categories_in_config
      h = { }
      Category.all.each do |category|
        next if %w{rating year unknown}.include?(category.name)
        h[category.name] = category.tags.collect { |tag| tag.name }
      end
      @config[:categories] = h
    end
971923
function() {
            var categories = { "": 1 };
            for (var i in this.registered_node_types) {
                if (
                    this.registered_node_types[i].category &&
                    !this.registered_node_types[i].skip_list
                ) {
                    categories[this.registered_node_types[i].category] = 1;
                }
            }
            var result = [];
            for (var i in categories) {
                result.push(i);
            }
            return result;
        }
337328
def categories(self):
    '''
    
    '''

    if not getattr(self, '_categories', False):
      self._categories = [re.sub(r'^Category:', '', x) for x in
        [link['title']
        for link in self.__continued_query({
          'prop': 'categories',
          'cllimit': 'max'
        })
      ]]

    return self._categories
632729
def with_category(category: str) -> Callable:
    """"""
    def cat_decorator(func):
        categorize(func, category)
        return func
    return cat_decorator
899999
def get_category_metrics(self, category):
        """"""
        slug_list = self._category_slugs(category)
        return self.get_metrics(slug_list)
1195243
def levels(self):
        
        def levels(categories):
            # yield all lower levels
            sub_categories = [
                sc for c in categories for sc in c.sub_categories
            ]
            if sub_categories:
                for level in levels(sub_categories):
                    yield level
            # yield this level
            yield [(cat.idx, cat.label) for cat in categories]

        for level in levels(self):
            yield level
960614
def classify(self, text):
        
        score = self.score(text)
        if not score:
            return None
        return sorted(score.items(), key=lambda v: v[1])[-1][0]