Пример #1
0
void DumpEditor::onBufferInfo()
{
    m_bufferInfos = m_watcher.result();
    m_bufferStats = ::fwMemory::BufferManager::computeBufferStats(m_bufferInfos);

    m_mapper->blockSignals(true);
    ::fwCom::Connection::Blocker block(m_connection);

    for(int row = 0; row < m_list->rowCount(); row++)
    {
        m_mapper->removeMappings( m_list->cellWidget(row, 4) );
    }
    m_list->clearContents();
    m_objectsUID.clear();

    int itemCount = 0;
    m_list->setSortingEnabled(false);
    m_list->setRowCount(static_cast<int>(m_bufferInfos.size()));
    m_list->setColumnCount(5);
    QColor backColor;
    for(const ::fwMemory::BufferManager::BufferInfoMapType::value_type& elt :  m_bufferInfos)
    {
        m_objectsUID.push_back(elt.first);

        std::string status     = "?";
        std::string date       = "?";
        std::string lockStatus = "?";

        const ::fwMemory::BufferInfo& dumpBuffInfo = elt.second;
        bool loaded                                = dumpBuffInfo.loaded;
        if(!loaded)
        {
            backColor = Qt::darkYellow;
            status    = "Dumped";
        }
        else
        {
            backColor = Qt::white;
            status    = "-";
        }

        bool isLock = dumpBuffInfo.lockCount() > 0;
        if ( isLock )
        {
            lockStatus = "locked(" + ::fwTools::getString(dumpBuffInfo.lockCount()) +")";
        }
        else
        {
            lockStatus = "unlocked";
        }

        date = ::fwTools::getString(dumpBuffInfo.lastAccess.getLogicStamp());

        QTableWidgetItem* currentSizeItem = new SizeTableWidgetItem( getHumanReadableSize(dumpBuffInfo.size) );
        currentSizeItem->setData(Qt::UserRole, (qulonglong)dumpBuffInfo.size );
        currentSizeItem->setFlags(Qt::ItemIsEnabled);
        currentSizeItem->setBackgroundColor(backColor);
        m_list->setItem(itemCount, 0, currentSizeItem );

        QTableWidgetItem* statusItem = new QTableWidgetItem( QString::fromStdString(status));
        statusItem->setFlags(Qt::ItemIsEnabled);
        statusItem->setBackgroundColor(backColor);
        m_list->setItem(itemCount, 1, statusItem );

        QTableWidgetItem* dateItem = new QTableWidgetItem( QString::fromStdString(date));
        dateItem->setFlags(Qt::ItemIsEnabled);
        dateItem->setBackgroundColor(backColor);
        m_list->setItem(itemCount, 2, dateItem );

        QTableWidgetItem* lockStatusItem = new QTableWidgetItem( QString::fromStdString(lockStatus));
        lockStatusItem->setFlags(Qt::ItemIsEnabled);
        lockStatusItem->setBackgroundColor(backColor);
        m_list->setItem(itemCount, 3, lockStatusItem );

        QPushButton* actionItem = new QPushButton(QString::fromStdString((loaded) ? "Dump" : "Restore"), m_list);
        actionItem->setEnabled(!isLock && (dumpBuffInfo.size > 0) );
        m_list->setCellWidget(itemCount, 4, actionItem );
        QObject::connect(actionItem, SIGNAL(pressed()), m_mapper, SLOT(map()));
        m_mapper->setMapping(actionItem, itemCount);

        ++itemCount;
    }
    m_list->setSortingEnabled(true);

    m_mapper->blockSignals(false);

    m_infoEditor->reset();
    m_infoEditor->resizeColumnsToContents();
}
Пример #2
0
/*
 * Beginning-of-function code:
 *
 * 'sp' is an array of indices in symtab for the arguments
 * 'cnt' is the number of arguments
 */
