Example #1
0
bool DirectoryBlobReader::ReadInternal(u64 offset, u64 length, u8* buffer,
                                       const std::set<DiscContent>& contents)
{
  if (contents.empty())
    return true;

  // Determine which DiscContent the offset refers to
  std::set<DiscContent>::const_iterator it = contents.lower_bound(DiscContent(offset));
  if (it->GetOffset() > offset && it != contents.begin())
    --it;

  // zero fill to start of file data
  PadToAddress(it->GetOffset(), &offset, &length, &buffer);

  while (it != contents.end() && length > 0)
  {
    _dbg_assert_(DISCIO, it->GetOffset() <= offset);
    if (!it->Read(&offset, &length, &buffer))
      return false;

    ++it;

    if (it != contents.end())
    {
      _dbg_assert_(DISCIO, it->GetOffset() >= offset);
      PadToAddress(it->GetOffset(), &offset, &length, &buffer);
    }
  }

  return true;
}
Example #2
0
    /*
     * INFO:        Adding line to the envelope
     *              Line is of type 'y=a*x+b' represented by 2 coefficients 'a' and 'b'
     * COMPLEXITY:  Adding N lines(N calls of function) takes O(N*log N) time
     */
    void addLine(coef_t a, coef_t b)
    {
        //find the place where line will be inserted in set
        Line l3 = Line(a, b);
        auto it = hull.lower_bound(l3);
 
        //if parallel line is already in set, one of them becomes irrelevant
        if (it!=hull.end() && areParallel(*it, l3))
        {
            if (isMax && it->b < b || !isMax && it->b > b)
                it = hull.erase(it);
            else
                return;
        }
 
        //try to insert
        it = hull.insert(it, l3);
        if (irrelevant(it)) { hull.erase(it); return; }
 
        //remove lines which became irrelevant after inserting line
        while (hasPrev(it) && irrelevant(std::prev(it))) hull.erase(std::prev(it));
        while (hasNext(it) && irrelevant(std::next(it))) hull.erase(std::next(it));
 
        //refresh 'xLine'
        it = updateLeftBorder(it);
        if (hasPrev(it))
            updateLeftBorder(std::prev(it));
        if (hasNext(it))
            updateLeftBorder(std::next(it));
    }
Example #3
0
int excellent(){
	int i,x,y,count;
	std::set<std::pair<int,int> >::iterator first,last,prev;

	C.clear();

	C.insert(A[0].second);
	count = 1;

	for(i = 1; i < N; i++){
		x = A[i].second.first;
		y = A[i].second.second;

		prev = C.lower_bound(A[i].second);
		first = prev;

		if(prev == C.begin() || (*(--prev)).second > y){
			++count;
			last = first;
			while(last != C.end() && (*last).second > y) last++;

			if(first != last) C.erase(first,last);
			C.insert(A[i].second);
		}

	}

	return count;
}
 size_t DiscreteDepthDistortionModel::getClosestToRef(const std::set<size_t> &divisors, const double &ref)
 {
   std::set<size_t>::iterator low, prev;
   low = divisors.lower_bound(ref);
   if(low == divisors.end())
   {
     return *(--divisors.end());
   }
   else if(low == divisors.begin())
   {
     return *low;
   }
   else
   {
     prev = low;
     --prev;
     if((ref - *prev) <= (*low - ref))
     {
       return *prev;
     }
     else
     {
       return *low;
     }
   }
 }
