counts the number of documents in an URML file.
        adapted from Listing 2 on
        http://www.ibm.com/developerworks/library/x-hiperfparse/
177484
def _get_num_of_documents(self):
        '''
        
        '''
        parser = etree.XMLParser(target=XMLElementCountTarget('document'))
        # When iterated over, 'results' will contain the output from
        # target parser's close() method
        num_of_documents = etree.parse(self.urml_file, parser)
        self._num_of_documents = num_of_documents
        return num_of_documents
847668
def process_files(count=None):
    

    pbar = enlighten.Counter(total=count, desc='Simple', unit='ticks',
                             bar_format=BAR_FMT, counter_format=COUNTER_FMT)

    for num in range(100):  # pylint: disable=unused-variable
        time.sleep(0.05)
        pbar.update(1.1)
220671
def read_counts(node):
  
  cfg.forward(node, cfg.ReachingDefinitions())

  rc = ReadCounts()
  rc.visit(node)
  return rc.n_read
1176702
public void count(String path,boolean b) throws IOException{

		HashMap<String, Integer> wordsFreq = new HashMap<String, Integer>();
		HashMap<Integer, Integer> lensFreq = new HashMap<Integer, Integer>();
		HashMap<String, Integer> posFreq = new HashMap<String, Integer>();
		HashMap<String, Integer> relsFreq = new HashMap<String, Integer>();
		HashMap<String, HashSet<String>> wordsPOS = new HashMap<String, HashSet<String>>();
		
		int total = 0;
		int totalsent = 0;
		Iterator<FNLPDoc> dit = docs.iterator();
		while(dit.hasNext()){
			FNLPDoc doc = dit.next();
			Iterator<FNLPSent> sit = doc.sentences.iterator();
			while(sit.hasNext()){
				FNLPSent sent = sit.next();
				totalsent++;
				for(int i=0;i<sent.words.length;i++){
					total++;
					String w = sent.words[i];
					int len = w.length();
					String pos = sent.tags[i];
					if(!pos.equals("专有名"))
						continue;
					String rels = sent.relations[i];
//					if(len > 20){
//						System.out.println(w);						
//					}
					
					if (posFreq.containsKey(pos)) {
						posFreq.put(pos, posFreq.get(pos) + 1);
					} else {
						posFreq.put(pos, 1);
					}

					if (lensFreq.containsKey(len)) {
						lensFreq.put(len, lensFreq.get(len) + 1);
					} else {
						lensFreq.put(len, 1);
					}

					if (wordsFreq.containsKey(w)) {
						wordsFreq.put(w, wordsFreq.get(w) + 1);
						
					} else {
						wordsFreq.put(w, 1);						
					}
					
					if (wordsPOS.containsKey(w)) {
						wordsPOS.get(w).add(pos);						
					} else {
						HashSet<String> posset = new HashSet<String>();
						posset.add(pos);
						wordsPOS.put(w, posset);			
					}
					
					
					
					if (relsFreq.containsKey(rels)) {
						relsFreq.put(rels, relsFreq.get(rels) + 1);
					} else {
						relsFreq.put(rels, 1);
					}
				}
			}
		}
		System.out.println("总字数："+total);
		System.out.println("总句数："+totalsent);
		List<Entry> sortedwordsFreq = MyCollection.sort(wordsFreq);		
		MyCollection.write(sortedwordsFreq, path+"/wc.txt", b);
		
		List<Entry> sortedposFreq = MyCollection.sort(posFreq);		
		MyCollection.write(sortedposFreq, path+"/pos.txt", b);
		
		List<Entry> sortedlrelsFreq = MyCollection.sort(relsFreq);
		MyCollection.write(sortedlrelsFreq, path+"/relations.txt", b);

		List<Entry> sortedlensFreq = MyCollection.sort(lensFreq);
		MyCollection.write(sortedlensFreq, path+"/lc.txt", b);
		
		MyCollection.write(wordsPOS, path+"/wordpos.txt");
	}
735945
def count_elements(fname, element):
    
    num = 0
    tot = 0
    for event, elem in iterparse(fname):
        tot += 1
        if elem.text != '':
            #print(' tag  = ', elem.tag)
            #print(' event  = ', event   # always end
            #print(' text = ',  elem.text)
            pass
        if element in elem.tag:
            #print(elem.xpath( 'description/text( )' ))
            #print(elem.text)
            num += 1
            elem.clear()
    return num, tot
1304432
def count(self, query, _or=False):
        
        if isinstance(query, str):
            return self.fm.count(query, MapIntInt({}))
        else:
            search_results = []
            for q in query:
                dids = MapIntInt({})
                self.fm.search(q, dids)
                search_results.append(dids.asdict())
            merged_dids = self._merge_search_result(search_results, _or)
            counts = 0
            for did in merged_dids:
                if _or:
                    counts += reduce(add, [int(x.pop(did, 0)) for x in search_results])
                else:
                    counts += min([int(x.pop(did, 0)) for x in search_results])
            return counts
