示例#1
0
static TLDNode *balance(TLDNode *node) {
	int nodeDiff;
	nodeDiff=checkDiff(node);
	if (nodeDiff>1){
		int checkLeft=checkDiff(node->left);
		if (checkLeft>0){
			node=LL(node);
		}else{
			node=LR(node);
		}
	}else if(nodeDiff<-1){
		int checkRight=checkDiff(node->right);
		if (checkRight>0){
			node=RL(node);
		}else{
			node=RR(node);
		}
	};
	return node;
}
示例#2
0
文件: Events.cpp 项目: adamsikora/kmc
void Events::execute()
{
	evolve();

newChoose:;

	double chooseEvent = _random() * rates.total;

	if (chooseEvent < rates.totalAds) {
		int index = static_cast<int> (floor(chooseEvent / rates.ads));

		adsorption(index, atomType::metal);
	}
	else if (chooseEvent < rates.totalAds + rates.totalDes) {
		chooseEvent -= rates.totalAds;
		double cumulateRates = 0;
		unsigned ei = 0, ej = 0;
      while (cumulateRates + rates.sumsofDes[ei] < chooseEvent) {
         if (ei >= c::nDesTypes) {
            goto newChoose;
         }
         cumulateRates += rates.sumsofDes[ei++];
      }
      ej = static_cast<int> (floor((chooseEvent - cumulateRates) / rates.des[ei]));
      if (ej >= eventLists._desEvents[ei].size()) {
         goto newChoose;
      }/*

		if (ei % c::nNeighCount == 0)
			_nFreeDes++;

      _nDesorbNeigh[ei % c::nNeighCount]++;*/

		desorption(eventLists._desEvents[ei][ej]);
	}
	else {
		chooseEvent -= rates.totalAds + rates.totalDes;
		double cumulateRates = 0;
		unsigned ei = 0, ej = 0;
      while (cumulateRates + rates.sumsofDiff[ei] < chooseEvent) {
         if (ei >= c::nDiffTypes) {
            goto newChoose;
         }
         cumulateRates += rates.sumsofDiff[ei++];
      }
		ej = static_cast<int> (floor((chooseEvent - cumulateRates) / rates.diff[ei]));
      if (ej >= eventLists._diffEvents[ei].size()) {
         goto newChoose;
      }
		checkDiff(ei, eventLists._diffEvents[ei][ej]);
		diffusion(eventLists._diffEvents[ei][ej]);
   }
   _nEvents++;
}
PyObject* check(PyObject *self, PyObject *args)
{
    int user_fd, right_fd, rst;
    
    if (!PyArg_ParseTuple(args, "ii", &right_fd, &user_fd))
        RAISE0("run parseTuple failure");
    
    if(checkDiff(right_fd, user_fd, &rst) == -1)
        return NULL;
    
    return Py_BuildValue("i", rst);
}
示例#4
0
    void check(const FunctionCallbackInfo<Value>& args) {
        Isolate* isolate = args.GetIsolate();

        if (args.Length() < 2) {
            isolate->ThrowException(Exception::TypeError(
                    String::NewFromUtf8(isolate, "Wrong arugments")
            ));
            return;
        }

        int sampleIn;
        int userIn;
        int result;

        sampleIn =  args[0]->Int32Value();
        userIn = args[1]->Int32Value();

        checkDiff(sampleIn, userIn, &result);
        args.GetReturnValue().Set(Number::New(isolate, result));
    }