Example #5
0
int main(void)
{
	scanf("%d", &tests);
	for(int t = 0; t < tests; ++ t)
	{
		tree = iTree();
		scanf("%d", &size);
		for(int s = 0; s < size; ++ s)
		{
			scanf("%d", &tab[s]);
			secik.insert(s);
		}

		for(int s = size - 1; s >= 0; -- s)
		{
			//printf("%d: %d; %d\n", s + 1, tab[s], tree.get(tab[s] + 1));
			temp = secik.lower_bound(tab[s] + tree.get(tab[s] + 1));
			result[s] = *temp + 1;
			//printf("%d => %d\n", s + 1, *temp + 1);
			secik.erase(temp);
			tree.insert(tab[s] + 2);
		}

		for(int s = 0; s < size; ++ s)
			printf("%d ", result[s]);

		puts("");
	}

	return 0;
}
Example #6
0
Float_t findNearestAllowedAngle(std::set<Float_t>& angles,
                                const Float_t ang) {
   // find closest allowed angle
   std::set<Float_t>::const_iterator
      hiang = angles.lower_bound(ang),
      loang = hiang;
   if (loang!=angles.begin()) {
      --loang;
   }
#ifdef DEBUG
      Printf("loang=%p, hiang=%p, end=%p",
             (void*)&(*loang), (void*)&(*hiang), (void*)&(*angles.end()));
#endif
   if ( (loang==angles.end()) || (hiang==angles.end()) ) {
      // too big; take the largest one
      return *(angles.rbegin());
   } else {
      // round to the nearest angle (round up if halfway)
#ifdef DEBUG
      Printf("loang=%g, hiang=%g, ang=%g",
             *loang, *hiang, ang);
#endif
      if ( TMath::Abs(*loang - ang) < TMath::Abs(*hiang - ang) ) {
         return *loang;
      } else {
         return *hiang;
      }
   }
}
std::set<IDBKeyData>::iterator MemoryObjectStoreCursor::firstForwardIteratorInRemainingRange(std::set<IDBKeyData>& set)
{
    if (m_remainingRange.isExactlyOneKey())
        return set.find(m_remainingRange.lowerKey);

    auto lowest = set.lower_bound(m_remainingRange.lowerKey);
    if (lowest == set.end())
        return lowest;

    if (m_remainingRange.lowerOpen && *lowest == m_remainingRange.lowerKey) {
        ++lowest;
        if (lowest == set.end())
            return lowest;
    }

    if (!m_remainingRange.upperKey.isNull()) {
        if (lowest->compare(m_remainingRange.upperKey) > 0)
            return set.end();

        if (m_remainingRange.upperOpen && *lowest == m_remainingRange.upperKey)
            return set.end();
    }

    return lowest;
}
Example #8
0
    void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
    {
        // DoS prevention: limit cache size to less than 10MB
        // (~200 bytes per cache entry times 50,000 entries)
        // Since there are a maximum of 20,000 signature operations per block
        // 50,000 is a reasonable default.
        int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
        if (nMaxCacheSize <= 0) return;

        boost::unique_lock<boost::shared_mutex> lock(cs_sigcache);

        while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
        {
            // Evict a random entry. Random because that helps
            // foil would-be DoS attackers who might try to pre-generate
            // and re-use a set of valid signatures just-slightly-greater
            // than our cache size.
            uint256 randomHash = GetRandHash();
            std::vector<unsigned char> unused;
            std::set<sigdata_type>::iterator it =
                setValid.lower_bound(sigdata_type(randomHash, unused, unused));
            if (it == setValid.end())
                it = setValid.begin();
            setValid.erase(*it);
        }

        sigdata_type k(hash, vchSig, pubKey);
        setValid.insert(k);
    }
Example #9
0
/// ComputeNodesReacahbleFrom - Compute the set of nodes in the specified
/// inverse graph that are reachable from N.  This is a simple depth first
/// search.
///
static void ComputeNodesReachableFrom(DSNode *N,
                            std::set<std::pair<DSNode*,DSNode*> > &InverseGraph,
                                      hash_set<const DSNode*> &Reachable) {
  if (!Reachable.insert(N).second) return;  // Already visited!
  
  std::set<std::pair<DSNode*,DSNode*> >::iterator I = 
    InverseGraph.lower_bound(std::make_pair(N, (DSNode*)0));
  for (; I != InverseGraph.end() && I->first == N; ++I)
    ComputeNodesReachableFrom(I->second, InverseGraph, Reachable);
}
Example #10
0
    /*
     * INFO:        Query, which returns max/min(depends on hull type - see more info above) value in point with abscissa 'x'
     * COMPLEXITY:  O(log N), N-amount of lines in hull
     */
    val_t getBest(coord_t x) const
    {
        Line q;
        q.val = x;
        q.type = isMax ? Line::Type::maxQuery : Line::Type::minQuery;

        auto bestLine = hull.lower_bound(q);
        if (isMax) --bestLine;
        return bestLine->valueAt(x);
    }
Example #11
0
UtxoData::iterator FindRandomFrom(const std::set<COutPoint> &utxoSet) {
    assert(utxoSet.size());
    auto utxoSetIt = utxoSet.lower_bound(COutPoint(InsecureRand256(), 0));
    if (utxoSetIt == utxoSet.end()) {
        utxoSetIt = utxoSet.begin();
    }
    auto utxoDataIt = utxoData.find(*utxoSetIt);
    assert(utxoDataIt != utxoData.end());
    return utxoDataIt;
}
Example #12
0
 val_t getBest(coord_t x) const
 {
     Line q;
     q.val = x;
     q.type = isMax ? Line::Type::maxQuery : Line::Type::minQuery;
     if(hull.empty())
         return isMax? -INF:INF;
     auto bestLine = hull.lower_bound(q);
     if(hull.begin()==bestLine && isMax)return isMax?-INF:INF;
     if (isMax) --bestLine;
     return bestLine->valueAt(x);
 }