void
bfcode(struct symtab **sp, int cnt)
{
	union arglist *usym;
	int saveallargs = 0;
	int i, argofs = 0;

	/*
	 * Detect if this function has ellipses and save all
	 * argument registers onto stack.
	 */
	usym = cftnsp->sdf->dfun;
	while (usym && usym->type != TNULL) {
		if (usym->type == TELLIPSIS) {
			saveallargs = 1;
			break;
		}
		++usym;
	}

	/* if returning a structure, move the hidden argument into a TEMP */
	if (cftnsp->stype == STRTY+FTN || cftnsp->stype == UNIONTY+FTN) {
		param_retstruct();
		++argofs;
	}

	/* recalculate the arg offset and create TEMP moves */
	for (i = 0; i < cnt; i++) {

		if (sp[i] == NULL)
			continue;

		if ((argofs >= NARGREGS) && !xtemps)
			break;

		if (argofs > NARGREGS) {
			putintemp(sp[i]);
		} else if (sp[i]->stype == STRTY || sp[i]->stype == UNIONTY) {
			param_struct(sp[i], &argofs);
		} else if (DEUNSIGN(sp[i]->stype) == LONGLONG) {
			param_64bit(sp[i], &argofs, xtemps && !saveallargs);
		} else if (sp[i]->stype == DOUBLE || sp[i]->stype == LDOUBLE) {
			if (features(FEATURE_HARDFLOAT))
				param_double(sp[i], &argofs,
				    xtemps && !saveallargs);
			else
				param_64bit(sp[i], &argofs,
				    xtemps && !saveallargs);
		} else if (sp[i]->stype == FLOAT) {
			if (features(FEATURE_HARDFLOAT))
				param_float(sp[i], &argofs,
				    xtemps && !saveallargs);
			else
				param_32bit(sp[i], &argofs,
				    xtemps && !saveallargs);
		} else {
			param_32bit(sp[i], &argofs, xtemps && !saveallargs);
		}
	}

	/* if saveallargs, save the rest of the args onto the stack */
	while (saveallargs && argofs < NARGREGS) {
      		NODE *p, *q;
		int off = ARGINIT/SZINT + argofs;
		q = block(REG, NIL, NIL, INT, 0, 0);
		regno(q) = R0 + argofs++;
		p = block(REG, NIL, NIL, INT, 0, 0);
		regno(p) = FPREG;
		p = block(PLUS, p, bcon(4*off), INT, 0, 0);
		p = block(UMUL, p, NIL, INT, 0, 0);
		p = buildtree(ASSIGN, p, q);
		ecomp(p);
	}

}
Пример #3
0
////////////////////////////////////////////////////////////////////////////////////////////////////////
//calculate hog features
//based on code from http://www.mathworks.com/matlabcentral/fileexchange/33863
cv::Mat HOGfeatures(cv::Mat & pixels, int nb_bins, double cheight, double cwidth, int block_rows, int block_cols, bool orient, double clip_val)
{
    //const double PI = 3.1415926536;
	bool grayscale;

	//img must be uchar
	if (pixels.type() == CV_8UC1)
	{
		grayscale = 1;
	}
	else if (pixels.type() == CV_8UC3)
	{
		grayscale = 0;
	}
	else
	{
		std::cerr << "Image is not uchar, cannot calculate HOG!!!" << std::endl;
		return cv::Mat();
	}

	/*if (!pixels.isContinuous())
	{
		cv::Mat temp = pixels.clone();
		pixels = temp;
		if (!pixels.isContinuous())
		{
			std::cerr << "Memory error, cannot allocate a continuous array for HOG calc!" << std::endl;
			return cv::Mat();
		}
	}
	unsigned char * pixels = img.data;*/
	
	int img_width  = pixels.cols;
	int img_height = pixels.rows;

    int hist1= 2+ceil(-0.5 + img_height/cheight);
    int hist2= 2+ceil(-0.5 + img_width/cwidth);

	double bin_size = (1+(orient==1))*PI/nb_bins;

	cv::Mat features((hist1-2-(block_rows-1))*(hist2-2-(block_cols-1))*nb_bins*block_rows*block_cols, 1, CV_32FC1);

    float dx[3], dy[3], grad_or, grad_mag, temp_mag;
    float Xc, Yc, Oc, block_norm;
    int x1, x2, y1, y2, bin1, bin2;
    int des_indx = 0;
    
    std::vector<std::vector<std::vector<double> > > h(hist1, std::vector<std::vector<double> > (hist2, std::vector<double> (nb_bins, 0.0) ) );    
    std::vector<std::vector<std::vector<double> > > block(block_rows, std::vector<std::vector<double> > (block_cols, std::vector<double> (nb_bins, 0.0) ) );

	std::vector<cv::Mat> pixel_vec;

	if (!grayscale)
	{
		cv::split(pixels, pixel_vec);
	}

	//Calculate gradients (zero padding)
    

    for(unsigned int y=0; y<img_height; y++) 
	{
        for(unsigned int x=0; x<img_width; x++) 
		{
            if (grayscale == 1)
			{
                if (x==0) 
				{
					dx[0] = pixels.at<unsigned char>(y , x+1);
				}
                else
				{
                    if (x==img_width-1) 
					{
						dx[0] = -pixels.at<unsigned char>(y , x-1);
					}
					else
					{
						dx[0] = pixels.at<unsigned char>(y, x+1) - pixels.at<unsigned char>(y , x-1);
					}
                }
                if (y==0)
				{
					dy[0] = -pixels.at<unsigned char>(y+1, x);
				}
				else{
                    if (y==img_height-1) 
					{
						dy[0] = pixels.at<unsigned char>(y-1, x);
					}
					else
					{
						dy[0] = -pixels.at<unsigned char>(y+1, x) + pixels.at<unsigned char>(y-1, x);
					}
                }
            }
            else
			{
                if(x==0)
				{
                    dx[0] = pixel_vec[0].at<unsigned char>(y , x+1);
                    dx[1] = pixel_vec[1].at<unsigned char>(y , x+1);
                    dx[2] = pixel_vec[2].at<unsigned char>(y , x+1);                    
                }
                else
				{
                    if (x==img_width-1)
					{
                        dx[0] = -pixel_vec[0].at<unsigned char>(y , x-1);                        
                        dx[1] = -pixel_vec[1].at<unsigned char>(y , x-1);
                        dx[2] = -pixel_vec[2].at<unsigned char>(y , x-1);
                    }
                    else
					{
                        dx[0] = pixel_vec[0].at<unsigned char>(y, x+1) - pixel_vec[0].at<unsigned char>(y , x-1);
                        dx[1] = pixel_vec[1].at<unsigned char>(y, x+1) - pixel_vec[1].at<unsigned char>(y , x-1);
                        dx[2] = pixel_vec[2].at<unsigned char>(y, x+1) - pixel_vec[2].at<unsigned char>(y , x-1);
                        
                    }
                }
                if(y==0)
				{
                    dy[0] = -pixel_vec[0].at<unsigned char>(y+1, x);
                    dy[1] = -pixel_vec[1].at<unsigned char>(y+1, x);
                    dy[2] = -pixel_vec[2].at<unsigned char>(y+1, x);
                }
                else
				{
                    if (y==img_height-1)
					{
                        dy[0] = pixel_vec[0].at<unsigned char>(y-1, x);
                        dy[1] = pixel_vec[1].at<unsigned char>(y-1, x);
                        dy[2] = pixel_vec[2].at<unsigned char>(y-1, x);
                    }
                    else
					{
                        dy[0] = -pixel_vec[0].at<unsigned char>(y+1, x) + pixel_vec[0].at<unsigned char>(y-1, x);
                        dy[1] = -pixel_vec[1].at<unsigned char>(y+1, x) + pixel_vec[1].at<unsigned char>(y-1, x);
                        dy[2] = -pixel_vec[2].at<unsigned char>(y+1, x) + pixel_vec[2].at<unsigned char>(y-1, x);
                    }
                }
            }
            
            grad_mag = sqrt(dx[0]*dx[0] + dy[0]*dy[0]);
            grad_or= atan2(dy[0], dx[0]);
            
            if (grayscale == 0)
			{
                temp_mag = grad_mag;
                for (unsigned int cli=1;cli<3;++cli)
				{
                    temp_mag= sqrt(dx[cli]*dx[cli] + dy[cli]*dy[cli]);
                    if (temp_mag>grad_mag)
					{
                        grad_mag=temp_mag;
                        grad_or= atan2(dy[cli], dx[cli]);
                    }
                }
            }
            
            if (grad_or<0) grad_or+=PI + (orient==1) * PI;

            // trilinear interpolation
            
            bin1 = (int)floor(0.5 + grad_or/bin_size) - 1;
            bin2 = bin1 + 1;
            x1   = (int)floor(0.5+ x/cwidth);
            x2   = x1+1;
            y1   = (int)floor(0.5+ y/cheight);
            y2   = y1 + 1;
            
            Xc = (x1+1-1.5)*cwidth + 0.5;
            Yc = (y1+1-1.5)*cheight + 0.5;
            
            Oc = (bin1+1+1-1.5)*bin_size;
            
            if (bin2==nb_bins){
                bin2=0;
            }
            if (bin1<0){
                bin1=nb_bins-1;
            }            
           
            h[y1][x1][bin1]= h[y1][x1][bin1] + grad_mag*(1-((x+1-Xc)/cwidth))*(1-((y+1-Yc)/cheight))*(1-((grad_or-Oc)/bin_size));
            h[y1][x1][bin2]= h[y1][x1][bin2] + grad_mag*(1-((x+1-Xc)/cwidth))*(1-((y+1-Yc)/cheight))*(((grad_or-Oc)/bin_size));
            h[y2][x1][bin1]= h[y2][x1][bin1] + grad_mag*(1-((x+1-Xc)/cwidth))*(((y+1-Yc)/cheight))*(1-((grad_or-Oc)/bin_size));
            h[y2][x1][bin2]= h[y2][x1][bin2] + grad_mag*(1-((x+1-Xc)/cwidth))*(((y+1-Yc)/cheight))*(((grad_or-Oc)/bin_size));
            h[y1][x2][bin1]= h[y1][x2][bin1] + grad_mag*(((x+1-Xc)/cwidth))*(1-((y+1-Yc)/cheight))*(1-((grad_or-Oc)/bin_size));
            h[y1][x2][bin2]= h[y1][x2][bin2] + grad_mag*(((x+1-Xc)/cwidth))*(1-((y+1-Yc)/cheight))*(((grad_or-Oc)/bin_size));
            h[y2][x2][bin1]= h[y2][x2][bin1] + grad_mag*(((x+1-Xc)/cwidth))*(((y+1-Yc)/cheight))*(1-((grad_or-Oc)/bin_size));
            h[y2][x2][bin2]= h[y2][x2][bin2] + grad_mag*(((x+1-Xc)/cwidth))*(((y+1-Yc)/cheight))*(((grad_or-Oc)/bin_size));
        }
    }

	//Block normalization

    for(unsigned int x=1; x<hist2-block_cols; x++)
	{
        for (unsigned int y=1; y<hist1-block_rows; y++)
		{
            
            block_norm=0;
            for (unsigned int i=0; i<block_rows; i++)
			{
                for(unsigned int j=0; j<block_cols; j++)
				{
                    for(unsigned int k=0; k<nb_bins; k++)
					{
                        block_norm+=h[y+i][x+j][k]*h[y+i][x+j][k];
                    }
                }
            }
            
            block_norm=sqrt(block_norm);
            for (unsigned int i=0; i<block_rows; i++)
			{
                for(unsigned int j=0; j<block_cols; j++)
				{
                    for(unsigned int k=0; k<nb_bins; k++)
					{
                        if (block_norm>0)
						{
                            block[i][j][k]=h[y+i][x+j][k]/block_norm;
                            if (block[i][j][k]>clip_val) block[i][j][k]=clip_val;
                        }
                    }
                }
            }
            
            block_norm=0;
            for (unsigned int i=0; i<block_rows; i++)
			{
                for(unsigned int j=0; j<block_cols; j++)
				{
                    for(unsigned int k=0; k<nb_bins; k++)
					{
                        block_norm+=block[i][j][k]*block[i][j][k];
                    }
                }
            }
            
            block_norm=sqrt(block_norm);
            for (unsigned int i=0; i<block_rows; i++)
			{
                for(unsigned int j=0; j<block_cols; j++)
				{
                    for(unsigned int k=0; k<nb_bins; k++)
					{
                        if (block_norm>0) 
						{
							features.at<float>(des_indx,0) = block[i][j][k]/block_norm;
						}
                        else 
						{
							features.at<float>(des_indx,0) = 0.0;
						}
						des_indx++;
                    }
                }
            }
        }
    }

	return features;
}
Пример #4
0
signed char CWorld::GetHeightPoint2( const CPointBase & pt, DWORD & wBlockFlags, bool fHouseCheck ) // Height of player who walked to X/Y/OLDZ
{
	ADDTOCALLSTACK("CWorld::GetHeightPoint2");
	// Given our coords at pt including pt.m_z
	// What is the height that gravity would put me at should i step hear ?
	// Assume my head height is PLAYER_HEIGHT/2
	// ARGS:
	//  pt = the point of interest.
	//  pt.m_z = my starting altitude.
	//  wBlockFlags = what we can pass thru. doors, water, walls ?
	//		CAN_C_GHOST	= Moves thru doors etc.	- CAN_I_DOOR						
	//		CAN_C_SWIM = walk thru water - CAN_I_WATER
	//		CAN_C_WALK = it is possible that i can step up. - CAN_I_PLATFORM
	//		CAN_C_PASSWALLS	= walk through all blocking items - CAN_I_BLOCK
	//		CAN_C_FLY  = gravity does not effect me. - CAN_I_CLIMB
	//		CAN_C_FIRE_IMMUNE = i can walk into lava etc. - CAN_I_FIRE
	//  pRegion = possible regional effects. (multi's)
	// RETURN:
	//  pt.m_z = Our new height at pt.m_x,pt.m_y
	//  wBlockFlags = our blocking flags at the given location. CAN_I_WATER,CAN_C_WALK,CAN_FLY,CAN_SPIRIT,
	//    CAN_C_INDOORS = i am covered from the sky
	//

	// ??? NOTE: some creatures should be taller than others !!!

	DWORD dwCan = wBlockFlags;
	CGrayMapBlockState block(wBlockFlags, pt.m_z, PLAYER_HEIGHT);

	GetHeightPoint2( pt, block, fHouseCheck );

	// Pass along my results.
	wBlockFlags = block.m_Bottom.m_dwBlockFlags;
	if (block.m_Top.m_dwBlockFlags)
	{
		wBlockFlags |= CAN_I_ROOF;	// we are covered by something.

		// Do not check for landtiles to block me. We pass through if statics are under them
		if (block.m_Top.m_dwTile > TERRAIN_QTY)
		{
			// If this tile possibly blocks me, roof cannot block me
			if (block.m_Top.m_dwBlockFlags &~(CAN_I_ROOF))
			{
				if (block.m_Top.m_z < block.m_Bottom.m_z + PLAYER_HEIGHT)
					wBlockFlags |= CAN_I_BLOCK; // we can't fit under this!
			}
		}
	}

	if (( block.m_Lowest.m_dwBlockFlags & CAN_I_HOVER ) || ( block.m_Bottom.m_dwBlockFlags & CAN_I_HOVER ) || ( block.m_Top.m_dwBlockFlags & CAN_I_HOVER ))
	{
		if ( dwCan & CAN_C_HOVER )
			wBlockFlags = 0; // we can hover over this
		else
			wBlockFlags &= ~CAN_I_HOVER; // we don't have the ability to fly
	}

	if (( wBlockFlags & ( CAN_I_CLIMB|CAN_I_PLATFORM) ) && ( dwCan & CAN_C_WALK ))
	{
		wBlockFlags &= ~CAN_I_CLIMB;
		wBlockFlags |= CAN_I_PLATFORM;	// not really true but hack it anyhow.
		return( block.m_Bottom.m_z );
	}

	if ( dwCan & CAN_C_FLY )
		return( pt.m_z );

	return( block.m_Bottom.m_z );
}
int32_t ompi_datatype_create_darray(int size,
                                    int rank,
                                    int ndims,
                                    int const* gsize_array,
                                    int const* distrib_array,
                                    int const* darg_array,
                                    int const* psize_array, 
                                    int order,
                                    const ompi_datatype_t* oldtype,
                                    ompi_datatype_t** newtype)
{
    ompi_datatype_t *lastType;
    ptrdiff_t orig_extent, *st_offsets = NULL;
    int i, start_loop, end_loop, step;
    int *coords = NULL, rc = OMPI_SUCCESS;

    /* speedy corner case */
    if (ndims < 1) {
        /* Don't just return MPI_DATATYPE_NULL as that can't be
           MPI_TYPE_FREE()ed, and that seems bad */
        *newtype = ompi_datatype_create(0);
        ompi_datatype_add(*newtype, &ompi_mpi_datatype_null.dt, 0, 0, 0);
        return MPI_SUCCESS;
    }

    rc = ompi_datatype_type_extent(oldtype, &orig_extent);
    if (MPI_SUCCESS != rc) goto cleanup;

    /* calculate position in grid using row-major ordering */
    {
        int tmp_rank = rank, procs = size;

        coords = (int *) malloc(ndims * sizeof(int));
        for (i = 0 ; i < ndims ; i++) {
            procs = procs / psize_array[i];
            coords[i] = tmp_rank / procs;
            tmp_rank = tmp_rank % procs;
        }
    }

    st_offsets = (ptrdiff_t *) malloc(ndims * sizeof(ptrdiff_t));

    /* duplicate type to here to 1) deal with constness without
       casting and 2) eliminate need to for conditional destroy below.
       Lame, yes.  But cleaner code all around. */
    rc = ompi_datatype_duplicate(oldtype, &lastType);
    if (OMPI_SUCCESS != rc) goto cleanup;

    /* figure out ordering issues */
    if (MPI_ORDER_C == order) {
        start_loop = ndims - 1 ; step = -1; end_loop = -1;
    } else {
        start_loop = 0 ; step = 1; end_loop = ndims;
    }

    /* Build up array */
    for (i = start_loop; i != end_loop; i += step) {
        int nprocs, tmp_rank;

        switch(distrib_array[i]) {
        case MPI_DISTRIBUTE_BLOCK:
            rc = block(gsize_array, i, ndims, psize_array[i], coords[i],
                       darg_array[i], order, orig_extent,
                       lastType, newtype, st_offsets+i);
            break;
        case MPI_DISTRIBUTE_CYCLIC:
            rc = cyclic(gsize_array, i, ndims, psize_array[i], coords[i],
                        darg_array[i], order, orig_extent,
                        lastType, newtype, st_offsets+i);
            break;
        case MPI_DISTRIBUTE_NONE:
            /* treat it as a block distribution on 1 process */
            if (order == MPI_ORDER_C) {
                nprocs = psize_array[i]; tmp_rank = coords[i];
            } else {
                nprocs = 1; tmp_rank = 0;
            }

            rc = block(gsize_array, i, ndims, nprocs, tmp_rank,
                       MPI_DISTRIBUTE_DFLT_DARG, order, orig_extent,
                       lastType, newtype, st_offsets+i);
            break;
        default:
            rc = MPI_ERR_ARG;
        }
        ompi_datatype_destroy(&lastType);
        /* need to destroy the old type even in error condition, so
           don't check return code from above until after cleanup. */
        if (MPI_SUCCESS != rc) goto cleanup;
        lastType = *newtype;
    }


    /* set displacement and UB correctly. Use struct instead of
       resized for same reason as subarray */
    {
        ptrdiff_t displs[3];
        ompi_datatype_t *types[3];
        int tmp_size, blength[3] = { 1, 1, 1};

        displs[1] = st_offsets[start_loop];
        tmp_size = 1;
        for (i = start_loop + step ; i != end_loop ; i += step) {
            tmp_size *= gsize_array[i - step];
            displs[1] += tmp_size * st_offsets[i];
        }

        displs[0] = 0;
        displs[1] *= orig_extent;
        displs[2] = orig_extent;
        for (i = 0 ; i < ndims ; i++) {
            displs[2] *= gsize_array[i];
        }
        types[0] = MPI_LB; types[1] = lastType; types[2] = MPI_UB;

        rc = ompi_datatype_create_struct(3, blength, displs, types, newtype);
        ompi_datatype_destroy(&lastType);
        /* need to destroy the old type even in error condition, so
           don't check return code from above until after cleanup. */
        if (MPI_SUCCESS != rc) goto cleanup;
    }

 cleanup:
    if (NULL != st_offsets) free(st_offsets);
    if (NULL != coords) free(coords);
    return OMPI_SUCCESS;
}
  void
  CachedQuarkletProblem<PROBLEM>::add_level (const Index& lambda,
				     //InfiniteVector<double, Index>& w,
				     Vector<double>& w,
				     const int j,
				     const double factor,
				     const int J,
				     const CompressionStrategy strategy,
                                     const int jmax,
                                     const int pmax,          
                                     const double a,
                                     const double b) const
  {
//      cout << "bin in addlevel drin" << endl;
//      cout << lambda << endl;
//      cout << j << endl;
      
//      WaveletBasis mybasis(basis());
      
      const int minplevel = std::max(0, lambda.p() + 1  - (int) pow(2,(J-b*abs(j-lambda.j())/a)));
      const int maxplevel = std::min(lambda.p() - 1  + (int) pow(2,(J-b*abs(j-lambda.j())/a)), pmax);

      
      const int lambda_num = number(lambda, jmax);
      //cout << lambda << ": " << lambda_num << endl;
      
      // search for column 'lambda'
      typedef std::list<Index> IntersectingList;
      typename ColumnCache::iterator col_lb(entries_cache.lower_bound(lambda_num));
      typename ColumnCache::iterator col_it(col_lb);
	 
      if (col_lb == entries_cache.end() ||
	  entries_cache.key_comp()(lambda_num,col_lb->first))
	{
	  // insert a new column
	  typedef typename ColumnCache::value_type value_type;
	  col_it = entries_cache.insert(col_lb, value_type(lambda_num, Column()));
	}

      Column& col(col_it->second);

      // check wether the level has already been calculated
      typename Column::iterator lb(col.lower_bound(j));
      typename Column::iterator it(lb);

      if (lb == col.end() ||
	  col.key_comp()(j, lb->first))
	{
	  // no entries have ever been computed for this column and this level
//         cout << "keine Einträge berechnet" << endl;
          
	  
	  // insert a new level
	  typedef typename Column::value_type value_type;
	  it = col.insert(lb, value_type(j, Block()));

	  
          Block& block(it->second);
          
          
          IntersectingList nus;
          
          
          //DKR strategy
          
//          cout << lambda << endl;
//          cout << j << endl;
//          cout << J << endl;
          //cout << minplevel << endl;
          //cout << maxplevel << endl;
          
         for(int p = minplevel; p<=maxplevel; ++p){
//             cout << "Hallo" << endl;
          intersecting_wavelets(basis(), lambda,
				std::max(j, basis().j0()),
				j == (basis().j0()-1),
				nus, p);
          
          
          
          

	  
	  // do the rest of the job
	  const double d1 = problem->D(lambda);
//          cout << d1 << endl;
          
	    for (typename IntersectingList::const_iterator it2(nus.begin()), itend2(nus.end());
		 it2 != itend2; ++it2) {
                
	      const double entry = problem->a(*it2, lambda);
 //             cout << *it2 << ", " << entry << endl;
	      typedef typename Block::value_type value_type_block;
	      if (entry != 0.) {
 //                 cout << "ja3" << endl;
		block.insert(block.end(), value_type_block(number(*it2,jmax), entry));
	      //w.add_coefficient(*it2, (entry / (d1 * problem->D(*it2))) * factor);
 //               cout << *it2 << ": " << (*it2).number() << endl;
 //             cout <<  number(*it2,jmax) << endl;
 //               cout << w.size() << endl;
                w[number(*it2,jmax)] += (entry / (d1*problem->D(*it2))) * factor;
                //cout << "ja5" << endl;
	      }
 //             cout << "ja1" << endl;
	    }
//	  cout << "ja2" << endl;
         }

        
	}
      else {
          //cout << "Einträge schon berechnet" << endl;
	// level already exists --> extract level from cache

	
          //cout << "Iterator: " << it->first << endl;
          Block& block(it->second);
        
	
	const double d1 = problem->D(lambda);
	
	//cout << "Länge w: " << w.size() << endl;
	  for (typename Block::const_iterator it2(block.begin()), itend2(block.end());
	       it2 != itend2; ++it2) {
//              w.add_coefficient(*(problem->basis().get_wavelet(it2->first)),
// 			      (it2->second / (d1 * problem->D( *(problem->basis().get_wavelet(it2->first)) )))  * factor);
                    //cout << it2->second << endl;
                    //cout << it2->first << endl;
              
                    w[it2->first] += (it2->second / (d1*problem->D(*(problem->basis().get_wavelet(it2->first))))) * factor;
                }
	
      }// end else
    
    
  }