769684
def parse(filename, MAX_TERM_COUNT=1000):
    
    with open(filename, "r") as f:

        termId = None
        name = None
        desc = None
        parents = []

        termCount = 0
        for l in f.readlines():
            if l.startswith("id:"):
                termId = l.strip()[4:]
            if l.startswith("name:"):
                name = l.strip()[6:]
            elif l.startswith("def:"):
                desc = l.strip()[5:]
            elif l.startswith("is_a:"):
                pid = l.strip()[6:].split(" ", 1)[0]
                parents.append(pid)
            if len(l) == 1:     # newline
                # save
                if termId is not None and name is not None:
                    terms[termId] = {'name': name, 'desc': desc,
                                     'parents': parents[:], 'children': []}
                    termId = None
                    name = None
                    parents = []
                    termCount += 1
                    if MAX_TERM_COUNT is not None and \
                       termCount > MAX_TERM_COUNT:
                        break

    count = 0
    for tid, tdict in terms.items():
        count += 1      # purely for display
        for p in tdict['parents']:
            if p in terms.keys():
                terms[p]['children'].append(tid)

    # Get unique term IDs for Tag Groups.
    tagGroups = set()
    for tid, tdict in terms.items():
        # Only create Tags for GO:terms that are 'leafs' of the tree
        if len(tdict['children']) == 0:
            for p in tdict['parents']:
                tagGroups.add(p)

    return tagGroups, terms
1368936
def count(self):
        
        params = self.dump()
        params['limit'] = 0
        params['count'] = 1
        content = self._do_request(params)
        return content['count']
13410
def count(self, view, include=None):
        
        return self._get(self._build_url(self.endpoint.count(id=view, include=include)))
8067
def build_counter_tag(epoch_field, dry_run=False):
    
    logger.info("Epoch Field: {}, OBJECT_COUNT {}".format(str(epoch_field), str(OBJECT_COUNT)))
    tag = epoch_field[1] + "-" + OBJECT_COUNT

    if dry_run:
        tag += "-DRYRUN"

    return tag
1291998
function getNumMatches(fileList, queryExpr) {
    var i,
        matches = 0;
    for (i = 0; i < fileList.length; i++) {
        var temp = countNumMatches(getFileContentsForFile(fileList[i]), queryExpr);
        if (temp) {
            numFiles++;
            matches += temp;
        }
        if (matches > MAX_TOTAL_RESULTS) {
            exceedsMaximum = true;
            break;
        }
    }
    return matches;
}
19007
def count_files(admin_sets)
        file_counts = Hash.new(0)
        admin_sets.each do |admin_set|
          query = "{!join from=file_set_ids_ssim to=id}isPartOf_ssim:#{admin_set.id}"
          file_results = ActiveFedora::SolrService.instance.conn.get(
            ActiveFedora::SolrService.select_path,
            params: { fq: [query, "has_model_ssim:FileSet"],
                      rows: 0 }
          )
          file_counts[admin_set.id] = file_results['response']['numFound']
        end
        file_counts
      end
66266
def count_children(cls, resource_id, db_session=None, *args, **kwargs):
        
        query = db_session.query(cls.model.resource_id)
        query = query.filter(cls.model.parent_id == resource_id)
        return query.count()
25553
def count(args):
    
    p = OptionParser(count.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(p.print_help())

    frgfile, = args
    fp = open(frgfile)

    counts = defaultdict(int)
    for rec in iter_records(fp):
        counts[rec.type] += 1

    for type, cnt in sorted(counts.items()):
        print('{0}: {1}'.format(type, cnt), file=sys.stderr)
508419
def count_elements(doc):
    ""
    summary = {}
    for el in doc.iter():
        try:
            namespace, element_name = re.search('^{(.+)}(.+)$', el.tag).groups()
        except:
            namespace = None
            element_name = el.tag
        if not summary.has_key(namespace):
            summary[namespace] = {}
        if not summary[namespace].has_key(element_name):
            summary[namespace][element_name] = 1
        else:
            summary[namespace][element_name] += 1
    return summary
483068
protected void countTerms(TermedDocument termedDocument,
			EntityStatistics entityStatistics) {
		entityStatistics.countLabels += termedDocument.getLabels().size();
		// for (MonolingualTextValue mtv : termedDocument.getLabels().values())
		// {
		// countKey(usageStatistics.labelCounts, mtv.getLanguageCode(), 1);
		// }

		entityStatistics.countDescriptions += termedDocument.getDescriptions()
				.size();
		// for (MonolingualTextValue mtv : termedDocument.getDescriptions()
		// .values()) {
		// countKey(usageStatistics.descriptionCounts, mtv.getLanguageCode(),
		// 1);
		// }

		for (String languageKey : termedDocument.getAliases().keySet()) {
			int count = termedDocument.getAliases().get(languageKey).size();
			entityStatistics.countAliases += count;
			// countKey(usageStatistics.aliasCounts, languageKey, count);
		}
	}
376951
def parse_document(self):
        
        s = Sitemap()
        self.logger.info("Reading sitemap(s) from %s ..." % (self.sitemap))
        try:
            list = s.parse_xml(url_or_file_open(self.sitemap))
        except IOError as e:
            raise ClientFatalError("Cannot read document (%s)" % str(e))
        num_entries = len(list.resources)
        capability = '(unknown capability)'
        if ('capability' in list.md):
            capability = list.md['capability']
        print("Parsed %s document with %d entries" % (capability, num_entries))
        if (self.verbose):
            to_show = 100
            override_str = ' (override with --max-sitemap-entries)'
            if (self.max_sitemap_entries):
                to_show = self.max_sitemap_entries
                override_str = ''
            if (num_entries > to_show):
                print(
                    "Showing first %d entries sorted by URI%s..." %
                    (to_show, override_str))
            n = 0
            for resource in list:
                print('[%d] %s' % (n, str(resource)))
                n += 1
                if (n >= to_show):
                    break