Example #13
0
void ColumnCmd::insertEmptyColumns(const std::set<int> &indices,
                                   bool insertAfter) {
  // Filter out all less than 0 indices (in particular, the 'camera' column
  // in the Toonz derivative product "Tab")
  std::vector<int> positiveIndices(indices.lower_bound(0), indices.end());
  if (positiveIndices.empty()) return;

  std::unique_ptr<ColumnCommandUndo> undo(
      new InsertEmptyColumnsUndo(positiveIndices, insertAfter));
  if (undo->isConsistent()) {
    undo->redo();
    TUndoManager::manager()->add(undo.release());
  }
}
Example #14
0
int main(){

    //insert O(log N) per element or O(1) am per element for _sorted_ elements
    //For a total of O(N log N)  or O(N) for sorted inputs
    int key;
    for(key = 0; key < 10; key++){
        myset.insert(key);
    }

    //find O(log N)
    it = myset.find(3);

    //removes 3 in O(1) am post-find time
    myset.erase(it);
    //removes 4 from the set  O(log N) time
    myset.erase(4);

    //iterate the set in forward order O(1) am / O(log N)
    //for a total of O(N) total
    //Note that begin() returns an iterator to the first element
    //whereas that end() returns to a dummy element after the last element
    for(it = myset.begin(); it != myset.end(); it++){
        std::cout << *it << " " ;
    }
    std::cout << std::endl;

    //iterate the set in reverse order )O(1) am / O(log N)
    //for a total of O(N) total
    //Note that rbegin() returns an iterator to the last element
    //whereas that end() returns to a dummy element before the first element
    for(rit = myset.rbegin(); rit != myset.rend(); rit++){
        std::cout << *rit << " " ;
    }
    std::cout << std::endl;

    //Find the first element greater than or equal to the current element in O(log N) time
    //In this case it returns 6
    it = myset.lower_bound(6);
    std::cout << *it << std::endl;
    
    //Find the first element greater than the current element in O(log N) time
    //In this case it returns 7
    it = myset.upper_bound(6);
    std::cout << *it << std::endl;
    
    // Empties the set O(N) time
    myset.clear();

}
void MemoryObjectStoreCursor::setForwardIteratorFromRemainingRange(std::set<IDBKeyData>& set)
{
    if (!set.size()) {
        m_iterator = Nullopt;
        return;
    }

    if (m_remainingRange.isExactlyOneKey()) {
        m_iterator = set.find(m_remainingRange.lowerKey);
        if (*m_iterator == set.end())
            m_iterator = Nullopt;

        return;
    }

    m_iterator = Nullopt;

    auto lowest = set.lower_bound(m_remainingRange.lowerKey);
    if (lowest == set.end())
        return;

    if (m_remainingRange.lowerOpen && *lowest == m_remainingRange.lowerKey) {
        ++lowest;
        if (lowest == set.end())
            return;
    }

    if (!m_remainingRange.upperKey.isNull()) {
        if (lowest->compare(m_remainingRange.upperKey) > 0)
            return;

        if (m_remainingRange.upperOpen && *lowest == m_remainingRange.upperKey)
            return;
    }

    m_iterator = lowest;
}
		void mark_object ( const gc_object_generic_base *b )
		{
			heap_block_iterator it = find_containing_block ( b );
			assert ( it != m_heap_blocks.end() );
			assert ( it->second.is_address_inside ( b ) );

			if ( it->second.mark == false )
			{
				// Mark this block.
				it->second.mark = true;
				// Find all gc pointers that are inside this heap block.
				// Mark the blocks that they point to.
				ptr_iterator it_ptr = m_heap_ptrs.lower_bound ( it->second.p );
				void *block_end = it->second.end();

				while ( it_ptr != m_heap_ptrs.end() && it_ptr->first < block_end )
				{
					gc_object_generic_base *p = it_ptr->second;
					assert ( p );
					m_to_mark.push_back ( p );
					//push_heap(m_to_mark);
					++it_ptr;
				}

				// Find all gc containers that are inside this heap block.
				{
					container_iterator it_cnt = m_containers.lower_bound ( ( singlethreaded_marksweep::gc_container_base * ) it->second.p );
					void *block_end = it->second.end();

					while ( it_cnt != m_containers.end() && *it_cnt < block_end )
					{
						( *it_cnt )->visit_contained_ptrs();
						++it_cnt;
					}
				}
			}
		}