Пример #7
0
void IsometricTileRenderer::renderTile(const TilePos& tile_pos, RGBAImage& tile) {
	// some vars, set correct image size
	int block_size = images->getBlockSize();
	tile.setSize(getTileSize(), getTileSize());

	// get the maximum count of water blocks
	// blitted about each over, until they are nearly opaque
	int max_water = images->getMaxWaterPreblit();

	// all visible blocks which are rendered in this tile
	std::set<RenderBlock> blocks;

	// iterate over the highest blocks in the tile
	// we use as tile position tile_pos+tile_offset because the offset means that
	// we treat the tile position as tile_pos, but it's actually tile_pos+tile_offset
	for (TileTopBlockIterator it(tile_pos, block_size, tile_width);
			!it.end(); it.next()) {
		// water render behavior n1:
		// are we already in a row of water?
		bool in_water = false;

		// water render behavior n2:
		// water counter, how many water blocks are at the moment in this row?
		int water = 0;

		// the render block objects in our current block row
		std::set<RenderBlock> row_nodes;
		// then iterate over the blocks, which are on the tile at the same position,
		// beginning from the highest block
		for (BlockRowIterator block(it.current); !block.end(); block.next()) {
			// get current chunk position
			mc::ChunkPos current_chunk_pos(block.current);

			// check if current chunk is not null
			// and if the chunk wasn't replaced in the cache (i.e. position changed)
			if (current_chunk == nullptr || current_chunk->getPos() != current_chunk_pos)
				// get chunk if not
				//if (!state.world->hasChunkSection(current_chunk, block.current.y))
				//	continue;
				current_chunk = world->getChunk(current_chunk_pos);
			if (current_chunk == nullptr) {
				// here is nothing (= air),
				// so reset state if we are in water
				in_water = false;
				continue;
			}

			// get local block position
			mc::LocalBlockPos local(block.current);

			// now get block id
			uint16_t id = current_chunk->getBlockID(local);
			// air is completely transparent so continue
			if (id == 0) {
				in_water = false;
				continue;
			}

			// now get the block data
			uint16_t data = current_chunk->getBlockData(local);

			// check if the render mode hides this block
			if (render_mode->isHidden(block.current, id, data))
				continue;

			bool is_water = (id == 8 || id == 9) && data == 0;
			if (is_water && !use_preblit_water) {
				// water render behavior n1:
				// render only the top sides of the water blocks
				// and darken the ground with the lighting data
				// used for lighting rendermode

				// if we are already in water, skip checking this water block
				if (is_water && in_water)
					continue;
				in_water = is_water;

			} else if (use_preblit_water) {
				// water render behavior n2:
				// render the top side of every water block
				// have also preblit water blocks to skip redundant alphablitting

				// no lighting is needed because the 'opaque-water-effect'
				// is created by blitting the top sides of the water blocks
				// one above the other

				if (!is_water) {
					// if not water, reset the counter
					water = 0;
				} else {
					water++;

					// when we have enough water in a row
					// we can stop searching more blocks
					// and replace the already added render blocks with a preblit water block
					if (water > max_water) {
						std::set<RenderBlock>::const_iterator it = row_nodes.begin();
						// iterate through the render blocks in this row
						while (it != row_nodes.end()) {
							std::set<RenderBlock>::const_iterator current = it++;
							// check if we have reached the top most water block
							if (it == row_nodes.end() || (it->id != 8 && it->id != 9)) {
								RenderBlock top = *current;
								row_nodes.erase(current);

								// check for neighbors
								mc::Block south, west;
								south = getBlock(top.pos + mc::DIR_SOUTH);
								west = getBlock(top.pos + mc::DIR_WEST);

								id = 8;
								data = OPAQUE_WATER;
								bool neighbor_south = !south.isFullWater();
								if (neighbor_south)
								//	data |= DATA_SOUTH;
									data |= OPAQUE_WATER_SOUTH;
								bool neighbor_west = !west.isFullWater();
								if (neighbor_west)
								//	data |= DATA_WEST;
									data |= OPAQUE_WATER_WEST;

								// get image and replace the old render block with this
								//top.image = images->getOpaqueWater(neighbor_south,
								//		neighbor_west);
								top.image = images->getBlock(id, data);

								// don't forget the render mode
								render_mode->draw(top.image, top.pos, id, data);

								row_nodes.insert(top);
								break;

							} else {
								// water render block
								row_nodes.erase(current);
							}
						}

						break;
					}
				}
			}

			// check for special data (neighbor related)
			// get block image, check for transparency, create render block...
			data = checkNeighbors(block.current, id, data);
			//if (is_water && (data & DATA_WEST) && (data & DATA_SOUTH))
			//	continue;
			RGBAImage image;
			bool transparent = images->isBlockTransparent(id, data);

			// check for biome data
			if (Biome::isBiomeBlock(id, data))
				image = images->getBiomeBlock(id, data, getBiomeOfBlock(block.current, current_chunk));
			else
				image = images->getBlock(id, data);

			RenderBlock node;
			node.x = it.draw_x;
			node.y = it.draw_y;
			node.pos = block.current;
			node.image = image;
			node.id = id;
			node.data = data;

			// let the render mode do their magic with the block image
			render_mode->draw(node.image, node.pos, id, data);

			// insert into current row
			row_nodes.insert(node);

			// if this block is not transparent, then break
			if (!transparent)
				break;
		}

		// iterate through the created render blocks
		for (std::set<RenderBlock>::const_iterator it = row_nodes.begin();
		        it != row_nodes.end(); ++it) {
			std::set<RenderBlock>::const_iterator next = it;
			next++;
			// insert render block to
			if (next == row_nodes.end()) {
				blocks.insert(*it);
			} else {
				// skip unnecessary leaves
				if (it->id == 18 && next->id == 18 && (next->data & 3) == (it->data & 3))
					continue;
				blocks.insert(*it);
			}
		}
	}

	// now blit all blocks
	for (std::set<RenderBlock>::const_iterator it = blocks.begin(); it != blocks.end();
			++it) {
		tile.alphaBlit(it->image, it->x, it->y);
	}
}
// input/ouput handler function to be called on thread
void *io_handler(void *param, int socket_fd) {

	char command[MAXCOMMANDSIZE];	// For receiving commands from user
	int exitsignal;		// If user wants to end the application (Command: EXIT, value: 8)


	// Main process loop for client
	while(fgets(command, sizeof command, stdin)) {
		
		// Manual removal of newline character
		int len = strlen(command);
		if (len > 0 && command[len-1] == '\n') {
			command[len-1] = '\0';
		}
		allCaps(command);

		// parse the command, check if either single or double arg command
		int token_count = 0;
		int idx = 1;
		char* pch;

		char s[2][MAXCOMMANDSIZE];
		memset(s[0], "", MAXCOMMANDSIZE);
		memset(s[1], "", MAXCOMMANDSIZE);

		int isnul = strlen(command);
		if (isnul == 0)
			continue;

		pch = strtok(command, " ");
		strcpy(s[0], pch);
		while (pch != NULL)
	  	{
	  		pch = strtok(NULL, " ");
			if (pch != NULL) {
				strcpy(s[1], pch);
		    	idx++;
		    	if (idx > 1)
		    		break;
		    }
	    }

		if (idx == 1) {
			char* c1 = &s[0];
			if(!strcmp(c1, "EXIT")) {
				/* clean up */
				printf("Terminating server...\n");
				close(socket_fd);
				exit(0);
			}
			else if(!strcmp(c1, "START")){
				ready = 1;
				enable_stats = 1;
				if (abs_start == 0)
					abs_start = 1;
				else
					printf("Server ready: waiting for connections...\n");
			}
			else if(!strcmp(c1, "STATS")){
				if (enable_stats == 0)
					printf ("Server still inactive\n");
				else
					stats();
			}
			else if (!strcmp(c1, "END")){
				printf ("Server terminating...\n");
				end();
				printf ("...done\n");
			}
			else {
				fprintf(stderr, "Unknown command: %s...\n", command);
			}
		}
		else if (idx == 2) {
			char* c1 = &s[0];
			char* c2 = &s[1];
			if(!strcmp(c1, "BLOCK")){
				int socket = atoi(c2);
				printf("Blocking socket %d\n", socket);
				block(socket);
			}
			else if(!strcmp(c1, "UNBLOCK")){
				int socket = atoi(c2);
				printf("Unblocking socket %d\n", socket);
				unblock(socket);
			}
			else if(!strcmp(c1, "THROWOUT")) {
				int socket = atoi(c2);
				printf("Throwing out socket %d\n", socket);
				throwout(socket);
			}
			else {
				fprintf(stderr, "Unknown command: %s...\n", command);
			}
		}
		else {
			fprintf(stderr, "Unknown command: %s...\n", command);
		}
	}

	return NULL;
}
Пример #9
0
void GetBlockTemplateContext::updateWork()
{
  MutexLocker locker(&_mutex);
  _blockTemplateExists = false;
  
  const char *error;  
  json_error_t jsonError;
  json_t *response = json_loads(_response.c_str(), 0, &jsonError);
  if (!response) {
    logFormattedWrite(_log,
                      "getblocktemplate response JSON parsing error: %s",
                      _response.c_str());   
    return;
  }
  
  std::unique_ptr<blktemplate_t, std::function<void(blktemplate_t*)>> block(
    blktmpl_create(), [](blktemplate_t *b) { blktmpl_free(b); });
  
  for (unsigned i = 0; i < _blocksNum; i++) {
    if (_blocks[i]) {
      blktmpl_free(_blocks[i]);
      _blocks[i] = 0;
    }
  }
  
  error = blktmpl_add_jansson(block.get(), response, time(0));
  json_delete(response);
  if (error) {
    logFormattedWrite(_log, "Error %s", error);
    return;
  }

  for (unsigned i = 0; i < _blocksNum; i++) {
    unsigned char data[80];
    _cbscript_t opt_coinbase_script;    
     bool newcb;    
   
    error = set_b58addr(_wallet, &opt_coinbase_script);
    if (error) {
      logFormattedWrite(_log, "Error %s", error);
      return;
    }
    
    _blocks[i] = blktmpl_duplicate(block.get());
    uint64_t num = 
      blkmk_init_generation2(_blocks[i],
                             opt_coinbase_script.data,
                             opt_coinbase_script.sz,
                             &newcb);
      
    uint32_t extraNonce = (_extraNonce << 16) + i;
    ssize_t coinbaseAppendResult = blkmk_append_coinbase_safe(_blocks[i], &extraNonce, sizeof(extraNonce));
    if (coinbaseAppendResult < 0) {
      logFormattedWrite(_log, "cannot add extra nonce (error %i)", (int)coinbaseAppendResult);
      return; 
    }
      
    size_t dataSize = blkmk_get_data(_blocks[i], data, sizeof(data), time(0), NULL, &_dataId);
    if (!(dataSize >= 76 && dataSize <= sizeof(data))) {
      logFormattedWrite(_log, "getblocktemplate response decoding error (invalid size)");
      return;
    }      
  }
   
   if (_height != block->height)
     logFormattedWrite(_log, "new block detected: %u", block->height-1);
  _height = block->height;
  _difficulty = difficultyFromBits(*(uint32_t*)(&block->diffbits));
  _blockTemplateExists = true;
}
Пример #10
0
/* Cover both external declarations, functions, and local declarations (with
 * optional initialization code) inside functions.
 */