示例#5
0
SourceView::SourceView(QWidget *parent,QFont & efont,bool line, QList<QColor> edcolors, QList<QColor> hicolors ) : QWidget(parent)
{
  
splitter=new MiniSplitter(this);
splitter->setOrientation(Qt::Vertical);

QFrame *framebis=new QFrame(splitter);
framebis->setLineWidth(0);
framebis->setFrameShape(QFrame::NoFrame);
framebis->setFrameShadow(QFrame::Plain);
framebis->setFrameStyle(QFrame::NoFrame);


QVBoxLayout* mainlay = new QVBoxLayout(framebis );
mainlay->setSpacing(0);
mainlay->setMargin(0);

centralToolBar=new QToolBar("ToolBar",framebis);
centralToolBar->setFloatable(false);
centralToolBar->setOrientation(Qt::Horizontal);
centralToolBar->setMovable(false);
centralToolBar->setIconSize(QSize(16,16 ));
centralToolBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
mainlay->addWidget(centralToolBar);
QAction *Act = new QAction(getIcon(":/images/fileopen16.png"), tr("Open"), this);
connect(Act, SIGNAL(triggered()), this, SLOT(fileOpen()));
centralToolBar->addAction(Act);
centralToolBar->addSeparator();
titleLabel=new QLabel("(read only)",centralToolBar);
centralToolBar->addWidget(titleLabel);
centralToolBar->addSeparator();
Act = new QAction(getIcon(":/images/diff.png"), tr("Check differences"), this);
connect(Act, SIGNAL(triggered()), this, SLOT(checkDiff()));
centralToolBar->addAction(Act);


QFrame *frame=new QFrame(framebis);
frame->setLineWidth(0);
frame->setFrameShape(QFrame::NoFrame);
frame->setFrameShadow(QFrame::Plain);
frame->setFrameStyle(QFrame::NoFrame);
mainlay->addWidget(frame);

lastdocument="";
editor=new LightLatexEditor(frame,efont,edcolors,hicolors,"");
connect(editor, SIGNAL(requestFind()), this, SLOT(showFind()));
connect(editor, SIGNAL(requestGotoLine()), this, SLOT(showGoto()));
m_lineNumberWidget = new LightLineNumberWidget( editor, frame);
m_lineNumberWidget->setFont(efont);
QFontMetrics fm( efont );
m_lineNumberWidget->setFixedWidth( fm.width( "00000" ) + 22 );
QHBoxLayout* lay = new QHBoxLayout( frame );
lay->setSpacing(0);
lay->setMargin(0);
lay->addWidget( m_lineNumberWidget );
lay->addWidget( editor );
setFocusProxy( editor );
setLineNumberWidgetVisible(line);

Stack=new QStackedWidget(this);
Stack->setLineWidth(0);
Stack->setFrameShape(QFrame::NoFrame);
Stack->setFrameShadow(QFrame::Plain);

findwidget=new LightFindWidget(Stack);
Stack->addWidget(findwidget);
findwidget->SetEditor(editor);
connect(findwidget, SIGNAL( requestHide() ), Stack, SLOT( hide() ) );
connect(findwidget, SIGNAL( requestExtension() ), this, SLOT( showFind() ) );

gotolinewidget=new LightGotoLineWidget(Stack);
Stack->addWidget(gotolinewidget);
gotolinewidget->SetEditor(editor);
connect(gotolinewidget, SIGNAL( requestHide() ), Stack, SLOT( hide() ) );

Stack->hide();

splitter->addWidget(framebis);
splitter->addWidget(Stack);

QVBoxLayout *mainlayout= new QVBoxLayout(this);
mainlayout->setSpacing(0);
mainlayout->setMargin(0);
mainlayout->addWidget(splitter);
}
示例#6
0
/* The processing loop. Kinda superstep style, everyone copies,
	everyone averages and then everyone checks if they're done.
	Will quit when every thread says it has finished.
*/
void* threadLoop( void* inData)
{
	LoopData* theData = (LoopData*) inData;

	int i, diff = 0;

	// Little bit of indirection to make access easier/simpler
	float** currArray		= theData->inArray;
	float** nextArray		= theData->outArray;
	int   	arrayX			= theData->arrayX;
	int   	arrayY			= theData->arrayY;
	float 	precision 		= theData->precision;
	int* 	finishedThreads	= theData->finishedThreads;

	for( i = 0; i < arrayX; i++)
	{
		memcpy(nextArray[i], theData->inArray[i], arrayY * sizeof(float));
	}

	while( 1 )
	{
		//copy the next array into the working copy.
		for( i = 1; i < arrayX - 1; i++)
		{
			memcpy(currArray[i], nextArray[i], arrayY * sizeof(float));
		}

		//Wait until everyones done that
		if(theData->barrier != NULL)
		{
			pthread_barrier_wait(theData->barrier);
		}

		averageFour(currArray, nextArray, arrayX, arrayY);

		diff = checkDiff(currArray, nextArray, arrayX, arrayY, precision);

		if (diff != 0)
		{

			if(theData->finLock != NULL)
			{
				pthread_mutex_lock(theData->finLock);
			}

			(*finishedThreads)++;

			if(theData->finLock != NULL)
			{
				pthread_mutex_unlock(theData->finLock);
			}
		}

		// Wait for everyone again
		if(theData->barrier != NULL)
		{
			pthread_barrier_wait(theData->barrier);
		}

		// If everyone is done we can go
		if ((*finishedThreads) == theData->numThreads)
		{
			break;
		}
		else //otherwise we have to try again
		{
			(*finishedThreads) = 0;
			// Didn't lock as we're setting to a constant and the only other
			// modification of the variable is behind a barrier in the loop.
		}

	}

	return 0;
}
示例#7
0
int main(int argc, char **argv)
{
	// Initial values (should get from cmd line)
	int arraySize	= 10;
	float precision	= 10;
	int numThreads 	= 2;
	__VERBOSE 		= 0;
	int arrSeed		= time(0);
	int testRight	= 0;

	// Read options
	// -s is the size, -p is the precision and -t is number of threads.
	// -v turns on some debug spew
	int c;
	opterr = 0;
	while ((c = getopt (argc, argv, "s:p:t:vr:c")) != -1)
	{
		switch (c)
		{
			case 'p':
            	if (sscanf(optarg, "%f", &precision) != 1)
				{
					fprintf (stderr,
					"Option -%c requires a float argument.\n",
					 optopt);
					printUsage();
				}
            	break;
			case 'r':
				if (sscanf(optarg, "%i", &arrSeed) != 1)
				{
					fprintf (stderr,
					"Option -%c requires an integer argument.\n",
					 optopt);
					printUsage();
				}
				break;
			case 's':
				if (sscanf(optarg, "%i", &arraySize) != 1)
				{
					fprintf (stderr,
					"Option -%c requires an integer argument.\n",
					 optopt);
					printUsage();
				}
            	break;
           	case 't':
             	if (sscanf(optarg, "%i", &numThreads) != 1)
				{
					fprintf (stderr,
					"Option -%c requires an integer argument.\n",
					 optopt);
					printUsage();
				}
            	break;
			case 'v':
				__VERBOSE = 1;
				break;
		case 'c':
			testRight = 1;
			break;
          	default:
          		printUsage();
           }
	}

#ifdef PTHREAD_THREADS_MAX // Linux don't got this
	if (numThreads > PTHREAD_THREADS_MAX)
	{
		numThreads = PTHREAD_THREADS_MAX;
	}
#endif

	if (numThreads && (arraySize / numThreads) < 2)
	{
		numThreads = arraySize / 2;
	}

	// Start timer
	struct timeval start_tv, end_tv;
	gettimeofday(&start_tv,NULL);

	printf("Starting to relax %d square array to precision %f.",
			arraySize, precision);

	printf("Using %d thread%s (other than main).\n",
			numThreads, numThreads == 1 ? "" : "s");

	printf(". Seed: %d.\n", arrSeed);

	// Initializing and mallocing the arrays
	float** currArray = make2DFloatArray(arraySize, arraySize);
	float** nextArray = make2DFloatArray(arraySize, arraySize);
	initArray(currArray, arraySize, arrSeed);

	// Do the work
	relaxationThreaded(currArray, nextArray, arraySize, precision, numThreads);

	// Stop timer here.
	gettimeofday(&end_tv,NULL);

	int correct = 0;

	if(testRight)
	{
		// Create 2 more arrays, we'll do it again serially
		float** currArray2 = make2DFloatArray(arraySize, arraySize);
		float** nextArray2 = make2DFloatArray(arraySize, arraySize);
		initArray(currArray2, arraySize, arrSeed);

		if(__VERBOSE)
		{
			printf("Original:\n");
			printSquareArray(currArray, arraySize);
		}

		relaxationThreaded(currArray2, nextArray2, arraySize, precision, 0);

		correct = checkDiff(nextArray, nextArray2, arraySize, arraySize, precision);

		if(__VERBOSE)
		{
			printf("\nThreaded:\n");
			printSquareArray(nextArray, arraySize);

			printf("\nSerial:\n");
			printSquareArray(nextArray2, arraySize);
		}
		// Cleanup
		free2DFloatArray(currArray2, arraySize);
		free2DFloatArray(nextArray2, arraySize);
	}

	// Cleanup
	free2DFloatArray(currArray, arraySize);
	free2DFloatArray(nextArray, arraySize);

	long long durr_us = (end_tv.tv_sec * (long long)1000000 + end_tv.tv_usec) -
 					(start_tv.tv_sec * (long long)1000000 + start_tv.tv_usec);

	printf("Relaxed %d square matrix in %llu microsceonds\n",
			arraySize, durr_us);

	if(testRight)
	{
		printf("Threaded relaxation result %s the serial result.\n",
 			correct ? "matched" : "didnt match");
	}

	// Windows command to stop console applications closing immediately.
	system("pause");

	return 0;
}
示例#8
0
void RayTracer::tracePixelAdapt(int i, int j)
{
	vec3f col;

	if (!scene)
		return;

	double x = double(i) / double(buffer_width);
	double y = double(j) / double(buffer_height);

	double pixWidth = 1.0 / double (buffer_width);
	double pixHeight = 1.0 / double (buffer_height);

	double xMin = x - pixWidth/2.0;
	//In case negative values
	if (xMin < RAY_EPSILON)
	{
		xMin = RAY_EPSILON;
	}
	double xMax = x + pixWidth / 2.0;
	double yMin = y - pixHeight / 2.0;
	if (yMin < RAY_EPSILON)
	{
		yMin = RAY_EPSILON;
	}
	double yMax = y + pixHeight / 2.0;

	double xVals[2] = { xMin, xMax };
	double yVals[2] = { yMin, yMax };


	unsigned char corners[2][2][3];
	for (int w = 0; w < 2; w++)
	{
		for (int h = 0; h < 2; h++)
		{
			int xPos = i + w;
			int yPos = j + h;
			if (bufferFilled[yPos*(buffer_width + 1) + xPos])
			{
				unsigned char* pixel = cornerBuffer + (yPos * (buffer_width + 1) + xPos) * 3;
				corners[w][h][0] = pixel[0];
				corners[w][h][1] = pixel[1];
				corners[w][h][2] = pixel[2];

			}
			else
			{
				col = trace(scene, xVals[w], yVals[h]);
				unsigned char *pixel = cornerBuffer + (xPos + yPos * buffer_width+1) * 3;

				pixel[0] = (int)(255.0 * col[0]);
				pixel[1] = (int)(255.0 * col[1]);
				pixel[2] = (int)(255.0 * col[2]);

				corners[w][h][0] = pixel[0];
				corners[w][h][1] = pixel[1];
				corners[w][h][2] = pixel[2];
				
				bufferFilled[yPos*(buffer_width + 1) + xPos] = true;
			}			
		}
	}
	
	unsigned char avg[3];
	unsigned char *pixel = buffer + (i + j * buffer_width) * 3;
	if (checkDiff(corners, 2, avg))
	{
		pixel[0] = avg[0];
		pixel[1] = avg[1];
		pixel[2] = avg[2];
	}
	else
	{
		vec3f subCol[4];
		vec3f colSum = vec3f(0,0,0);
		double subx[4];
		double suby[4];

		double halfWidth = pixWidth / 2.0;
		double halfHeight = pixHeight / 2.0;

		subx[0] = xMin;
		suby[0] = yMin;
		subx[1] = xMin + halfWidth;
		suby[1] = yMin;
		subx[2] = xMin;
		suby[2] = yMin + halfHeight;
		subx[3] = xMin + halfWidth;
		suby[3] = yMin + halfHeight;

		for (int i = 0; i < 4; i++)
		{
			colSum += qSubPix(subx[i], suby[i], halfWidth, halfHeight, 1);
		}
		colSum /= 4.0;
		
		pixel[0] = (int)(255.0 * colSum[0]);
		pixel[1] = (int)(255.0 * colSum[1]);
		pixel[2] = (int)(255.0 * colSum[2]);
	}

	
}