Example #17
0
	// 左对齐
	PBLOBNBOX LineFinder::findAlignedBlob(const AlignedBlobParams& p, std::set<PBLOBNBOX, BoxCmp_LT<BLOBNBOX>>& bset, PBLOBNBOX bbox){
		if (bbox == nullptr) return nullptr;
		int dx = p.vertical.x, dy = p.vertical.y;
		int dir_y = dy < 0 ? -1 : 1;

		int skew_tolerance = p.max_v_gap / jun::kMaxSkewFactor;
		int x2 = (p.max_v_gap*dx + dy / 2) / dy;
		Rect box = bbox->bounding_box();
		int x_start = box.x;
		x2 += x_start;
		int xmin, xmax, ymin, ymax;
		if (x2 < x_start){ //向左
			xmin = x2; xmax = x_start;
		}
		else{
			xmin = x_start; xmax = x2;
		}
		if (dy > 0){ //向下
			ymin = box.ylast();
			ymax = ymin + p.max_v_gap;
		}
		else{
			ymax = box.y;
			ymin = ymax - p.max_v_gap;
		}
		xmin -= skew_tolerance - p.min_gutter;
		xmax += skew_tolerance + p.r_align_tolerance;

		logger()->debug("Starting {} {}  search at {}-{},{}  dy={} search_size={}, gutter={}\n",
			p.ragged ? "Ragged" : "Aligned", "Left", xmin, xmax, box.ylast(), dir_y, p.max_v_gap, p.min_gutter
			);
		auto begin_blob = std::make_shared<BLOBNBOX>();
		begin_blob->set_bounding_box(Rect{ xmin, ymin, 1, 1 });
		auto end_blob = std::make_shared<BLOBNBOX>();
		end_blob->set_bounding_box(Rect{ xmax, ymax, 1, 1 });
		auto beginIter = bset.lower_bound(begin_blob);
		auto endIter = bset.upper_bound(end_blob);

		PBLOBNBOX result = nullptr;
		int min_dist = std::numeric_limits<int>::max();
		for (auto iter = beginIter; iter != endIter; ++iter){
			Rect nbox = (*iter)->bounding_box();
			int n_y = (nbox.y + nbox.ylast()) / 2;
			if ((dy > 0) && (n_y<ymin || n_y>ymax)) continue;
			if (dy < 0 && (n_y < ymin || n_y > ymax)) continue;

			int x_at_ny = x_start + (n_y - ymin)*dx / dy;
			int n_x = nbox.x;
			//aligned so keep it.
			if (n_x <= x_at_ny + p.r_align_tolerance&&n_x >= x_at_ny - p.l_align_tolerance){
				logger()->debug("aligned, seeking left, box={}\n", nbox);
				TabType n_type = (*iter)->left_tab_type;
				if (n_type != TabType::TT_NONE && (p.ragged || n_type != TabType::TT_MAYBE_RAGGED)){

					int x_dist = n_x - x_at_ny;
					int y_dist = n_y - ymin;
					int new_dist = x_dist*x_dist + y_dist*y_dist;
					if (new_dist < min_dist) {
						min_dist = new_dist;
						result = (*iter);
					}

				}
			}
		}
		return result;

	}