struct block *declaration(struct block *parent)
{
    struct typetree *base;
    enum symtype symtype;
    enum linkage linkage;
    int stc = '$';

    base = declaration_specifiers(&stc);
    switch (stc) {
    case EXTERN:
        symtype = SYM_DECLARATION;
        linkage = LINK_EXTERN;
        break;
    case STATIC:
        symtype = SYM_TENTATIVE;
        linkage = LINK_INTERN;
        break;
    case TYPEDEF:
        symtype = SYM_TYPEDEF;
        linkage = LINK_NONE;
        break;
    default:
        if (!ns_ident.current_depth) {
            symtype = SYM_TENTATIVE;
            linkage = LINK_EXTERN;
        } else {
            symtype = SYM_DEFINITION;
            linkage = LINK_NONE;
        }
        break;
    }

    while (1) {
        struct definition *def;
        const char *name = NULL;
        const struct typetree *type;
        struct symbol *sym;

        type = declarator(base, &name);
        if (!name) {
            consume(';');
            return parent;
        }

        sym = sym_add(&ns_ident, name, type, symtype, linkage);
        if (ns_ident.current_depth) {
            assert(ns_ident.current_depth > 1);
            def = current_func();
            def->locals = sym_list_add(def->locals, sym);
        }

        switch (peek().token) {
        case ';':
            consume(';');
            return parent;
        case '=':
            if (sym->symtype == SYM_DECLARATION) {
                error("Extern symbol '%s' cannot be initialized.", sym->name);
                exit(1);
            }
            if (!sym->depth && sym->symtype == SYM_DEFINITION) {
                error("Symbol '%s' was already defined.", sym->name);
                exit(1);
            }
            consume('=');
            sym->symtype = SYM_DEFINITION;
            if (sym->linkage == LINK_NONE) {
                assert(parent);
                parent = initializer(parent, var_direct(sym));
            } else {
                assert(sym->depth || !parent);
                def = push_back_definition(sym);
                initializer(def->body, var_direct(sym));
            }
            assert(size_of(&sym->type) > 0);
            if (peek().token != ',') {
                consume(';');
                return parent;
            }
            break;
        case '{': {
            int i;
            if (!is_function(&sym->type) || sym->depth) {
                error("Invalid function definition.");
                exit(1);
            }
            assert(!parent);
            assert(sym->linkage != LINK_NONE);
            sym->symtype = SYM_DEFINITION;
            def = push_back_definition(sym);
            push_scope(&ns_ident);
            define_builtin__func__(sym->name);
            for (i = 0; i < nmembers(&sym->type); ++i) {
                name = get_member(&sym->type, i)->name;
                type = get_member(&sym->type, i)->type;
                symtype = SYM_DEFINITION;
                linkage = LINK_NONE;
                if (!name) {
                    error("Missing parameter name at position %d.", i + 1);
                    exit(1);
                }
                def->params = sym_list_add(def->params,
                    sym_add(&ns_ident, name, type, symtype, linkage));
            }
            parent = block(def->body);
            pop_scope(&ns_ident);
            return parent;
        }
        default:
            break;
        }
        consume(',');
    }
}
Пример #11
0
 bool isStopped()
 {
     synchronized block(*this);
     return stopped;
 }
Пример #12
0
    void Consumer::ensureSetup()
    {
        if (!topicPtr.load(std::memory_order_acquire))
        {
            CriticalBlock block(lock);

            if (!topicPtr.load(std::memory_order_relaxed))
            {
                initFileOffsetIfNotExist();

                std::string errStr;
                RdKafka::Conf* globalConfig = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);

                if (globalConfig)
                {
                    // Set global configuration parameters, used mainly at the consumer level
                    globalConfig->set("metadata.broker.list", brokers, errStr);
                    globalConfig->set("compression.codec", "snappy", errStr);
                    globalConfig->set("queued.max.messages.kbytes", "10000000", errStr);
                    globalConfig->set("fetch.message.max.bytes", "10000000", errStr);

                    // Set any global configurations from file, allowing
                    // overrides of above settings
                    applyConfig("kafka_global.conf", globalConfig, traceLevel);

                    // Set consumer callbacks
                    globalConfig->set("event_cb", static_cast<RdKafka::EventCb*>(this), errStr);

                    // Create the consumer
                    consumerPtr = RdKafka::Consumer::create(globalConfig, errStr);

                    if (consumerPtr)
                    {
                        RdKafka::Conf* topicConfPtr = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);

                        // Set the per-topic configuration parameters
                        topicConfPtr->set("group.id", consumerGroup, errStr);
                        topicConfPtr->set("auto.offset.reset", "smallest", errStr);

                        // Set any topic configurations from file, allowing
                        // overrides of above settings
                        std::string confName = "kafka_consumer_topic_" + topic + ".conf";
                        applyConfig(confName.c_str(), topicConfPtr, traceLevel);

                        // Ensure that some items are set a certain way
                        // by setting them after loading the external conf
                        topicConfPtr->set("auto.commit.enable", "false", errStr);

                        // Create the topic
                        topicPtr.store(RdKafka::Topic::create(consumerPtr, topic, topicConfPtr, errStr), std::memory_order_release);

                        if (!topicPtr)
                        {
                            throw MakeStringException(-1, "Kafka: Unable to create consumer topic object for topic '%s'; error: '%s'", topic.c_str(), errStr.c_str());
                        }
                    }
                    else
                    {
                        throw MakeStringException(-1, "Kafka: Unable to create consumer object for brokers '%s'; error: '%s'", brokers.c_str(), errStr.c_str());
                    }
                }
                else
                {
                    throw MakeStringException(-1, "Kafka: Unable to create consumer global configuration object for brokers '%s'; error: '%s'", brokers.c_str(), errStr.c_str());
                }
            }
        }
    }
Пример #13
0
    void Publisher::ensureSetup()
    {
        if (!topicPtr.load(std::memory_order_acquire))
        {
            CriticalBlock   block(lock);

            if (!topicPtr.load(std::memory_order_relaxed))
            {
                std::string errStr;
                RdKafka::Conf* globalConfig = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);

                if (globalConfig)
                {
                    // Set global configuration parameters, used mainly at the producer level
                    globalConfig->set("metadata.broker.list", brokers, errStr);
                    globalConfig->set("queue.buffering.max.messages", "1000000", errStr);
                    globalConfig->set("compression.codec", "snappy", errStr);
                    globalConfig->set("message.send.max.retries", "3", errStr);
                    globalConfig->set("retry.backoff.ms", "500", errStr);

                    // Set any global configurations from file, allowing
                    // overrides of above settings
                    applyConfig("kafka_global.conf", globalConfig, traceLevel);

                    // Set producer callbacks
                    globalConfig->set("event_cb", static_cast<RdKafka::EventCb*>(this), errStr);
                    globalConfig->set("dr_cb", static_cast<RdKafka::DeliveryReportCb*>(this), errStr);

                    // Create the producer
                    producerPtr = RdKafka::Producer::create(globalConfig, errStr);

                    if (producerPtr)
                    {
                        RdKafka::Conf* topicConfPtr = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);

                        // Set any topic configurations from file
                        std::string confName = "kafka_publisher_topic_" + topic + ".conf";
                        applyConfig(confName.c_str(), topicConfPtr, traceLevel);

                        // Create the topic
                        topicPtr.store(RdKafka::Topic::create(producerPtr, topic, topicConfPtr, errStr), std::memory_order_release);

                        if (topicPtr)
                        {
                            // Start the attached background poller
                            pollerPtr->start();
                        }
                        else
                        {
                            throw MakeStringException(-1, "Kafka: Unable to create producer topic object for topic '%s'; error: '%s'", topic.c_str(), errStr.c_str());
                        }
                    }
                    else
                    {
                        throw MakeStringException(-1, "Kafka: Unable to create producer object for brokers '%s'; error: '%s'", brokers.c_str(), errStr.c_str());
                    }
                }
                else
                {
                    throw MakeStringException(-1, "Kafka: Unable to create producer global configuration object for brokers '%s'; error: '%s'", brokers.c_str(), errStr.c_str());
                }
            }
        }
    }
void ScCodeEditor::matchBrackets()
{
    mBracketSelections.clear();

    QTextCursor cursor(textCursor());
    QTextBlock block( cursor.block() );
    int posInBlock = cursor.positionInBlock();
    TokenIterator it(block);
    while (it.isValid() && it.block() == block)
    {
        const Token & token = *it;
        if (token.positionInBlock > posInBlock) {
            it = TokenIterator();
            break;
        } else if (
            (token.positionInBlock == posInBlock && token.type == Token::OpeningBracket) ||
            (token.positionInBlock == posInBlock - 1 && token.type == Token::ClosingBracket)
        )
            break;
        ++it;
    }

    if (!it.isValid() || it.block() != block) {
        updateExtraSelections();
        return;
    }

    BracketPair match;
    matchBracket( it, match );

    if( match.first.isValid() && match.second.isValid() )
    {
        const Token & tok1 = *match.first;
        const Token & tok2 = *match.second;

        if (
            (tok1.character == '(' && tok2.character == ')')
            || (tok1.character == '[' && tok2.character == ']')
            || (tok1.character == '{' && tok2.character == '}')
        ){
            QTextEdit::ExtraSelection selection;
            selection.format = mBracketHighlight;

            cursor.setPosition(match.first.position());
            cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
            selection.cursor = cursor;
            mBracketSelections.append(selection);

            cursor.setPosition(match.second.position());
            cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
            selection.cursor = cursor;
            mBracketSelections.append(selection);
        }
        else {
            QTextEdit::ExtraSelection selection;
            selection.format = mBracketMismatchFormat;
            cursor.setPosition(match.first.position());
            cursor.setPosition(match.second.position()+1, QTextCursor::KeepAnchor);
            selection.cursor = cursor;
            mBracketSelections.append(selection);
        }
    }
    else
    {
        if ( it.type() == Token::OpeningBracket ) {
            cursor.setPosition(it.position());
            cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
        }
        else {
            cursor.setPosition(it.position() + 1);
            cursor.movePosition(QTextCursor::Start, QTextCursor::KeepAnchor);
        }
        QTextEdit::ExtraSelection selection;
        selection.format = mBracketMismatchFormat;
        selection.cursor = cursor;
        mBracketSelections.append(selection);
    }

    updateExtraSelections();
}
Пример #15
0
void main_help()
{
    cout << block(main_help_str, 0, 80) << endl;
}
Пример #16
0
 const Block::header_t* header() const { return &(block()->_header); }
Пример #17
0
/* clocal() is called to do local transformations on
 * an expression tree preparitory to its being
 * written out in intermediate code.
 *
 * the major essential job is rewriting the
 * automatic variables and arguments in terms of
 * REG and OREG nodes
 * conversion ops which are not necessary are also clobbered here
 * in addition, any special features (such as rewriting
 * exclusive or) are easily handled here as well
 */
NODE *
clocal(NODE *p)
{

	register struct symtab *q;
	register NODE *r, *l;
	register int o;
	TWORD t;

#ifdef PCC_DEBUG
	if (xdebug) {
		printf("clocal: %p\n", p);
		fwalk(p, eprint, 0);
	}
#endif
	switch( o = p->n_op ){

	case NAME:
		if ((q = p->n_sp) == NULL)
			return p; /* Nothing to care about */

		switch (q->sclass) {

		case PARAM:
		case AUTO:
			/* fake up a structure reference */
			r = block(REG, NIL, NIL, PTR+STRTY, 0, 0);
			slval(r, 0);
			r->n_rval = FPREG;
			p = stref(block(STREF, r, p, 0, 0, 0));
			break;

		case REGISTER:
			p->n_op = REG;
			slval(p, 0);
			p->n_rval = q->soffset;
			break;

		case USTATIC:
		case STATIC:
			if (kflag == 0)
				break;
			if (blevel > 0 && !statinit)
				p = picstatic(p);
			break;

		case EXTERN:
		case EXTDEF:
			if (kflag == 0)
				break;
			if (blevel > 0 && !statinit)
				p = picext(p);
			break;
		}
		break;

	case ADDROF:
		if (kflag == 0 || blevel == 0 || statinit)
			break;
		/* char arrays may end up here */
		l = p->n_left;
		if (l->n_op != NAME ||
		    (l->n_type != ARY+CHAR && l->n_type != ARY+WCHAR_TYPE))
			break;
		l = p;
		p = picstatic(p->n_left);
		nfree(l);
		if (p->n_op != UMUL)
			cerror("ADDROF error");
		l = p;
		p = p->n_left;
		nfree(l);
		break;

	case STASG: /* convert struct assignment to call memcpy */
		l = p->n_left;
		if (l->n_op == NAME && ISFTN(l->n_sp->stype))
			break; /* struct return, do nothing */
		/* first construct arg list */
		p->n_left = buildtree(ADDROF, p->n_left, 0);
		r = bcon(tsize(STRTY, p->n_df, p->n_ap)/SZCHAR);
		p->n_left = buildtree(CM, p->n_left, p->n_right);
		p->n_right = r;
		p->n_op = CM;
		p->n_type = INT;

		r = block(NAME, NIL, NIL, INT, 0, 0);
		r->n_sp = lookup(addname("memcpy"), SNORMAL);
		if (r->n_sp->sclass == SNULL) {
			r->n_sp->sclass = EXTERN;
			r->n_sp->stype = INCREF(VOID+PTR)+(FTN-PTR);
		}
		r->n_type = r->n_sp->stype;
		p = buildtree(CALL, r, p);
		break;

	case SCONV:
		l = p->n_left;
		if (l->n_op == ICON && ISPTR(l->n_type)) {
			/* Do immediate cast here */
			/* Should be common code */
			q = l->n_sp;
			l->n_sp = NULL;
			l->n_type = UNSIGNED;
			if (concast(l, p->n_type) == 0)
				cerror("clocal");
			p = nfree(p);
			p->n_sp = q;
		}
		break;

	case FORCE:
		/* put return value in return reg */
		p->n_op = ASSIGN;
		p->n_right = p->n_left;
		p->n_left = block(REG, NIL, NIL, p->n_type, 0, 0);
		t = p->n_type;
		if (ISITY(t))
			t = t - (FIMAG-FLOAT);
		p->n_left->n_rval = RETREG(t);
		break;
	}
#ifdef PCC_DEBUG
	if (xdebug) {
		printf("clocal end: %p\n", p);
		fwalk(p, eprint, 0);
	}
#endif
	return(p);
}
Пример #18
0
RIFActionBlock RIFActionBlock::parse(DPtr<uint8_t> *utf8str)
    throw(BadAllocException, SizeUnknownException,
          InvalidCodepointException, InvalidEncodingException,
          MalformedIRIRefException, TraceableException) {
  if (utf8str == NULL) {
    THROW(TraceableException, "utf8str must not be NULL.");
  }
  if (!utf8str->sizeKnown()) {
    THROWX(SizeUnknownException);
  }
  const uint8_t *begin = utf8str->dptr();
  const uint8_t *end = begin + utf8str->size();
  const uint8_t *mark = begin;
  for (; mark != end && is_space(*mark); ++mark) {
    // find beginning of action block
  }
  if (end - mark < 4) {
    THROW(TraceableException, "Could not find action block.");
  }
  if (ascii_strncmp(mark, "Do", 2) != 0) {
    THROW(TraceableException, "Action block must start with \"Do\".");
  }
  mark += 2;
  for (; mark != end && is_space(*mark); ++mark) {
    // search for left parenthesis
  }
  if (mark == end || *mark != to_ascii('(')) {
    THROW(TraceableException, "Could not find opening parenthesis.");
  }
  for (--end; end != mark && is_space(*end); --end) {
    // find right parenthesis
  }
  if (end == mark || *end != to_ascii(')')) {
    THROW(TraceableException, "Could not find closing parenthesis.");
  }
  for (--end; end != mark && is_space(*end); --end) {
    // find end of last action
  }
  ++end;
  for (++mark; mark != end && is_space(*mark); ++mark) {
    // find first binding or action
  }
  if (mark == end) {
    THROW(TraceableException, "Action block is (illegaly) empty.");
  }
  deque<RIFAction> actions;
  ActVarMap bindings(RIFVar::cmplt0);
  bool find_bindings = (*mark == to_ascii('('));
  const uint8_t *bound = mark;
  while (bound != end) {
    for (; bound != end && *bound != to_ascii(')'); ++bound) {
      // find end of action block binding or action... maybe
    }
    if (bound != end) {
      ++bound;
    }
    DPtr<uint8_t> *str = utf8str->sub(mark - begin, bound - mark);
    if (find_bindings) {
      try {
        RIFActVarBind bind = RIFActVarBind::parse(str);
        str->drop();
        str = NULL;
        pair<ActVarMap::iterator, bool> p = bindings.insert(
            pair<RIFVar, RIFActVarBind>(bind.getActVar(), bind));
        if (!p.second) {
          THROW(TraceableException,
                "Cannot have multiple bindings for same action variable.");
        }
      } catch (BadAllocException &e) {
        str->drop();
        RETHROW(e, "Cannot parse action variable binding.");
      } catch (InvalidCodepointException &e) {
        str->drop();
        RETHROW(e, "Cannot parse action variable binding.");
      } catch (InvalidEncodingException &e) {
        str->drop();
        RETHROW(e, "Cannot parse action variable binding.");
      } catch (MalformedIRIRefException &e) {
        str->drop();
        continue;
      } catch (TraceableException &e) {
        if (str == NULL) {
          RETHROW(e, "Malformed action block.");
        }
        str->drop();
        continue;
      }
    } else {
      try {
        RIFAction act = RIFAction::parse(str);
        str->drop();
        actions.push_back(act);
      } catch (BadAllocException &e) {
        str->drop();
        RETHROW(e, "Cannot parse action.");
      } catch (InvalidCodepointException &e) {
        str->drop();
        RETHROW(e, "Cannot parse action.");
      } catch (InvalidEncodingException &e) {
        str->drop();
        RETHROW(e, "Cannot parse action.");
      } catch (MalformedIRIRefException &e) {
        str->drop();
        continue;
      } catch (TraceableException &e) {
        str->drop();
        continue;
      }
    }
    for (mark = bound; mark != end && is_space(*mark); ++mark) {
      // find beginning of next action block binding or action... maybe
    }
    bound = mark;
    find_bindings = find_bindings && (*mark == to_ascii('('));
  }
  DPtr<RIFAction> *pact;
  try {
    NEW(pact, APtr<RIFAction>, actions.size());
  } RETHROW_BAD_ALLOC
  copy(actions.begin(), actions.end(), pact->dptr());
  try {
    RIFActionBlock block(pact, bindings);
    pact->drop();
    return block;
  } catch (TraceableException &e) {
    pact->drop();
    RETHROW(e, "Cannot parse action block.");
  }
}
  double
  CachedQuarkletProblem<PROBLEM>::a(const Index& lambda,
			    const Index& nu) const
  {
      
      //const int lambda_num = number(lambda,2);
      double r = 0;
      
      WaveletBasis mybasis(basis());
      
      
      const int jmax = mybasis.get_jmax_();
      const int pmax = mybasis.get_pmax_();
      const int lambda_num = number(lambda, jmax);
      const int nu_num = number(nu,jmax);
      
      //cout << "Punkt 1" << endl;
      // BE CAREFUL: KEY OF GENERATOR LEVEL IS j0-1 NOT j0 !!!!
      typedef typename Index::type_type generator_type;
      int j = (lambda.e() == generator_type()) ? (lambda.j()-1) : lambda.j();
      
      // check wether entry has already been computed
      typedef std::list<Index> IntersectingList;

      // search for column 'nu'
      typename ColumnCache::iterator col_lb(entries_cache.lower_bound(nu_num));
      typename ColumnCache::iterator col_it(col_lb);
      
      if (col_lb == entries_cache.end() ||
	  entries_cache.key_comp()(nu_num, col_lb->first))
	
	{
	  // insert a new column
	  typedef typename ColumnCache::value_type value_type;
	  col_it = entries_cache.insert(col_lb, value_type(nu_num, Column()));
	}
	 //cout << "Punkt 2" << endl; 
      Column& col(col_it->second);
      
      // check wether the level 'lambda' belongs to has already been calculated
      typename Column::iterator lb(col.lower_bound(j));
      typename Column::iterator it(lb);
      // no entries have ever been computed for this column and this level
      if (lb == col.end() ||
	  col.key_comp()(j, lb->first))
	{
         //cout << "Punkt 3" << endl; 
	  // compute whole level block
	  // #### ONLY CDD COMPRESSION STRATEGY IMPLEMENTED ####
	  // #### MAYBE WE ADD TRUNK FOR STEVENSON APPROACH ####
	  // #### LATER.                                    ####
	  
	  // insert a new level
	  typedef typename Column::value_type value_type;
	  it = col.insert(lb, value_type(j, Block()));

	  Block& block(it->second);	  

	  IntersectingList nus;
          
          for(int p=0; p<=pmax; p++){
	   
            intersecting_wavelets(basis(), nu,
                                  std::max(j, basis().j0()),
                                  j == (basis().j0()-1),
                                  nus, p);
//            for (typename IntersectingList::const_iterator it100(nus.begin()), itend(nus.end());
//                   it100 != itend; ++it100) {
//                cout << *it100 << endl;
//            }
            

	  // compute entries
            for (typename IntersectingList::const_iterator it(nus.begin()), itend(nus.end());
                   it != itend; ++it) {
                const double entry = problem->a(*it, nu);
//                cout << *it << ", " << nu << ": " << entry << endl;
//                cout << (*it).number()+(*it).p()*waveletsonplevel << endl;
                typedef typename Block::value_type value_type_block;
                if (entry != 0.) {
                    block.insert(block.end(), value_type_block(number(*it,jmax), entry));
                    if (number(*it,jmax) == lambda_num) {
                        r = entry;
                    }
                }
            }
          }
          //cout << "nu" << nu << endl;
          //cout << block.end() << endl;
	}
      // level already exists --> extract row corresponding to 'lambda'
      else {
	  //cout << "ja" << endl;
          Block& block(it->second);

 	//typename Block::iterator block_lb(block.lower_bound(lambda));
	typename Block::iterator block_lb(block.lower_bound(lambda_num));
 	typename Block::iterator block_it(block_lb);
	// level exists, but in row 'lambda' no entry is available ==> entry must be zero
	if (block_lb == block.end() ||
	    block.key_comp()(lambda_num, block_lb->first))
	  {
	    r = 0;
	  }
	else {
	  r = block_it->second;
	}
      }
        
    
    return r;
  }