Example #18
0
unsigned NxsCompressDiscreteMatrix(
    const NxsCXXDiscreteMatrix & mat,       /**< is the data source */
    std::set<NxsCharacterPattern> & patternSet, /* matrix that will hold the compressed columns */
    std::vector<const NxsCharacterPattern *> * compressedIndexPattern, /** if not 0L, this will be filled to provide a map from an index in `compressedTransposedMatrix` to the original character count */
    const NxsUnsignedSet * taxaToInclude, /**< if not 0L, this should be  the indices of the taxa in `mat` to include (if 0L all characters will be included). Excluding taxa will result in shorter patterns (the skipped taxa will not be filled with empty codes, instead the taxon indexing will be frameshifted -- the client code must keep track of these frameshifts). */
    const NxsUnsignedSet * charactersToInclude)
{
    const unsigned origNumPatterns = (unsigned) patternSet.size();
    unsigned ntax = mat.getNTax();
    unsigned patternLength = ntax;
    unsigned nchar = mat.getNChar();
    if (compressedIndexPattern)
    {
        compressedIndexPattern->resize(nchar);
    }
    NxsUnsignedSet allTaxaInds;
    if (taxaToInclude)
    {
        if (taxaToInclude->empty())
        {
            return 0; // might want to warn about this!
        }
        const unsigned lastTaxonIndex = *(taxaToInclude->rbegin());
        if (lastTaxonIndex >= ntax)
        {
            throw NxsException("Taxon index in taxaToInclude argument to NxsCompressDiscreteMatrix is out of range");
        }
        patternLength -= taxaToInclude->size();
    }
    else
    {
        for (unsigned i = 0; i < ntax; ++i) {
            allTaxaInds.insert(i);
        }
        taxaToInclude = &allTaxaInds;
    }
    if (charactersToInclude)
    {
        if (charactersToInclude->empty())
        {
            return 0; // might want to warn about this!
        }
        const unsigned lastColumnIndex = *(charactersToInclude->rbegin());
        if (lastColumnIndex >= nchar)
        {
            throw NxsException("Character index in charactersToInclude argument to NxsCompressDiscreteMatrix is out of range");
        }
    }

    // Create actingWeights vector and copy the integer weights from mat into it
    // If there are no integer weights in mat, copy the floating point weights instead
    // if floating point weights have been defined
    const std::vector<int> & iwts = mat.getIntWeightsConst();
    std::vector<double> actingWeights(nchar, 1.0);
    bool weightsSpecified = false;
    bool weightsAsInts = false;
    if (!iwts.empty())
    {
        NCL_ASSERT(iwts.size() >= nchar);
        weightsSpecified = true;
        weightsAsInts = true;
        for (unsigned j = 0; j < nchar; ++j) {
            actingWeights[j] = (double)iwts.at(j);
        }
    }
    else
    {
        const std::vector<double> & dwts = mat.getDblWeightsConst();
        if (!dwts.empty())
        {
            weightsSpecified = true;
            actingWeights = dwts;
            NCL_ASSERT(actingWeights.size() == nchar);
        }
    }

    // Set corresponding actingWeights elements to zero if any characters have been excluded in mat
    const NxsUnsignedSet & excl = mat.getExcludedCharIndices();
    for (NxsUnsignedSet::const_iterator eIt = excl.begin(); eIt != excl.end(); ++eIt)
    {
        NCL_ASSERT(*eIt < nchar);
        actingWeights[*eIt] = 0.0;
    }
    const double * wts = &(actingWeights[0]);

    NxsCharacterPattern patternTemp;
    patternTemp.count = 1;
    for (unsigned j = 0; j < nchar; ++j)
    {
        double patternWeight = wts[j];
        bool shouldInclude = (charactersToInclude == 0L || (charactersToInclude->find(j) != charactersToInclude->end()));
        if (patternWeight > 0.0 &&  shouldInclude)
        {
            // Build up a vector representing the pattern of state codes at this site
            patternTemp.stateCodes.clear();
            patternTemp.stateCodes.reserve(patternLength);
            patternTemp.sumOfPatternWeights = patternWeight;

            unsigned indexInPattern = 0;
            for (NxsUnsignedSet::const_iterator taxIndIt = taxaToInclude->begin(); taxIndIt != taxaToInclude->end(); ++taxIndIt, ++indexInPattern)
            {
                const unsigned taxonIndex = *taxIndIt;
                const NxsCDiscreteStateSet * row    = mat.getRow(taxonIndex);
                const NxsCDiscreteStateSet code = row[j];
                patternTemp.stateCodes.push_back(code);
            }
            NCL_ASSERT(indexInPattern == patternLength);

            std::set<NxsCharacterPattern>::iterator lowBoundLoc = patternSet.lower_bound(patternTemp);
            if ((lowBoundLoc == patternSet.end()) || (patternTemp < *lowBoundLoc))
            {
                std::set<NxsCharacterPattern>::iterator insertedIt = patternSet.insert(lowBoundLoc, patternTemp);
                if (compressedIndexPattern)
                {
                    const NxsCharacterPattern & patInserted = *insertedIt;
                    (*compressedIndexPattern)[j] = &patInserted;
                }
            }
            else
            {
                NCL_ASSERT(patternTemp == *lowBoundLoc);
                lowBoundLoc->sumOfPatternWeights += patternWeight;
                lowBoundLoc->count += 1;
                if (compressedIndexPattern)
                {
                    (*compressedIndexPattern)[j] = &(*lowBoundLoc);
                }
            }
        }
    }
    return (unsigned)patternSet.size() - origNumPatterns;
}