Пример #20
0
void V8LazyEventListener::prepareListenerObject(ExecutionContext* executionContext)
{
    if (!executionContext)
        return;

    // A ScriptState used by the event listener needs to be calculated based on
    // the ExecutionContext that fired the the event listener and the world
    // that installed the event listener.
    v8::HandleScope handleScope(toIsolate(executionContext));
    v8::Local<v8::Context> v8Context = toV8Context(executionContext, world());
    if (v8Context.IsEmpty())
        return;
    ScriptState* scriptState = ScriptState::from(v8Context);
    if (!scriptState->contextIsValid())
        return;

    if (!executionContext->isDocument())
        return;

    if (!toDocument(executionContext)->allowInlineEventHandlers(m_node, this, m_sourceURL, m_position.m_line)) {
        clearListenerObject();
        return;
    }

    if (hasExistingListenerObject())
        return;

    ScriptState::Scope scope(scriptState);

    // Nodes other than the document object, when executing inline event
    // handlers push document, form owner, and the target node on the scope chain.
    // We do this by using 'with' statement.
    // See fast/forms/form-action.html
    //     fast/forms/selected-index-value.html
    //     fast/overflow/onscroll-layer-self-destruct.html
    HTMLFormElement* formElement = 0;
    if (m_node && m_node->isHTMLElement())
        formElement = toHTMLElement(m_node)->formOwner();

    v8::Local<v8::Object> scopes[3];

    scopes[2] = toObjectWrapper<Node>(m_node, scriptState);
    scopes[1] = toObjectWrapper<HTMLFormElement>(formElement, scriptState);
    scopes[0] = toObjectWrapper<Document>(m_node ? m_node->ownerDocument() : 0, scriptState);

    v8::Local<v8::String> parameterName = v8String(isolate(), m_eventParameterName);
    v8::ScriptOrigin origin(
        v8String(isolate(), m_sourceURL),
        v8::Integer::New(isolate(), m_position.m_line.zeroBasedInt()),
        v8::Integer::New(isolate(), m_position.m_column.zeroBasedInt()),
        v8::True(isolate()),
        v8::Local<v8::Integer>(),
        v8::True(isolate()));
    v8::ScriptCompiler::Source source(v8String(isolate(), m_code), origin);

    v8::Local<v8::Function> wrappedFunction;
    {
        // JavaScript compilation error shouldn't be reported as a runtime
        // exception because we're not running any program code.  Instead,
        // it should be reported as an ErrorEvent.
        v8::TryCatch block(isolate());
        wrappedFunction = v8::ScriptCompiler::CompileFunctionInContext(isolate(), &source, v8Context, 1, &parameterName, 3, scopes);
        if (block.HasCaught()) {
            fireErrorEvent(v8Context, executionContext, block.Message());
            return;
        }
    }

    // Change the toString function on the wrapper function to avoid it
    // returning the source for the actual wrapper function. Instead it
    // returns source for a clean wrapper function with the event
    // argument wrapping the event source code. The reason for this is
    // that some web sites use toString on event functions and eval the
    // source returned (sometimes a RegExp is applied as well) for some
    // other use. That fails miserably if the actual wrapper source is
    // returned.
    v8::Local<v8::Function> toStringFunction = v8::Function::New(isolate(), V8LazyEventListenerToString);
    if (toStringFunction.IsEmpty())
        return;
    String toStringString = "function " + m_functionName + "(" + m_eventParameterName + ") {\n  " + m_code + "\n}";
    V8HiddenValue::setHiddenValue(scriptState, wrappedFunction, V8HiddenValue::toStringString(isolate()), v8String(isolate(), toStringString));
    if (!v8CallBoolean(wrappedFunction->Set(scriptState->context(), v8AtomicString(isolate(), "toString"), toStringFunction)))
        return;
    wrappedFunction->SetName(v8String(isolate(), m_functionName));

    // FIXME: Remove the following comment-outs.
    // See https://bugs.webkit.org/show_bug.cgi?id=85152 for more details.
    //
    // For the time being, we comment out the following code since the
    // second parsing can happen.
    // // Since we only parse once, there's no need to keep data used for parsing around anymore.
    // m_functionName = String();
    // m_code = String();
    // m_eventParameterName = String();
    // m_sourceURL = String();
    setListenerObject(wrappedFunction, scriptState);
}
Пример #21
0
int MPI_Type_create_darray(int size,
                           int rank,
                           int ndims,
                           int gsize_array[],
                           int distrib_array[],
                           int darg_array[],
                           int psize_array[],
                           int order,
                           MPI_Datatype oldtype,
                           MPI_Datatype *newtype)

{
    ompi_datatype_t *lastType;
    ptrdiff_t orig_extent, *st_offsets = NULL;
    int i, start_loop, end_loop, step;
    int *coords = NULL, rc = OMPI_SUCCESS;

    if (MPI_PARAM_CHECK) {
        int prod_psize = 1;
        OMPI_ERR_INIT_FINALIZE(FUNC_NAME);
        if( (rank < 0) || (size < 0) || (rank >= size) ) {
            return OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_ARG, FUNC_NAME);
        } else if( ndims < 0 ) {
            return OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_COUNT, FUNC_NAME);
        } else if( (NULL == gsize_array) || (NULL == distrib_array) || (NULL == darg_array) || (NULL == psize_array)) {
            return OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_ARG, FUNC_NAME);
        } else if (NULL == newtype) {
            return OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_TYPE, FUNC_NAME);
        } else if( !(DT_FLAG_DATA & oldtype ->flags) ) {
            return OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_TYPE, FUNC_NAME);
        } else if( (MPI_ORDER_C != order) && (MPI_ORDER_FORTRAN != order) ) {
            return OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_ARG, FUNC_NAME);
        }
        for( i = 0; i < ndims; i++ ) {
            if( (MPI_DISTRIBUTE_BLOCK != distrib_array[i]) && 
                (MPI_DISTRIBUTE_CYCLIC != distrib_array[i]) &&
                (MPI_DISTRIBUTE_NONE != distrib_array[i]) ) {
                return OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_ARG, FUNC_NAME);
            } else if( (gsize_array[i] < 1) || (psize_array[i] < 0) ||
                       ((darg_array[i] < 0) && (MPI_DISTRIBUTE_DFLT_DARG != darg_array[i]) ) ) {
                return OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_ARG, FUNC_NAME);
            } else if( (MPI_DISTRIBUTE_DFLT_DARG != darg_array[i]) &&
                       (MPI_DISTRIBUTE_BLOCK == distrib_array[i]) &&
                       ((darg_array[i] * psize_array[i]) < gsize_array[i]) ) {
                return OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_ARG, FUNC_NAME);
            } else if( 1 > psize_array[i] )
                return OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_ARG, FUNC_NAME);
            prod_psize *= psize_array[i];
        }
        if( prod_psize != size )
            return OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_ARG, FUNC_NAME);
    }

    /* speedy corner case */
    if (ndims < 1) {
        /* Don't just return MPI_DATATYPE_NULL as that can't be
           MPI_TYPE_FREE()ed, and that seems bad */
        *newtype = ompi_ddt_create(0);
        ompi_ddt_add(*newtype, &ompi_mpi_datatype_null, 0, 0, 0);
        return MPI_SUCCESS;
    }

    rc = ompi_ddt_type_extent(oldtype, &orig_extent);
    if (MPI_SUCCESS != rc) goto cleanup;

    /* calculate position in grid using row-major ordering */
    {
        int tmp_rank = rank, procs = size;

        coords = (int *) malloc(ndims * sizeof(int));
        for (i = 0 ; i < ndims ; i++) {
            procs = procs / psize_array[i];
            coords[i] = tmp_rank / procs;
            tmp_rank = tmp_rank % procs;
        }
    }

    st_offsets = (ptrdiff_t *) malloc(ndims * sizeof(ptrdiff_t));

    /* duplicate type to here to 1) deal with constness without
       casting and 2) eliminate need to for conditional destroy below.
       Lame, yes.  But cleaner code all around. */
    rc = ompi_ddt_duplicate(oldtype, &lastType);
    if (OMPI_SUCCESS != rc) goto cleanup;

    /* figure out ordering issues */
    if (MPI_ORDER_C == order) {
        start_loop = ndims - 1 ; step = -1; end_loop = -1;
    } else {
        start_loop = 0 ; step = 1; end_loop = ndims;
    }

    /* Build up array */
    for (i = start_loop ; i != end_loop; i += step) {
        int nprocs, rank;

        switch(distrib_array[i]) {
        case MPI_DISTRIBUTE_BLOCK:
            rc = block(gsize_array, i, ndims, psize_array[i], coords[i], 
                       darg_array[i], order, orig_extent, 
                       lastType, newtype, st_offsets+i); 
            break;
        case MPI_DISTRIBUTE_CYCLIC:
            rc = cyclic(gsize_array, i, ndims, psize_array[i], coords[i], 
                        darg_array[i], order, orig_extent, 
                        lastType, newtype, st_offsets+i);
            break;
        case MPI_DISTRIBUTE_NONE:
            /* treat it as a block distribution on 1 process */
            if (order == MPI_ORDER_C) {
                nprocs = psize_array[i]; rank = coords[i];
            } else {
                nprocs = 1; rank = 0;
            }

            rc = block(gsize_array, i, ndims, nprocs, rank,
                       MPI_DISTRIBUTE_DFLT_DARG, order, orig_extent, 
                       lastType, newtype, st_offsets+i); 
            break;
        default:
            rc = MPI_ERR_ARG;
        }
        ompi_ddt_destroy(&lastType);
        /* need to destroy the old type even in error condition, so
           don't check return code from above until after cleanup. */
        if (MPI_SUCCESS != rc) goto cleanup;
        lastType = *newtype;
    }


    /* set displacement and UB correctly.  Use struct instead of
       resized for same reason as subarray */
    { 
        ptrdiff_t displs[3];
        ompi_datatype_t *types[3];
        int tmp_size, blength[3] = { 1, 1, 1};

        displs[1] = st_offsets[start_loop];
        tmp_size = 1;
        for (i = start_loop + step ; i != end_loop ; i += step) {
            tmp_size *= gsize_array[i - step];
            displs[1] += tmp_size * st_offsets[i];
        }

        displs[0] = 0; 
        displs[1] *= orig_extent;
        displs[2] = orig_extent;
        for (i = 0 ; i < ndims ; i++) {
            displs[2] *= gsize_array[i];
        }
        types[0] = MPI_LB; types[1] = lastType; types[2] = MPI_UB;

        rc = ompi_ddt_create_struct(3, blength, displs, types, newtype);
        ompi_ddt_destroy(&lastType);
        /* need to destroy the old type even in error condition, so
           don't check return code from above until after cleanup. */
        if (MPI_SUCCESS != rc) goto cleanup;
    }

    {
        int* a_i[8];

        a_i[0] = &size;
        a_i[1] = &rank;
        a_i[2] = &ndims;
        a_i[3] = gsize_array;
        a_i[4] = distrib_array;
        a_i[5] = darg_array;
        a_i[6] = psize_array;
        a_i[7] = &order;

        ompi_ddt_set_args( *newtype, 4 * ndims + 4, a_i, 0, NULL, 1, &oldtype,
                           MPI_COMBINER_DARRAY );
    }

 cleanup:
    if (NULL != st_offsets) free(st_offsets);
    if (NULL != coords) free(coords);

    OMPI_ERRHANDLER_RETURN(rc, MPI_COMM_WORLD, rc, FUNC_NAME);
}
Пример #22
0
int QTextDocumentPrivate::undoRedo(bool undo)
{
    PMDEBUG("%s, undoState=%d, undoStack size=%d", undo ? "undo:" : "redo:", undoState, undoStack.size());
    if (!undoEnabled || (undo && undoState == 0) || (!undo && undoState == undoStack.size()))
        return -1;

    undoEnabled = false;
    beginEditBlock();
    while (1) {
        if (undo)
            --undoState;
        QTextUndoCommand &c = undoStack[undoState];
        int resetBlockRevision = c.pos;

	switch(c.command) {
        case QTextUndoCommand::Inserted:
            remove(c.pos, c.length, (QTextUndoCommand::Operation)c.operation);
            PMDEBUG("   erase: from %d, length %d", c.pos, c.length);
            c.command = QTextUndoCommand::Removed;
	    break;
        case QTextUndoCommand::Removed:
            PMDEBUG("   insert: format %d (from %d, length %d, strpos=%d)", c.format, c.pos, c.length, c.strPos);
            insert_string(c.pos, c.strPos, c.length, c.format, (QTextUndoCommand::Operation)c.operation);
            c.command = QTextUndoCommand::Inserted;
	    break;
	case QTextUndoCommand::BlockInserted:
	case QTextUndoCommand::BlockAdded:
            remove_block(c.pos, &c.blockFormat, c.command, (QTextUndoCommand::Operation)c.operation);
            PMDEBUG("   blockremove: from %d", c.pos);
	    if (c.command == QTextUndoCommand::BlockInserted)
		c.command = QTextUndoCommand::BlockRemoved;
	    else
		c.command = QTextUndoCommand::BlockDeleted;
	    break;
	case QTextUndoCommand::BlockRemoved:
	case QTextUndoCommand::BlockDeleted:
            PMDEBUG("   blockinsert: charformat %d blockformat %d (pos %d, strpos=%d)", c.format, c.blockFormat, c.pos, c.strPos);
            insert_block(c.pos, c.strPos, c.format, c.blockFormat, (QTextUndoCommand::Operation)c.operation, c.command);
            resetBlockRevision += 1;
	    if (c.command == QTextUndoCommand::BlockRemoved)
		c.command = QTextUndoCommand::BlockInserted;
	    else
		c.command = QTextUndoCommand::BlockAdded;
	    break;
	case QTextUndoCommand::CharFormatChanged: {
            resetBlockRevision = -1; // ## TODO
            PMDEBUG("   charFormat: format %d (from %d, length %d)", c.format, c.pos, c.length);
            FragmentIterator it = find(c.pos);
            Q_ASSERT(!it.atEnd());

            int oldFormat = it.value()->format;
            setCharFormat(c.pos, c.length, formats.charFormat(c.format));
            c.format = oldFormat;
	    break;
	}
	case QTextUndoCommand::BlockFormatChanged: {
            resetBlockRevision = -1; // ## TODO
            PMDEBUG("   blockformat: format %d pos %d", c.format, c.pos);
            QTextBlock it = blocksFind(c.pos);
            Q_ASSERT(it.isValid());

            int oldFormat = block(it)->format;
            block(it)->format = c.format;
            QTextBlockGroup *oldGroup = qobject_cast<QTextBlockGroup *>(objectForFormat(formats.blockFormat(oldFormat)));
            QTextBlockGroup *group = qobject_cast<QTextBlockGroup *>(objectForFormat(formats.blockFormat(c.format)));
            c.format = oldFormat;
            if (group != oldGroup) {
                if (oldGroup)
                    oldGroup->blockRemoved(it);
                if (group)
                    group->blockInserted(it);
            } else if (group) {
                group->blockFormatChanged(it);
            }
            documentChange(it.position(), it.length());
	    break;
	}
	case QTextUndoCommand::GroupFormatChange: {
            resetBlockRevision = -1; // ## TODO
            PMDEBUG("   group format change");
            QTextObject *object = objectForIndex(c.objectIndex);
            int oldFormat = formats.objectFormatIndex(c.objectIndex);
            changeObjectFormat(object, c.format);
            c.format = oldFormat;
	    break;
	}
	case QTextUndoCommand::Custom:
            resetBlockRevision = -1; // ## TODO
            if (undo)
                c.custom->undo();
            else
                c.custom->redo();
	    break;
	default:
	    Q_ASSERT(false);
        }

        if (resetBlockRevision >= 0) {
            int b = blocks.findNode(resetBlockRevision);
            QTextBlockData *B = blocks.fragment(b);
            B->revision = c.revision;
        }

        if (undo) {
            if (undoState == 0 || !undoStack[undoState-1].block)
                break;
        } else {
            ++undoState;
            if (undoState == undoStack.size() || !undoStack[undoState-1].block)
                break;
        }
    }
    undoEnabled = true;
    int editPos = -1;
    if (docChangeFrom >= 0) {
        editPos = qMin(docChangeFrom + docChangeLength, length() - 1);
    }
    endEditBlock();
    emitUndoAvailable(isUndoAvailable());
    emitRedoAvailable(isRedoAvailable());
    return editPos;
}
Пример #23
0
/**
* Compute a path from (x1,y1) to (x2,y2)
* Store waypoint inside path
* limit is the maximum number of explored node
* @return true if a path is found
*/
bool MapCollision::compute_path(FPoint start_pos, FPoint end_pos, std::vector<FPoint> &path, MOVEMENTTYPE movement_type, unsigned int limit) {

	if (is_outside_map(end_pos.x, end_pos.y)) return false;

	if (limit == 0)
		limit = std::max(map_size.x, map_size.y);

	// path must be empty
	if (!path.empty())
		path.clear();

	// convert start & end to MapCollision precision
	Point start = map_to_collision(start_pos);
	Point end = map_to_collision(end_pos);

	// if the target square has an entity, temporarily clear it to compute the path
	bool target_blocks = false;
	int target_blocks_type = colmap[end.x][end.y];
	if (colmap[end.x][end.y] == BLOCKS_ENTITIES || colmap[end.x][end.y] == BLOCKS_ENEMIES) {
		target_blocks = true;
		unblock(end_pos.x, end_pos.y);
	}

	Point current = start;
	AStarNode* node = new AStarNode(start);
	node->setActualCost(0);
	node->setEstimatedCost(static_cast<float>(calcDist(start,end)));
	node->setParent(current);

	AStarContainer open(map_size.x, map_size.y, limit);
	AStarCloseContainer close(map_size.x, map_size.y, limit);

	open.add(node);

	while (!open.isEmpty() && static_cast<unsigned>(close.getSize()) < limit) {
		node = open.get_shortest_f();

		current.x = node->getX();
		current.y = node->getY();
		close.add(node);
		open.remove(node);

		if ( current.x == end.x && current.y == end.y)
			break; //path found !

		//limit evaluated nodes to the size of the map
		std::list<Point> neighbours = node->getNeighbours(map_size.x, map_size.y);

		// for every neighbour of current node
		for (std::list<Point>::iterator it=neighbours.begin(); it != neighbours.end(); ++it)	{
			Point neighbour = *it;

			// do not exceed the node limit when adding nodes
			if (static_cast<unsigned>(open.getSize()) >= limit) {
				break;
			}

			// if neighbour is not free of any collision, skip it
			if (!is_valid_tile(neighbour.x,neighbour.y,movement_type, false))
				continue;
			// if nabour is already in close, skip it
			if(close.exists(neighbour))
				continue;

			// if neighbour isn't inside open, add it as a new Node
			if(!open.exists(neighbour)) {
				AStarNode* newNode = new AStarNode(neighbour.x,neighbour.y);
				newNode->setActualCost(node->getActualCost() + static_cast<float>(calcDist(current,neighbour)));
				newNode->setParent(current);
				newNode->setEstimatedCost(static_cast<float>(calcDist(neighbour,end)));
				open.add(newNode);
			}
			// else, update it's cost if better
			else {
				AStarNode* i = open.get(neighbour.x, neighbour.y);
				if (node->getActualCost() + static_cast<float>(calcDist(current,neighbour)) < i->getActualCost()) {
					Point pos(i->getX(), i->getY());
					Point parent_pos(node->getX(), node->getY());
					open.updateParent(pos, parent_pos, node->getActualCost() + static_cast<float>(calcDist(current,neighbour)));
				}
			}
		}
	}

	if (current.x != end.x || current.y != end.y) {

		//couldnt find the target so map a path to the closest node found
		node = close.get_shortest_h();
		current.x = node->getX();
		current.y = node->getY();

		while (current.x != start.x || current.y != start.y) {
			path.push_back(collision_to_map(current));
			current = close.get(current.x, current.y)->getParent();
		}
	}
	else {
		// store path from end to start
		path.push_back(collision_to_map(end));
		while (current.x != start.x || current.y != start.y) {
			path.push_back(collision_to_map(current));
			current = close.get(current.x, current.y)->getParent();
		}
	}
	// reblock target if needed
	if (target_blocks) block(end_pos.x, end_pos.y, target_blocks_type == BLOCKS_ENEMIES);

	return !path.empty();
}
Пример #24
0
CConfigHelper* CConfigHelper::getInstance(const IPropertyTree *cfg, const char* esp_name, IDeploymentCallback *pCallBack)
{
    CriticalBlock block(m_critSect);

    static CConfigHelper *p_sConfigHelper = NULL;
    StringBuffer xpath1, xpath2;

    if (p_sConfigHelper != NULL)
    {
        return p_sConfigHelper;
    }

    p_sConfigHelper = new CConfigHelper(pCallBack);

    if (cfg != NULL && esp_name != NULL)
    {
        xpath1.clear().appendf("%s/%s/%s[%s='%s']/%s",XML_TAG_SOFTWARE, XML_TAG_ESPPROCESS, XML_TAG_ESPSERVICE, XML_ATTR_NAME, esp_name, XML_TAG_LOCALCONFFILE);
        p_sConfigHelper->m_strConfFile = cfg->queryProp(xpath1.str());

        xpath2.clear().appendf("%s/%s/%s[%s='%s']/%s",XML_TAG_SOFTWARE, XML_TAG_ESPPROCESS, XML_TAG_ESPSERVICE, XML_ATTR_NAME, esp_name, XML_TAG_LOCALENVCONFFILE);
        p_sConfigHelper->m_strEnvConfFile = cfg->queryProp(xpath2.str());

        if (p_sConfigHelper->m_strConfFile.length() > 0 && p_sConfigHelper->m_strEnvConfFile.length() > 0 && checkFileExists(p_sConfigHelper->m_strConfFile.str()) && checkFileExists(p_sConfigHelper->m_strEnvConfFile.str()))
        {
            Owned<IProperties> pParams = createProperties(p_sConfigHelper->m_strConfFile.str());
            Owned<IProperties> pEnvParams = createProperties(p_sConfigHelper->m_strEnvConfFile.str());

            p_sConfigHelper->m_strConfigXMLDir = pEnvParams->queryProp(TAG_PATH);

            if (p_sConfigHelper->m_strConfigXMLDir.length() == 0)
            {
              p_sConfigHelper->m_strConfigXMLDir = INSTALL_DIR;
            }

            p_sConfigHelper->m_strBuildSetFileName = pParams->queryProp(TAG_BUILDSET);

            p_sConfigHelper->m_strBuildSetFilePath.append(p_sConfigHelper->m_strConfigXMLDir).append(STANDARD_CONFIG_CONFIGXML_DIR).append(
                        p_sConfigHelper->m_strBuildSetFileName.length() > 0 ? p_sConfigHelper->m_strBuildSetFileName : STANDARD_CONFIG_BUILDSETFILE);

            try
            {
                p_sConfigHelper->m_pDefBldSet.set(createPTreeFromXMLFile(p_sConfigHelper->m_strBuildSetFilePath.str()));
            }
            catch (IException *e)
            {
                if (p_sConfigHelper->m_pDefBldSet.get() != NULL)
                {
                    p_sConfigHelper->m_pDefBldSet.clear();
                }

                StringBuffer msg;
                e->errorMessage(msg);

                delete e;

                if (p_sConfigHelper->m_cbDeployment.get() != NULL)
                {
                    p_sConfigHelper->m_cbDeployment->printStatus(STATUS_ERROR, NULL, NULL, NULL,
                                                "Failed create PTree from buildset.xml file %s with error %s", p_sConfigHelper->m_strBuildSetFilePath.str(), msg.str());

                    return p_sConfigHelper;
                }
                else
                {
                    throw MakeStringException(-1, "Failed create PTree from buildset.xml file %s with error %s", p_sConfigHelper->m_strBuildSetFilePath.str(), msg.str());
                }
            }

            try
            {
                p_sConfigHelper->appendBuildSetFromPlugins();
            }
            catch (IException *e)
            {
                if (p_sConfigHelper->m_cbDeployment.get() != NULL)
                {
                    StringBuffer msg;
                    e->errorMessage(msg);

                    p_sConfigHelper->m_cbDeployment->printStatus(STATUS_ERROR, NULL, NULL, NULL,
                                                "Failed to add plugin buildset.xml file %s with error %s", p_sConfigHelper->m_strBuildSetFilePath.str(), msg.str());
                }
                // TODO: log message to configmgr log but continue execution

                delete e;
            }

            return p_sConfigHelper;
        }
        else
        {
            delete p_sConfigHelper;
            p_sConfigHelper = NULL;

            throw MakeStringException(-1, "Config file does not define values for %s and %s", xpath1.str(), xpath2.str());
        }
    }

    return p_sConfigHelper;
}
Пример #25
0
/* setup a 64-bit parameter (double/ldouble/longlong)
 * used by bfcode() */
static void
param_64bit(struct symtab *sym, int *argofsp, int dotemps)
{
	int argofs = *argofsp;
	NODE *p, *q;
	int navail;

#if ALLONGLONG == 64
	/* alignment */
	++argofs;
	argofs &= ~1;
	*argofsp = argofs;
#endif

	navail = NARGREGS - argofs;

	if (navail < 2) {
		/* half in and half out of the registers */
		if (features(FEATURE_BIGENDIAN)) {
			cerror("param_64bit");
			p = q = NULL;
		} else {
			q = block(REG, NIL, NIL, INT, 0, 0);
			regno(q) = R0 + argofs;
			if (dotemps) {
				q = block(SCONV, q, NIL,
				    ULONGLONG, 0, 0);
				p = nametree(sym);
				p->n_type = ULONGLONG;
				p->n_df = 0;
				p->n_ap = NULL;
				p = block(LS, p, bcon(32), ULONGLONG, 0, 0);
				q = block(PLUS, p, q, ULONGLONG, 0, 0);
				p = tempnode(0, ULONGLONG, 0, 0);
				sym->soffset = regno(p);
				sym->sflags |= STNODE;
			} else {
				p = nametree(sym);
				regno(p) = sym->soffset;
				p->n_type = INT;
				p->n_df = 0;
				p->n_ap = NULL;
			}
		}
		p = buildtree(ASSIGN, p, q);
		ecomp(p);
		*argofsp = argofs + 2;
		return;
	}

	q = block(REG, NIL, NIL, sym->stype, sym->sdf, sym->sap);
	regno(q) = R0R1 + argofs;
	if (dotemps) {
		p = tempnode(0, sym->stype, sym->sdf, sym->sap);
		sym->soffset = regno(p);
		sym->sflags |= STNODE;
	} else {
		p = nametree(sym);
	}
	p = buildtree(ASSIGN, p, q);
	ecomp(p);
	*argofsp = argofs + 2;
}
Пример #26
0
void fullmoonfever(void)
{
  int ok = 1;
  while(ok)
  {
    if(tokeq("ILLGOL") || tokeq("Illgola2") || tokeq("Illberon") || tokeq("Illgol##"))
    {
      scan();
      block();
    }
    else if(tokeq("GO"))
    {
      scan();
      boolexpr();
      boolexpr();
      g_pop_ax();
      g_pop_dx();
      g_mov_dh_al();
      g_mov_ah(2);
      g_xor_bx_bx();
      g_int(0x10);
    }
    else if(tokeq("PRINT"))
    {
      scan();
      boolexpr();
      g_mov_ah(0x0e);
      g_pop_si();
      g_label(); g_mov_al_SI();
      g_or_al_al();
      g_jz(12);
      g_mov_bx_I(caddr(pencolor));
      g_xor_bh_bh();
      g_int(16);
      g_inc_si();
      g_jmp(-18);
      g_label();
    }
    else if(tokeq("CENTRE"))
    {
      int l = 0;
      scan();
      l = (80-(strlen(token)-1)) >> 1;
      boolexpr();
      boolexpr();
      g_pop_ax();
      g_mov_dx(l);
      g_mov_dh_al();
      g_mov_ah(2);
      g_xor_bx_bx();
      g_int(0x10);
      g_mov_ah(0x0e);
      g_pop_si();
      g_label(); g_mov_al_SI();
      g_or_al_al();
      g_jz(12);
      g_mov_bx_I(caddr(pencolor));
      g_xor_bh_bh();
      g_int(16);
      g_inc_si();
      g_jmp(-18);
      g_label();
    }
    else if(tokeq("PAUSE"))
Пример #27
0
/* called from moveargs() */
static NODE *
movearg_struct(NODE *p, int *regp)
{
	int reg = *regp;
	NODE *l, *q, *t, *r;
	int tmpnr;
	int navail;
	int num;
	int sz;
	int ty;
	int i;

	assert(p->n_op == STARG);

	navail = NARGREGS - (reg - R0);
	navail = navail < 0 ? 0 : navail;
	sz = tsize(p->n_type, p->n_df, p->n_ap) / SZINT;
	num = sz > navail ? navail : sz;

	/* remove STARG node */
	l = p->n_left;
	nfree(p);
	ty = l->n_type;

	/*
	 * put it into a TEMP, rather than tcopy(), since the tree
	 * in p may have side-affects
	 */
	t = tempnode(0, ty, l->n_df, l->n_ap);
	tmpnr = regno(t);
	q = buildtree(ASSIGN, t, l);

	/* copy structure into registers */
	for (i = 0; i < num; i++) {
		t = tempnode(tmpnr, ty, 0, 0);
		t = block(SCONV, t, NIL, PTR+INT, 0, 0);
		t = block(PLUS, t, bcon(4*i), PTR+INT, 0, 0);
		t = buildtree(UMUL, t, NIL);

		r = block(REG, NIL, NIL, INT, 0, 0);
		regno(r) = reg++;
		r = buildtree(ASSIGN, r, t);

		q = block(CM, q, r, INT, 0, 0);
	}

	/* put the rest of the structure on the stack */
	for (i = num; i < sz; i++) {
		t = tempnode(tmpnr, ty, 0, 0);
		t = block(SCONV, t, NIL, PTR+INT, 0, 0);
		t = block(PLUS, t, bcon(4*i), PTR+INT, 0, 0);
		t = buildtree(UMUL, t, NIL);
		r = pusharg(t, &reg);
		q = block(CM, q, r, INT, 0, 0);
	}

	q = reverse(q);

	*regp = reg;
	return q;
}
Пример #28
0
/* Get the computer's move */
void get_computer_move(void)
{
check=0;
block();
if(check==0)
	{
	if (count==1)
	ip=2;
	else if(count==3)
		{
		if(t[1]=='O' || t[3]=='O' || t[5]=='O' || t[8]=='O')
		  ip=9;
		else if(t[4]=='O' || t[6]=='O')
		ip=5;
		else if(t[7]=='O')
		ip=1;
		else if(t[9]=='O')
		ip=3;
		}
	else if(count==5)
		{
		switch(readip)
			{
			case 7: if(t[1]=='O')
				  ip=5;
				else if(t[3]=='O')
				  ip=5;
				else if(t[5]=='O')
				  ip=3;
				else if(t[8]=='O')
				  ip=3;
				else do
					{
					ip=random(10);
					}while(ip==0);
				break;
			case 8: if(t[4]=='O' || t[6]=='O')
				  ip=3;
				else do
					{
					ip=random(10);
					}while(ip==0);
				break;
			case 3: if(t[7]=='O')
				  ip=5;
				else if(t[1]=='O')
				  ip=8;
				else do
					{
					ip=random(10);
					}while(ip==0);
				break;
			case 1: ip=5;
				break;
			case 4: if(t[8]=='O')
					  ip=3;
				       else do
					{
					ip=random(10);
					}while(ip==0);
				break;
			case 5: if(t[8]=='O')
					  ip=3;
				       else do
					{
					ip=random(10);
					}while(ip==0);
				break;
			case 6: if(t[8]=='O')
				  ip=1;
				else do
					{
					ip=random(10);
					}while(ip==0);
				break;
			default:do
				{
				ip=random(10);
				}while(ip==0);
				break;
			}
		}
	else if (count==7)
		{
		do
			{
			ip=random(10);
			}
		while(ip==0);
		}
	else if(count==9)
		{
		for (int i=1;i<=9;i++)
			{
			itoa(i,ic,10);
			if(t[i]==ic[0])
				{
				ip=i;
				break;
				}
			}
		}
	}

itoa(ip,c,10);

for (int i=1; i<=10; i++)       //Dis-allows duplicate entries
     {
	if (c[0]==b[i])
		{
		get_computer_move();
		}
     }
}
Пример #29
0
 /** Begin new block. */
 Struct writeBlock(uint8_t type = InvalidType) {
    Struct block(mBuf, mBuf.size());
    if(type != InvalidType)
       block.push(type);
    return block;
 }
Пример #30
0
int main(int argc, char** argv)
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " <file name>\n";
        return 1;
    }

    // Open a new file and write the EBML Header. This specifies that the file
    // is an EBML file, and is a Tawara document.
    std::fstream stream(argv[1], std::ios::in|std::ios::out|std::ios::trunc);
    tawara::EBMLElement ebml_el;
    ebml_el.write(stream);

    // Open a new segment in the file. This will write some initial meta-data
    // and place some padding at the start of the file for final meta-data to
    // be written after tracks, clusters, etc. have been written.
    tawara::Segment segment;
    segment.write(stream);
    // Set up the segment information so it can be used while writing tracks
    // and clusters.
    // A UID is not required, but is highly recommended.
    boost::uuids::random_generator gen;
    boost::uuids::uuid uuid = gen();
    std::vector<char> uuid_data(uuid.size());
    std::copy(uuid.begin(), uuid.end(), uuid_data.begin());
    segment.info.uid(uuid_data);
    // The filename can be nice to know.
    segment.info.filename(argv[1]);
    // The segment's timecode scale is possibly the most important value in the
    // segment meta-data data. Without it, timely playback of frames is not
    // possible. It has a sensible default (defined in the Tawara specification),
    // but here we set it to ten milliseconds for demonstrative purposes.
    segment.info.timecode_scale(10000000);
    // The segment's date should be set. It is the somewhat-awkward value of
    // the number of seconds since the start of the millenium. Boost::Date_Time
    // to the rescue!
    bpt::ptime basis(boost::gregorian::date(2001, 1, 1));
    bpt::ptime start(bpt::second_clock::local_time());
    bpt::time_duration td = start - basis;
    segment.info.date(td.total_seconds());
    // Let's give the segment an inspirational title.
    segment.info.title("Example segment");
    // It sometimes helps to know what created a Tawara file.
    segment.info.muxing_app("libtawara-0.1");
    segment.info.writing_app("tawara_eg_write");

    // Set up the tracks meta-data and write it to the file.
    tawara::Tracks tracks;
    // Each track is represented in the Tracks information by a TrackEntry.
    // This specifies such things as the track number, the track's UID and the
    // codec used.
    tawara::TrackEntry::Ptr track(new tawara::TrackEntry(1, 1, "string"));
    track->name("Example frames");
    track->codec_name("ASCII string");
    // Adding each level 1 element (only the first occurance, in the case of
    // clusters) to the index makes opening the file later much faster.
    segment.index.insert(std::make_pair(tracks.id(),
                segment.to_segment_offset(stream.tellp())));
    // Now we can write the Tracks element.
    tracks.insert(track);
    tracks.write(stream);

    // The data itself is stored in clusters. Each cluster contains a number of
    // blocks, with each block containing a single frame of data.  Different
    // cluster implementations are available using different optimisations.
    // Here, we use the implementation that stores all its blocks in memory
    // before writing them all to the file at once. As with the segment,
    // clusters must be opened for writing before blocks are added. Once the
    // cluster is complete, it is finalised. How many blocks each cluster
    // contains is relatively flexible: the only limitation is on the range of
    // block timecodes that can be stored. Each timecode is a signed 16-bit
    // integer, and usually blocks have timecodes that are positive, limiting
    // the range to 32767. The unit of this value is the segment's timecode
    // scale. The default timecode scale therefore gives approximately 65
    // seconds of total range, with 32 seconds being used.
    tawara::MemoryCluster cluster;
    // Again, we add the cluster to the index for faster file opening.
    segment.index.insert(std::make_pair(cluster.id(),
                segment.to_segment_offset(stream.tellp())));
    // The cluster's timecode determines the basis for the timecodes of all
    // blocks in that cluster.
    bpt::ptime c_start(bpt::second_clock::local_time());
    bpt::time_duration c_td = c_start - start;
    cluster.timecode(c_td.total_microseconds() / 10000);
    // Open the cluster for writing so we can begin adding blocks.
    cluster.write(stream);
    // Here, a few blocks are added.
    for (int ii(1); ii <= 5; ++ii)
    {
        std::string frame("frame 1");
        frame[6] = ii + '0';
        // When creating a block, the track number must be specified. In our
        // case, all blocks belong to track 1. A timecode must also be given.
        // It is an offset from the cluster's timecode measured in the
        // segment's timecode scale.
        bpt::ptime b_start(bpt::second_clock::local_time());
        bpt::time_duration b_td = b_start - c_start;
        tawara::BlockElement::Ptr block(new tawara::SimpleBlock(1,
                    b_td.total_microseconds() / 10000));
        // Here the frame data itself is added to the block
        tawara::Block::FramePtr frame_ptr(
            new tawara::Block::Frame(frame.begin(), frame.end()));
        block->push_back(frame_ptr);
        // And then the block is added to its cluster.
        cluster.push_back(block);
    }
    // Finally, now that all blocks have been added, the cluster is finalised.
    cluster.finalise(stream);

    // Now we'll add another cluster, this time using the in-file cluster
    // implementation.
    tawara::FileCluster cluster2;
    // This cluster does not need to be added to the index, as it is easily
    // found during reading by skipping past the first cluster.
    // Give the cluster a timecode.
    c_start = bpt::second_clock::local_time();
    c_td = c_start - start;
    cluster2.timecode(c_td.total_microseconds() / 10000);
    // Open the cluster for writing.
    cluster2.write(stream);
    // Add some blocks.
    for (int ii(0); ii < 10; ++ii)
    {
        std::string frame("frame a");
        frame[6] = ii + 'a';
        // The block's timecode
        bpt::ptime b_start(bpt::second_clock::local_time());
        bpt::time_duration b_td = b_start - c_start;
        tawara::BlockElement::Ptr block(new tawara::SimpleBlock(1,
                    b_td.total_microseconds() / 10000));
        // Add the frame data to the block.
        tawara::Block::FramePtr frame_ptr(
            new tawara::Block::Frame(frame.begin(), frame.end()));
        block->push_back(frame_ptr);
        // Add the block to the cluster.
        cluster2.push_back(block);
    }
    // Finally, now that all blocks have been added, the cluster is finalised.
    cluster2.finalise(stream);

    // Now that all the data has been written, the last thing to do is to
    // finalise the segment.
    segment.finalise(stream);
    // And close the file.
    stream.close();

    return 0;
}