Example #1
0
void Database::execute(const String &request)
{
	Statement statement = prepare(request);
	statement.step();
	statement.finalize();
}
    long long DeleteExecutor::execute(Database* db) {
        uassertStatusOK(prepare());
        uassert(17417,
                mongoutils::str::stream() <<
                "DeleteExecutor::prepare() failed to parse query " << _request->getQuery(),
                _isQueryParsed);

        const NamespaceString& ns(_request->getNamespaceString());
        if (!_request->isGod()) {
            if (ns.isSystem()) {
                uassert(12050,
                        "cannot delete from system namespace",
                        legalClientSystemNS(ns.ns(), true));
            }
            if (ns.ns().find('$') != string::npos) {
                log() << "cannot delete from collection with reserved $ in name: " << ns << endl;
                uasserted(10100, "cannot delete from collection with reserved $ in name");
            }
        }

        Collection* collection = db->getCollection(_request->getOpCtx(), ns.ns());
        if (NULL == collection) {
            return 0;
        }

        uassert(10101,
                str::stream() << "cannot remove from a capped collection: " << ns.ns(),
                !collection->isCapped());

        uassert(ErrorCodes::NotMaster,
                str::stream() << "Not primary while removing from " << ns.ns(),
                !_request->shouldCallLogOp() ||
                repl::getGlobalReplicationCoordinator()->canAcceptWritesForDatabase(ns.db()));

        PlanExecutor* rawExec;
        if (_canonicalQuery.get()) {
            // This is the non-idhack branch.
            uassertStatusOK(getExecutorDelete(_request->getOpCtx(), collection,
                                              _canonicalQuery.release(), _request->isMulti(),
                                              _request->shouldCallLogOp(), &rawExec));
        }
        else {
            // This is the idhack branch.
            uassertStatusOK(getExecutorDelete(_request->getOpCtx(), collection, ns.ns(),
                                              _request->getQuery(), _request->isMulti(),
                                              _request->shouldCallLogOp(), &rawExec));
        }
        scoped_ptr<PlanExecutor> exec(rawExec);

        // Concurrently mutating state (by us) so we need to register 'exec'.
        const ScopedExecutorRegistration safety(exec.get());

        uassertStatusOK(exec->executePlan());

        // Extract the number of documents deleted from the DeleteStage stats.
        invariant(exec->getRootStage()->stageType() == STAGE_DELETE);
        DeleteStage* deleteStage = static_cast<DeleteStage*>(exec->getRootStage());
        const DeleteStats* deleteStats =
            static_cast<const DeleteStats*>(deleteStage->getSpecificStats());
        return deleteStats->docsDeleted;
    }
int dtObstacleAvoidanceQuery::sampleVelocityAdaptive(const float* pos, const float rad, const float vmax,
													 const float* vel, const float* dvel, float* nvel,
													 const dtObstacleAvoidanceParams* params,
													 dtObstacleAvoidanceDebugData* debug)
{
	prepare(pos, dvel);
	
	memcpy(&m_params, params, sizeof(dtObstacleAvoidanceParams));
	m_invHorizTime = 1.0f / m_params.horizTime;
	m_vmax = vmax;
	m_invVmax = 1.0f / vmax;
	
	dtVset(nvel, 0,0,0);
	
	if (debug)
		debug->reset();

	// Build sampling pattern aligned to desired velocity.
	float pat[(DT_MAX_PATTERN_DIVS*DT_MAX_PATTERN_RINGS+1)*2];
	int npat = 0;

	const int ndivs = (int)m_params.adaptiveDivs;
	const int nrings= (int)m_params.adaptiveRings;
	const int depth = (int)m_params.adaptiveDepth;
	
	const int nd = dtClamp(ndivs, 1, DT_MAX_PATTERN_DIVS);
	const int nr = dtClamp(nrings, 1, DT_MAX_PATTERN_RINGS);
	const float da = (1.0f/nd) * DT_PI*2;
	const float dang = atan2f(dvel[2], dvel[0]);
	
	// Always add sample at zero
	pat[npat*2+0] = 0;
	pat[npat*2+1] = 0;
	npat++;
	
	for (int j = 0; j < nr; ++j)
	{
		const float rad = (float)(nr-j)/(float)nr;
		float a = dang + (j&1)*0.5f*da;
		for (int i = 0; i < nd; ++i)
		{
			pat[npat*2+0] = cosf(a)*rad;
			pat[npat*2+1] = sinf(a)*rad;
			npat++;
			a += da;
		}
	}

	// Start sampling.
	float cr = vmax * (1.0f - m_params.velBias);
	float res[3];
	dtVset(res, dvel[0] * m_params.velBias, 0, dvel[2] * m_params.velBias);
	int ns = 0;

	for (int k = 0; k < depth; ++k)
	{
		float minPenalty = FLT_MAX;
		float bvel[3];
		dtVset(bvel, 0,0,0);
		
		for (int i = 0; i < npat; ++i)
		{
			float vcand[3];
			vcand[0] = res[0] + pat[i*2+0]*cr;
			vcand[1] = 0;
			vcand[2] = res[2] + pat[i*2+1]*cr;
			
			if (dtSqr(vcand[0])+dtSqr(vcand[2]) > dtSqr(vmax+0.001f)) continue;
			
			const float penalty = processSample(vcand,cr/10, pos,rad,vel,dvel, debug);
			ns++;
			if (penalty < minPenalty)
			{
				minPenalty = penalty;
				dtVcopy(bvel, vcand);
			}
		}

		dtVcopy(res, bvel);

		cr *= 0.5f;
	}	
	
	dtVcopy(nvel, res);
	
	return ns;
}
Example #4
0
Regex::Regex( const JHSTD::string &regex ) : mState( Regex::STATE_INIT )
{
	prepare( regex );
}
Example #5
0
int main(int argc,char *argv[])
	{   
   pid_t child;
	char **arg_vec=NULL;
	float duration;
	int argno = 1;
	int verbose = 0;
	if (argc >= 3)
		{
		if (strcmp(argv[argno],"-v") == 0 && argc >= 4)
			{
			if (argc >= 4)
				{
				verbose = 1;
				argno++;
				}
			else
				{
				usage(argv[0]);
				}
			}
		sscanf(argv[argno++],"%f",&duration);
		if (sscanf(argv[argno],"%d",(int *)&child) != 1)
			{
			child = 0;
			}
		if (child == 0)
			{
			int i,len;
#if NEVER
			char *p;
#endif
			/* skip two: the prog name, and the duration.  And then we need
			 * an extra one for the new prog name: 1+1-1 is 1.
			 */
			len = argc - 1;
			arg_vec = malloc(sizeof(char *)*len);
			if (arg_vec == NULL)
				{
				fprintf(stderr,"malloc failed\n");
				exit(1);
				}
			for (i=0; i<len-1; i++)
				{
				arg_vec[i] = argv[i+argno];
				}
			arg_vec[len-1] = NULL;
			if (verbose)
				{
				fprintf(stderr,"Attempting to monitor new prog %s\n",arg_vec[0]);
				}
#if NEVER
			for (p=&(arg_vec[0]); p != NULL; p++)
				{
				fprintf(stderr,"arg_vec[%d] is %s\n", p - &(arg_vec[0]), p);
				}
#endif
			for (i=0; i < len; i++)
				{
				if (arg_vec[i] == NULL)
					{
					if (verbose)
						{
						fprintf(stderr,"arg_vec[%d] is %s\n", i, "NULL");
						}
					}
				else
					{
					if (verbose)
						{
						fprintf(stderr,"arg_vec[%d] is %s\n", i, arg_vec[i]);
						}
					}
				}
			}
		else
			{
			if (verbose)
				{
				fprintf(stderr,"Attempting to monitor preexisting pid %d\n",
					(int)child);
				}
			}
		}
	else
		{
		usage(argv[0]);
		}
	/* for use by caught_signal */
	global.child = child;
	global.argv0 = argv[0];
	signal(SIGTERM,caught_signal);
	signal(SIGINT,caught_signal);
	if (arg_vec == NULL)
		{
		monitor(child,duration,0,verbose);
		}
	else
		{
		child = fork();
		if (child == 0)
			{
			prepare();
			if (verbose)
				{
				fprintf(stderr,"Exec'ing %s in 2 seconds\n",arg_vec[0]);
				}
			/* ugly race window */
			sleep(2);
			execvp(arg_vec[0], &(arg_vec[0]));
			perror("execl failed");
			exit(1);
			}
		else
			{
			monitor(child,duration,1,verbose);
			}
		}
   return 0;
   }
Example #6
0
	statement session::operator<<(char const *s)
	{
		return prepare(s);
	}
Example #7
0
void Transmitter::answer()
{
	prepare();
	sendAnswerPacket();
}
Example #8
0
StringTokenizer::StringTokenizer(std::string tosplit, std::string token, bool splitAtAllChars)
        : myTosplit(tosplit), myPos(0) {
    prepare(tosplit, token, splitAtAllChars);
}
Example #9
0
//=========================================
// Main
//-----------------------------------------
int main(int argc,char *argv[]) {
	char* args[argc];
	int fd         = 0;
	int timeout    = 8;
	int status     = 0;
	char* logfile  = NULL;
	char* logPart1 = NULL;
	char* logPart2 = NULL;
	FILE* data;
	int   i,n,count;

	//=========================================
	// Prepare for i18n
	//-----------------------------------------
	setlocale (LC_ALL, "");
	bindtextdomain ("sax", "/usr/share/locale");
	textdomain ("sax");
	bind_textdomain_codeset ("sax","UTF-8");

	//=========================================
	// save first parameter as logfile name
	//-----------------------------------------
	if (argc > 1) {
		logfile = (char*)malloc(sizeof(char)*128);
		strcpy(logfile,argv[1]);
		logPart1 = strtok (logfile,":");
		if (logPart1) {
			logPart2 = strtok (NULL,":");
			logfile  = logPart1;
			logtimer = logPart2;
		}
	}

	//=========================================
	// save the rest of the parameters for the
	// execv call to the X-Server
	//-----------------------------------------
	displayname = (char*)malloc(DISPSIZE);
	strcpy(displayname,":0");

	args[0]     = (char*)malloc(strlen(argv[0])+1);
	strcpy(args[0],argv[0]);
	count = argc;
	n = 1;
	for (i=2;i<argc;i++) {
	if (strncmp(argv[i],"-blank",6) == 0) {
		blank = argv[i];
		count--;
	} else {
		args[n] = (char*)malloc(strlen(argv[i])+1);
		strcpy(args[n],argv[i]);
		n++;
	}
	if (strstr(argv[i],":") != NULL) {
		strcpy(displayname,argv[i]); 
	}
	}
	if (count > 1) {
		args[count-1] = (char*)malloc(sizeof(char)*4);
		strcpy(args[count-1],"-ac"); count++;
		args[count-1] = NULL;
	} else {
		args[count] = (char*)malloc(sizeof(char*)*4);
		strcpy(args[count],"-ac"); count++;
		args[count] = NULL;
	}

	//=========================================
	// setup signal handler
	//-----------------------------------------
	signal (SIGHUP  , trapper);
	signal (SIGINT  , trapper);
	signal (SIGTERM , trapper);
	signal (SIGPIPE , trapper);
	signal (SIGCHLD , child  );

	if ((fd = open(PATH_DEV_NULL, O_RDWR, 0)) != -1) {
		dup2  ( fd, STDERR_FILENO );
		close ( fd );
	}

	cpid = fork();
	switch (cpid) {
	case -1:
		// ...
		// can not fork
		// ---
		perror("fork"); exit(1);
	break;
	case 0:
		// ...
		// child process...
		// ---
		if (logfile != NULL) {
			data = freopen (logfile,"w",stderr );
			setvbuf ( data,(char*)NULL,_IONBF,0 );
		}
		execv (XFree86,args);
	break;
	default:
		// ...
		// parent process
		// ---
		break;
	}
	while ( timeout > 0  ) {
	sleep ( timeout -= 2 );
	if ( waitpid ( cpid, &status, WNOHANG | WUNTRACED) == cpid ) {
		break;
	} else {
		dpy = XOpenDisplay (displayname);
		if (dpy != NULL) {
			break;
		}
	}
	}
	if (dpy == NULL) {
		exit(1);
	}
	prepare ();
	//=====================================
	// start idle timer logtimer is set
	//-------------------------------------
	if (logtimer) {
		char pidToKill [20] = "";
		sprintf (pidToKill,"%d",looppid);
		if (blank) {
			sprintf (pidToKill,"%d",cpid);
		}
		timerpid = fork();
		switch (timerpid) {
		case -1:
			perror("fork"); exit(1);
		break;
		case 0:
			execl (XIDLE,
				"xapi","-x","-p",pidToKill,"-display",displayname,NULL
			);
		break;
		default:
		waitpid (
			timerpid, NULL, WNOHANG | WUNTRACED
		);
		}
	}
	if (! blank) {
	if (! kill (looppid,0)) {
		printf ("%d\n",cpid);
	} else {
		printf ("%d\n",looppid);
	}
	} else {
		printf ("%d\n",cpid);
	}
	exit (0);
}
Example #10
0
QString DialogFilter::getWhere()
{
    QString result = prepare(fieldsCollection.at(cbField->itemData(cbField->currentIndex()).toInt()),cbExpression->itemData(cbExpression->currentIndex()).toString(),edExpression->text());
    if (result == "") result =  "1 = 2";
    return result;
}
Example #11
0
/**
 * Copies selected files into sandbox. Existing files in sandbox are not overwriten.
 *
 * @c QDir::NoDotAndDotDot is always added into @a filters.
 */
bool Sandbox::addWorldFiles(const QString &directory, QDir::Filters filters,
    const QStringList &filterNames, bool recurse){
  Q_ASSERT(!isActive());
  Q_ASSERT(!directory.isEmpty());

  if (!prepare()){
    return false;
  }

  const QString sandboxedDirectory = m_workingSandboxDir.filePath(
      QDir::root().relativeFilePath(
        QFileInfo(directory).absoluteFilePath()));

  if (!QFileInfo(directory).exists()){
    // Accept missing world directory - allow to create directories inside sandbox
    qDebug("%s: Directory does not exist - an empty one will be created instead of copied: '%s'",
        Q_FUNC_INFO, qPrintable(directory));
  } else if (!QFileInfo(directory).isDir()){
    qWarning("%s: Is not a directory: '%s'", Q_FUNC_INFO, qPrintable(directory));
    return false;
  }

  if (!QFileInfo(sandboxedDirectory).exists()){
    if (!QDir().mkpath(sandboxedDirectory)){
      qWarning("%s: Failed to create sandbox directory '%s'", Q_FUNC_INFO,
          qPrintable(sandboxedDirectory));
      return false;
    }
  } else if (!QFileInfo(sandboxedDirectory).isDir()){
    qWarning("%s: Failed to create sandbox directory '%s': Is not a directory", Q_FUNC_INFO,
        qPrintable(sandboxedDirectory));
    return false;
  }

  if (filters == QDir::NoFilter){
    filters = QDir::AllEntries;
  }

  filters |= QDir::NoDotAndDotDot;

  foreach (const QFileInfo &worldEntryInfo, QDir(directory).entryInfoList(filterNames, filters)){

    const QFileInfo sandboxEntryInfo(QDir(sandboxedDirectory).filePath(worldEntryInfo.fileName()));

    if (worldEntryInfo.isDir()){
      if (!sandboxEntryInfo.exists()){
        if (!QDir(sandboxedDirectory).mkdir(worldEntryInfo.fileName())){
          qWarning("%s: Failed to create overlay directory '%s/%s'", Q_FUNC_INFO,
              qPrintable(sandboxedDirectory), qPrintable(worldEntryInfo.fileName()));
          return false;
        }
      } else if (!sandboxEntryInfo.isDir()){
          qWarning("%s: Failed to create sandboxed copy '%s': Is not a directory", Q_FUNC_INFO,
              qPrintable(sandboxEntryInfo.filePath()));
          return false;
      }

      if (recurse){
        if (!addWorldFiles(worldEntryInfo.absoluteFilePath(), filters, filterNames, true)){
          return false;
        }
      }
    } else{
      if (!sandboxEntryInfo.exists()){
        if (!QFile(worldEntryInfo.filePath()).copy(sandboxEntryInfo.filePath())){
          qWarning("%s: Failed to copy file into sandbox '%s'", Q_FUNC_INFO,
              qPrintable(worldEntryInfo.filePath()));
          return false;
        }
      } else if (sandboxEntryInfo.isDir()){
          qWarning("%s: Failed to create sandboxed copy '%s': Is a directory", Q_FUNC_INFO,
              qPrintable(sandboxEntryInfo.filePath()));
          return false;
      }
    }
  }

  return true;
}
int dtObstacleAvoidanceQuery::sampleVelocityAdaptive(const float* pos, const float rad, const float vmax,
													 const float* vel, const float* dvel, float* nvel,
													 const dtObstacleAvoidanceParams* params,
													 dtObstacleAvoidanceDebugData* debug)
{
	prepare(pos, dvel);
	
	memcpy(&m_params, params, sizeof(dtObstacleAvoidanceParams));
	m_invHorizTime = 1.0f / m_params.horizTime;
	m_vmax = vmax;
	m_invVmax = vmax > 0 ? 1.0f / vmax : FLT_MAX;
	
	dtVset(nvel, 0,0,0);
	
	if (debug)
		debug->reset();

	// Build sampling pattern aligned to desired velocity.
	float pat[(DT_MAX_PATTERN_DIVS*DT_MAX_PATTERN_RINGS+1)*2];
	int npat = 0;

	const int ndivs = (int)m_params.adaptiveDivs;
	const int nrings= (int)m_params.adaptiveRings;
	const int depth = (int)m_params.adaptiveDepth;
	
	const int nd = dtClamp(ndivs, 1, DT_MAX_PATTERN_DIVS);
	const int nr = dtClamp(nrings, 1, DT_MAX_PATTERN_RINGS);
	const int nd2 = nd / 2;
	const float da = (1.0f/nd) * DT_PI*2;
	const float ca = cosf(da);
	const float sa = sinf(da);

	// desired direction
	float ddir[6];
	dtVcopy(ddir, dvel);
	dtNormalize2D(ddir);
	dtRorate2D (ddir+3, ddir, da*0.5f); // rotated by da/2

	// Always add sample at zero
	pat[npat*2+0] = 0;
	pat[npat*2+1] = 0;
	npat++;
	
	for (int j = 0; j < nr; ++j)
	{
		const float r = (float)(nr-j)/(float)nr;
		pat[npat*2+0] = ddir[(j%1)*3] * r;
		pat[npat*2+1] = ddir[(j%1)*3+2] * r;
		float* last1 = pat + npat*2;
		float* last2 = last1;
		npat++;

		for (int i = 1; i < nd-1; i+=2)
		{
			// get next point on the "right" (rotate CW)
			pat[npat*2+0] = last1[0]*ca + last1[1]*sa;
			pat[npat*2+1] = -last1[0]*sa + last1[1]*ca;
			// get next point on the "left" (rotate CCW)
			pat[npat*2+2] = last2[0]*ca - last2[1]*sa;
			pat[npat*2+3] = last2[0]*sa + last2[1]*ca;

			last1 = pat + npat*2;
			last2 = last1 + 2;
			npat += 2;
		}

		if ((nd&1) == 0)
		{
			pat[npat*2+2] = last2[0]*ca - last2[1]*sa;
			pat[npat*2+3] = last2[0]*sa + last2[1]*ca;
			npat++;
		}
	}


	// Start sampling.
	float cr = vmax * (1.0f - m_params.velBias);
	float res[3];
	dtVset(res, dvel[0] * m_params.velBias, 0, dvel[2] * m_params.velBias);
	int ns = 0;

	for (int k = 0; k < depth; ++k)
	{
		float minPenalty = FLT_MAX;
		float bvel[3];
		dtVset(bvel, 0,0,0);
		
		for (int i = 0; i < npat; ++i)
		{
			float vcand[3];
			vcand[0] = res[0] + pat[i*2+0]*cr;
			vcand[1] = 0;
			vcand[2] = res[2] + pat[i*2+1]*cr;
			
			if (dtSqr(vcand[0])+dtSqr(vcand[2]) > dtSqr(vmax+0.001f)) continue;
			
			const float penalty = processSample(vcand,cr/10, pos,rad,vel,dvel, minPenalty, debug);
			ns++;
			if (penalty < minPenalty)
			{
				minPenalty = penalty;
				dtVcopy(bvel, vcand);
			}
		}

		dtVcopy(res, bvel);

		cr *= 0.5f;
	}	
	
	dtVcopy(nvel, res);
	
	return ns;
}
Example #13
0
 void run()
 {
     prepare();
     start();
     stop(Journal{});
 }
void AbstractDecorator::decorate(const QString &text, int state)
{
    if (text.contains("\n")) {
        qDebug() << "Wrong block found";
        return;
    }

    prepare(text);

    QmlJS::Scanner scanner;
    QList<QmlJS::Token> tokens = scanner(text, state);
    for (int i = 0; i < tokens.count(); i++) {
        const QmlJS::Token token = tokens.at(i);

        switch (token.kind) {
        case QmlJS::Token::Keyword:
            addKeyword(token.offset, token.length);
            break;
        case QmlJS::Token::Identifier: {
                QString entry = text.mid(token.offset, token.length);

                if (maybeQmlKeyword(entry)) {
                    // check the previous token
                    if (i == 0 || tokens.at(i - 1).isNot(QmlJS::Token::Dot)) {
                        if (i + 1 == tokens.count() || tokens.at(i + 1).isNot(QmlJS::Token::Colon)) {
                            addKeyword(token.offset, token.length);
                            break;
                        }
                    }
                } else if (i > 0 && maybeQmlBuiltinType(entry)) {
                    const QmlJS::Token &previousToken = tokens.at(i - 1);
                    if (previousToken.is(QmlJS::Token::Identifier)
                        && text.mid(previousToken.offset, previousToken.length) == QLatin1String("property")) {
                        addKeyword(token.offset, token.length);
                        break;
                    }
                }

                if (maybeMacro(entry)) {
                    addMacro(token.offset, token.length);
                    break;
                }

                if (entry.at(0).isUpper()) {
                    // Check if we are importing a module
                    if (i > 0) {
                        const QmlJS::Token &previousToken = tokens.first();
                        if (previousToken.is(QmlJS::Token::Identifier)
                            && text.mid(previousToken.offset, previousToken.length) == QLatin1String("import")) {
                            addKeyword(token.offset, token.length);
                            break;
                        }
                    }

                    addComponent(token.offset, token.length);
                    break;
                }

                // Try to find if it is a property
                // The easy ones are followed by a { or a :
                if (i + 1 < tokens.count()) {
                    const QmlJS::Token &nextToken = tokens.at(i + 1);
                    if (nextToken.is(QmlJS::Token::Colon)
                        || nextToken.is(QmlJS::Token::LeftBrace)) {
                        addIdentifier(token.offset, token.length);
                        break;
                    }
                }

                // A harder one is anchors.fill:
                if (i + 3 < tokens.count()) {
                    const QmlJS::Token &next1Token = tokens.at(i + 1);
                    const QmlJS::Token &next2Token = tokens.at(i + 2);
                    const QmlJS::Token &next3Token = tokens.at(i + 3);

                    if (next1Token.is(QmlJS::Token::Dot)
                        && next2Token.is(QmlJS::Token::Identifier)
                        && (next3Token.is(QmlJS::Token::Colon)
                            || next3Token.is(QmlJS::Token::LeftBrace))) {
                        addIdentifier(token.offset, token.length);
                        break;
                    }
                }
            }
            break;
        case QmlJS::Token::String:
            addString(token.offset, token.length);
            break;
        case QmlJS::Token::Comment:
            addComment(token.offset, token.length);
            break;
        case QmlJS::Token::Number:
            addNumber(token.offset, token.length);
            break;
        default:
            break;
        }
    }

    setState(scanner.state());
    finalize();
}
Example #15
0
    long long DeleteExecutor::execute(OperationContext* txn, Database* db) {
        uassertStatusOK(prepare());
        uassert(17417,
                mongoutils::str::stream() <<
                "DeleteExecutor::prepare() failed to parse query " << _request->getQuery(),
                _isQueryParsed);
        const bool logop = _request->shouldCallLogOp();
        const NamespaceString& ns(_request->getNamespaceString());
        if (!_request->isGod()) {
            if (ns.isSystem()) {
                uassert(12050,
                        "cannot delete from system namespace",
                        legalClientSystemNS(ns.ns(), true));
            }
            if (ns.ns().find('$') != string::npos) {
                log() << "cannot delete from collection with reserved $ in name: " << ns << endl;
                uasserted( 10100, "cannot delete from collection with reserved $ in name" );
            }
        }

        Collection* collection = db->getCollection(txn, ns.ns());
        if (NULL == collection) {
            return 0;
        }

        uassert(10101,
                str::stream() << "cannot remove from a capped collection: " << ns.ns(),
                !collection->isCapped());

        uassert(ErrorCodes::NotMaster,
                str::stream() << "Not primary while removing from " << ns.ns(),
                !logop ||
                repl::getGlobalReplicationCoordinator()->canAcceptWritesForDatabase(ns.db()));

        long long nDeleted = 0;

        Runner* rawRunner;
        if (_canonicalQuery.get()) {
            uassertStatusOK(getRunner(txn, collection, _canonicalQuery.release(), &rawRunner));
        }
        else {
            CanonicalQuery* ignored;
            uassertStatusOK(getRunner(txn,
                                      collection,
                                      ns.ns(),
                                      _request->getQuery(),
                                      &rawRunner,
                                      &ignored));
        }

        auto_ptr<Runner> runner(rawRunner);
        ScopedRunnerRegistration safety(runner.get());

        DiskLoc rloc;
        Runner::RunnerState state;
        CurOp* curOp = txn->getCurOp();
        int oldYieldCount = curOp->numYields();
        while (Runner::RUNNER_ADVANCED == (state = runner->getNext(NULL, &rloc))) {
            if (oldYieldCount != curOp->numYields()) {
                uassert(ErrorCodes::NotMaster,
                        str::stream() << "No longer primary while removing from " << ns.ns(),
                        !logop ||
                        repl::getGlobalReplicationCoordinator()->canAcceptWritesForDatabase(
                                ns.db()));
                oldYieldCount = curOp->numYields();
            }
            BSONObj toDelete;

            // TODO: do we want to buffer docs and delete them in a group rather than
            // saving/restoring state repeatedly?
            runner->saveState();
            collection->deleteDocument(txn, rloc, false, false, logop ? &toDelete : NULL );
            runner->restoreState(txn);

            nDeleted++;

            if (logop) {
                if ( toDelete.isEmpty() ) {
                    log() << "Deleted object without id in collection " << collection->ns()
                          << ", not logging.";
                }
                else {
                    bool replJustOne = true;
                    repl::logOp(txn, "d", ns.ns().c_str(), toDelete, 0, &replJustOne);
                }
            }

            if (!_request->isMulti()) {
                break;
            }

            if (!_request->isGod()) {
                txn->recoveryUnit()->commitIfNeeded();
            }

            if (debug && _request->isGod() && nDeleted == 100) {
                log() << "warning high number of deletes with god=true "
                      << " which could use significant memory b/c we don't commit journal";
            }
        }

        return nDeleted;
    }
Example #16
0
/* Perform one GS2 step.  GS2 state is in MECH_DATA.  Any data from
   server is provided in INPUT/INPUT_LEN and output from client is
   expected to be put in newly allocated OUTPUT/OUTPUT_LEN.  Return
   GSASL_NEEDS_MORE or GSASL_OK on success, or an error code.  */
int
_gsasl_gs2_client_step (Gsasl_session * sctx,
			void *mech_data,
			const char *input, size_t input_len,
			char **output, size_t * output_len)
{
  _gsasl_gs2_client_state *state = mech_data;
  gss_buffer_desc bufdesc;
  gss_buffer_t buf = GSS_C_NO_BUFFER;
  OM_uint32 maj_stat, min_stat, ret_flags;
  gss_OID actual_mech_type;
  int res;

  if (state->step > 2)
    return GSASL_MECHANISM_CALLED_TOO_MANY_TIMES;

  if (state->step == 0)
    {
      res = prepare (sctx, state);
      if (res != GSASL_OK)
	return res;
      state->step++;
    }

  if (state->step == 2)
    {
      bufdesc.length = input_len;
      bufdesc.value = (void *) input;
      buf = &bufdesc;
    }

  /* First release memory for token from last round-trip, if any. */
  if (state->token.value != NULL)
    {
      maj_stat = gss_release_buffer (&min_stat, &state->token);
      if (GSS_ERROR (maj_stat))
	return GSASL_GSSAPI_RELEASE_BUFFER_ERROR;

      state->token.value = NULL;
      state->token.length = 0;
    }

  maj_stat = gss_init_sec_context (&min_stat,
				   GSS_C_NO_CREDENTIAL,
				   &state->context,
				   state->service,
				   state->mech_oid,
				   GSS_C_MUTUAL_FLAG,
				   0,
				   &state->cb,
				   buf,
				   &actual_mech_type,
				   &state->token, &ret_flags, NULL);
  if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
    return GSASL_GSSAPI_INIT_SEC_CONTEXT_ERROR;

  res = token2output (sctx, state, &state->token, output, output_len);
  if (res != GSASL_OK)
    return res;

  if (maj_stat == GSS_S_CONTINUE_NEEDED)
    return GSASL_NEEDS_MORE;

  /* The GSS-API layer is done here, check that we established a valid
     security context for GS2 purposes. */

  if (!(ret_flags & GSS_C_MUTUAL_FLAG))
    return GSASL_AUTHENTICATION_ERROR;

  if (!gss_oid_equal (state->mech_oid, actual_mech_type))
    return GSASL_AUTHENTICATION_ERROR;

  state->step++;
  return GSASL_OK;
}
Example #17
0
	statement session::operator<<(std::string const &q)
	{
		return prepare(q);
	}
int DMM::queryForList(const char ***outList, const char *inQuery ...)
{
	if (NULL == outList)
		return -1;
	*outList = &empty_list;
	
	int sqlrv = SQLITE_OK;
	sqlite3_stmt *statement = NULL;

	va_list args;
	va_start(args, inQuery);
	int rv = prepare(&statement, inQuery, args);
	va_end(args);
	if (SQLITE_OK != rv)
		return rv;
	
	// Process..
	std::vector<const char*> accumulator;
	bool done = false;
	while (!done)
	{
		sqlrv = sqlite3_step(statement);
		switch (sqlrv)
		{
			case SQLITE_ROW:
				{
					int numColumns = sqlite3_column_count(statement);
					for (int col = 0; col < numColumns; ++col)
					{
						const char *p = reinterpret_cast<const char *>(sqlite3_column_text(statement, col));
						if (p)
						{
							char *np= (char *) malloc((strlen(p) + 1) * sizeof(char));
							strcpy(np, p);
							accumulator.push_back(np);
						}
						else
						{
							accumulator.push_back(NULL);
						}
					}
				}
				break;

			case SQLITE_DONE:
				if (accumulator.size() >= 1)
					rv = SQLITE_OK;
				else
				{
					rv = -1;
				}

				done = true;
				break;
				
			case SQLITE_ERROR:
				// Meaningful errors are reported at finalize, not here.
				break;

			default:
				done = true;
				break;
		}
	}

	// Slap together an array to return.
	if (SQLITE_OK == rv)
	{
		size_t elements = accumulator.size();
		*outList = (const char **) malloc((elements + 1) * sizeof(char*));
		if (NULL == *outList)
		{
			rv = -1;
		}
		else
		{
			for (int i = 0; i < static_cast<int>(elements); i++)
			{			
				(*outList)[i] = accumulator[i];
			}
			(*outList)[elements] = NULL;
		}
	}

	// Cleanup...
	sqlrv = sqlite3_finalize(statement);

	return rv;
}
Example #19
0
 void push(const T&x)const
 {
     prepare()=x;
 }
Example #20
0
File: kips.c Project: 10crimes/code
void line(V3d a,V3d b) {
  plotline(prepare(a),prepare(b),1);
}
Example #21
0
 virtual void reset(cmd_context & ctx) { m_dl_ctx->reset(); prepare(ctx); }
Example #22
0
void run_drakvuf(gpointer data, gpointer user_data)
{
    UNUSED(user_data);
    struct start_drakvuf* start = data;
    char* command;
    gint rc;
    GThread* timer;
    GThread* tcpd;

restart:
    command = NULL;
    rc = 0;
    printf("[%i] Starting %s on domid %u\n", start->threadid, start->input, start->cloneID);

    start->timer = 60;
    g_mutex_lock(&start->timer_lock);
    timer = g_thread_new("timer", timer_thread, start);

    command = g_strdup_printf(CONFIG_CMD, config_script, rekall_profile, start->cloneID, injection_pid, start->threadid+1, run_folder, start->input, out_folder, start->utime);
    printf("[%i] ** RUNNING COMMAND: %s\n", start->threadid, command);
    g_spawn_command_line_sync(command, NULL, NULL, &rc, NULL);
    g_free(command);

    g_mutex_unlock(&start->timer_lock);
    g_thread_join(timer);

    printf("[%i] ** Preconfig finished with RC %i. Timer: %i.\n", start->threadid, rc, start->timer);

    if (!start->timer)
        goto end;

    tcpd = g_thread_new("tcpdump", tcpdump, start);

    start->timer = 180;
    g_mutex_lock(&start->timer_lock);
    timer = g_thread_new("timer", timer_thread, start);

    command = g_strdup_printf(DRAKVUF_CMD, drakvuf_script, rekall_profile, start->cloneID, injection_pid, start->threadid+1, run_folder, start->input, out_folder, start->utime);
    printf("[%i] ** RUNNING COMMAND: %s\n", start->threadid, command);
    g_spawn_command_line_sync(command, NULL, NULL, &rc, NULL);
    g_free(command);

    g_mutex_unlock(&start->timer_lock);
    g_thread_join(timer);
    g_thread_join(tcpd);

    printf("[%i] ** DRAKVUF finished with RC %i. Timer: %i\n", start->threadid, rc, start->timer);

    if ( start->timer )
    {
        printf("[%i] Finished processing %s\n", start->threadid, start->input);

        g_mutex_unlock(&locks[start->threadid]);
        g_mutex_clear(&start->timer_lock);
        g_free(start->input);
        g_free(start->clone_name);
        g_free(start);
        return;
    }
    else
        cleanup(start->cloneID, start->threadid+1);

end:
    if ( !shutting_down )
    {
        printf("[%i] %s failed to execute on %u because of a timeout, creating new clone\n", start->threadid, start->input, start->cloneID);
        prepare(start, -1);
        goto restart;
    }
}
Example #23
0
void compareRndYields(int analysisIs2D=1,
		      TString conf="defaultAdHoc",
		      int iBr=0,
		      int doSave=0,
		      TString *figName=NULL,
		      TString *dirName=NULL) {

  if (!DYTools::setup(analysisIs2D)) {
    std::cout << "failed to initialize the analysis\n";
    return;
  }

  //--------------------------------------------------------------------------------------------------------------
  // Settings
  //==============================================================================================================

  int totalErr=1;
  int loadSyst=1;

  int the_set=0;
  std::vector<TString> pathV;
  std::vector<TString> fnameV;
  std::vector<TString> fieldV;
  std::vector<TString> labelV;
  TString canvasSaveName, canvasSaveDir;

  std::vector<HistoPair2D_t*> csV;

  double set_ratio_y[2];
  double transLegendX=(DYTools::study2D==1) ? -0.42 : -0.2;
  double transLegendY=0.;

  set_ratio_y[0]=1.00;
  set_ratio_y[1]=1.00;


  InputFileMgr_t inpMgr;
  if (!inpMgr.Load(conf)) return;

  DYTools::TRunMode_t runMode= DYTools::NORMAL_RUN;
  DYTools::TSystematicsStudy_t systModeRef, systMode1, systMode2, systModeV;
  systModeRef=DYTools::APPLY_ESCALE;
  systMode1  =DYTools::SYST_MODE_FAILURE;
  systMode2  =DYTools::SYST_MODE_FAILURE;
  systModeV  =DYTools::SYST_MODE_FAILURE;

  int seedMin=inpMgr.userKeyValueAsInt("SEEDMIN");
  int seedMax=inpMgr.userKeyValueAsInt("SEEDMAX");
  int dSeed=1;
  unsigned int idxRndVec=(unsigned int)(-1);

  //--------------------------------------------------------------------------------------------------------------
  // Define branches
  //==============================================================================================================

  TString extraTag;
  TString plotExtraTag;

  if ((iBr==0) || (iBr==1)) { // added on 2014.04.12

    if (iBr==1) {
      seedMin=-111;
      seedMax= 111;
      dSeed= 222;
    }

    loadSyst=0;
    prepare(2,pathV,fnameV,fieldV,labelV);
    // Construct eventSelector, update mgr and plot directory
    systModeRef=DYTools::APPLY_ESCALE;
    EventSelector_t evtSelector1(inpMgr,runMode,systModeRef,
		       extraTag, plotExtraTag, EventSelector::_selectDefault);
    pathV [0]="";
    fnameV[0]=inpMgr.yieldFullFileName(-1,systModeRef,0);
    fieldV[0]="yields/hYield_data";
    labelV[0]="Data with peak corr.";

    systMode1=DYTools::ESCALE_DIFF_0000;
    EventSelector_t evtSelector2(inpMgr,runMode,systMode1,
		       extraTag, plotExtraTag, EventSelector::_selectDefault);
    pathV [1]="";
    fnameV[1]=inpMgr.yieldFullFileName(-1,systMode1,0);
    fieldV[1]="yields/hYield_data";
    labelV[1]="Data (regressed)";

    prepare(int((seedMax-seedMin)/dSeed),pathV,fnameV,fieldV,labelV,0,0);
    systModeV=DYTools::ESCALE_STUDY_RND;
    idxRndVec=pathV.size();
    for (int iseed=seedMin; iseed<=seedMax; iseed+=dSeed) {
      //if ((1 || (dSeed==1)) && (iseed-seedMin>79)) break;
      //if (iseed-seedMin>2) break;
      InputFileMgr_t inpMgrRnd(inpMgr);
      inpMgrRnd.editEnergyScaleTag().Append(Form("_RANDOMIZED%d",iseed));
      EventSelector_t evtSelector3(inpMgrRnd,runMode,systModeV,
		       extraTag, plotExtraTag, EventSelector::_selectDefault);
      pathV.push_back("");
      fnameV.push_back(inpMgrRnd.yieldFullFileName(-1,systModeV,0));
      fieldV.push_back("yields/hYield_data");
      labelV.push_back(Form("Data rnd%d",iseed));
    }

    transLegendX=(DYTools::study2D==1) ? -0.42 : -0.1;
  }

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code
  //==============================================================================================================


  /*
  {
    canvasSaveName="fig-puStudy-";
    canvasSaveDir="plots-puStudy";
    transLegendX=(DYTools::study2D==1) ? -0.35 : -0.1;
    transLegendY=(DYTools::study2D==1) ? -0.55 : -0.0;
    set_ratio_y[0]=(DYTools::study2D==1) ? 0.9 : 0.96;
    set_ratio_y[1]=(DYTools::study2D==1) ? 1.1 : 1.04;
  }
  */

  if (DYTools::study2D) {
    for (unsigned int i=0; i<fnameV.size(); ++i) {
      fnameV[i].ReplaceAll("preFsr_1D","preFsrDet_2D");
    }
  }

  if (!loadHistoPairV(pathV,fnameV,fieldV,labelV, csV, loadSyst)) {
    std::cout << "failed to load data\n";
    return;
  }

  std::vector<TH2D*> histoV;
  if (!convertHistoPairVec2HistoVec(csV, histoV, totalErr)) {
    std::cout << "failed to prepare histos\n";
    return;
  }

  std::vector<ComparisonPlot_t*> cpV;
  std::vector<std::vector<TH1D*>*> hProfV;
  int delayDraw=1;
  TCanvas *cx=plotProfiles("cx",histoV,labelV,NULL,0,"observed yield counts",
			   &hProfV, &cpV,delayDraw);
  if (!cx) {
    std::cout << "failed to create canvas with profiles\n";
    return;
  }

  if (iBr==1) {
    // shift the notation
    HERE("shift the notation\n");
    for (unsigned int ic=0; ic<cpV.size(); ++ic) {
      if (DYTools::study2D==0) cpV[ic]->SetLogy(1);
      TH1D* h1=cpV[ic]->GetHisto(0);
      h1->SetMarkerStyle(24);
      h1->SetMarkerColor(kBlue);
      h1->SetLineColor(kBlue);
      h1->SetLineStyle(2);
      TH1D* h2=cpV[ic]->GetHisto(1);
      h2->SetMarkerStyle(5);
      h2->SetMarkerColor(kGreen+1);
      h2->SetMarkerSize(1.5);
      h2->SetLineStyle(1);
      h2->SetLineColor(kGreen+1);
      TH1D* h3=cpV[ic]->GetHisto(2);
      h3->SetMarkerStyle(3);
      h3->SetMarkerColor(kOrange+1);
      h3->SetMarkerSize(1.5);
      h3->SetLineStyle(3);
      h3->SetLineColor(kOrange+1);
      TH1D* h4=cpV[ic]->GetHisto(3);
      h4->SetMarkerStyle(2);
      h4->SetMarkerColor(kRed);
      h4->SetLineStyle(2);
      h4->SetLineColor(kRed);
    }
  }

  for (unsigned int ic=0; ic<cpV.size(); ++ic) {
    ComparisonPlot_t *cp=cpV[ic];
    cp->TransLegend(transLegendX,transLegendY);
    cp->SetRatioYRange(set_ratio_y[0], set_ratio_y[1]);
    if (DYTools::study2D) cp->Draw6(cx,1,ic+1);
    else cp->Draw(cx);
  }
  cx->Update();


  // plot count dirstributions of a mass bin
  if (0 && (DYTools::study2D==0)) {
    std::cout << "hProfV.size()=" << hProfV.size() << "\n";
    std::vector<TH1D*> hMassV;
    std::vector<TString> massStrV;
    massStrV.reserve(DYTools::nMassBins);
    for (int im=0; im<DYTools::nMassBins; ++im) {
      massStrV.push_back(Form("M_%1.0lf_%1.0lf",
		  DYTools::massBinLimits[im],DYTools::massBinLimits[im+1]));
    }
    if (!createAnyH1Vec(hMassV,"hMassProf_",massStrV,200,-1e6,1e6,
			"yield count","count",1)) return;
    std::vector<TH1D*> *histos=hProfV[0];
    for (int im=14; im<20; im++) {
      double avg=0.;
      int count=0;
      for (unsigned int ii=0; ii<histos->size(); ++ii) {
	avg+=(*histos)[ii]->GetBinContent(im);
	count++;
      }
      avg/=double(count);
      for (unsigned int ii=0; ii<histos->size(); ++ii) {
	hMassV[im]->Fill((*histos)[ii]->GetBinContent(im) - avg);
      }

      TString canvName=TString("canvProfAt_") + massStrV[im];
      TCanvas *cm=new TCanvas(canvName,canvName,600,600);
      hMassV[im]->Draw();
      cm->Update();
    }
  }

  TString outName=canvasSaveName + DYTools::analysisTag;
  if (doSave) {
    SaveCanvas(cx,outName,canvasSaveDir);
  }
  else {
    std::cout << "would save to <" << outName << "> in <" << canvasSaveDir << ">\n";
  }
  if (figName) *figName= outName;
  if (dirName) *dirName= canvasSaveDir;

  // Covariance study
  if (0) {
    std::vector<TH2D*> hRndVec;
    hRndVec.reserve(histoV.size());
    for (unsigned int i=idxRndVec; i<histoV.size(); ++i) {
      hRndVec.push_back(histoV[i]);
    }

    int unbiasedEstimate=1;
    TH2D* avgDistr=createBaseH2("hYieldAvgDistr");
    TMatrixD* cov= deriveCovMFromRndStudies(hRndVec,unbiasedEstimate,avgDistr);
    TMatrixD* corr=corrFromCov(*cov);

    TCanvas *canvCov= new TCanvas("ccov","ccov",900,900);
    AdjustFor2DplotWithHeight(canvCov);
    cov->Draw("COLZ");
    canvCov->Update();
    TCanvas *canvCorr= new TCanvas("ccorr","ccorr",900,900);
    AdjustFor2DplotWithHeight(canvCorr);
    corr->Draw("COLZ");
    canvCorr->Update();
  }

  return;
}
Example #24
0
int main(int argc, char** argv)
{
    DIR* dir;
    struct dirent* ent;
    unsigned int i;
    unsigned int processed = 0;
    unsigned int total_processed = 0;
    int ret = 0;
    struct sigaction act;
    shutting_down = 0;

    if (argc!=15)
    {
        printf("Not enough arguments: %i!\n", argc);
        printf("%s <loop (0) or poll (1)> <origin domain name> <domain config> <rekall_profile> <injection pid> <watch folder> <serve folder> <output folder> <max clones> <clone_script> <config_script> <drakvuf_script> <cleanup_script> <tcpdump_script>\n", argv[0]);
        return 1;
    }

    /* for a clean exit */
    act.sa_handler = close_handler;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    sigaction(SIGHUP, &act, NULL);
    sigaction(SIGTERM, &act, NULL);
    sigaction(SIGINT, &act, NULL);
    sigaction(SIGALRM, &act, NULL);

    xen_init_interface(&xen);

    int do_poll = atoi(argv[1]);
    domain_name = argv[2];
    domain_config = argv[3];
    rekall_profile = argv[4];
    injection_pid = atoi(argv[5]);
    in_folder = argv[6];
    run_folder = argv[7];
    out_folder = argv[8];
    threads = atoi(argv[9]);
    clone_script = argv[10];
    config_script = argv[11];
    drakvuf_script = argv[12];
    cleanup_script = argv[13];
    tcpdump_script = argv[14];

    if (threads > 128)
    {
        printf("Too many clones requested (max 128 is specified right now)\n");
        return 1;
    }

    for (i=0; i<threads; i++)
        g_mutex_init(&locks[i]);

    pool = g_thread_pool_new(run_drakvuf, NULL, threads, TRUE, NULL);

    int fd = inotify_init();
    int wd = inotify_add_watch(fd, in_folder, IN_CLOSE_WRITE);
    char buffer[sizeof(struct inotify_event) + NAME_MAX + 1];

    struct pollfd pollfd =
    {
        .fd = fd,
        .events = POLLIN
    };

    int threadid = -1;

    do
    {
        processed = 0;

        while (threadid<0 && !shutting_down)
        {
            sleep(1);
            threadid = find_thread();
        }

        if ((dir = opendir (in_folder)) != NULL)
        {
            while ((ent = readdir (dir)) != NULL && !shutting_down)
            {
                if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
                    continue;

                char* command;
                command = g_strdup_printf("mv %s/%s %s/%s", in_folder, ent->d_name, run_folder, ent->d_name);
                printf("** MOVING FILE FOR PROCESSING: %s\n", command);
                g_spawn_command_line_sync(command, NULL, NULL, NULL, NULL);
                g_free(command);

                struct start_drakvuf* _start = prepare(NULL, threadid);
                start(_start, ent->d_name);

                threadid = -1;
                processed++;

            }
            closedir (dir);
        }
        else
        {
            printf("Failed to open target folder!\n");
            ret = 1;
            break;
        }

        if ( processed )
        {
            total_processed += processed;
            printf("Batch processing started %u samples (total %u)\n", processed, total_processed);
        }

        if ( !processed && !shutting_down )
        {
            if ( do_poll )
            {
                do
                {
                    int rv = poll (&pollfd, 1, 1000);
                    if ( rv < 0 )
                    {
                        printf("Error polling\n");
                        ret = 1;
                        break;
                    }
                    if ( rv > 0 && pollfd.revents & POLLIN )
                    {
                        if ( read( fd, buffer, sizeof(struct inotify_event) + NAME_MAX + 1 ) < 0 )
                        {
                            printf("Error reading inotify event\n");
                            ret = 1;
                        }
                        break;
                    }
                }
                while (!shutting_down && !ret);
            }
            else
                sleep(1);
        }
    }
    while (!shutting_down && !ret);

    inotify_rm_watch( fd, wd );
    close(fd);

    g_thread_pool_free(pool, FALSE, TRUE);

    if ( threadid >= 0 )
        g_mutex_unlock(&locks[threadid]);

    for (i=0; i<threads; i++)
        g_mutex_clear(&locks[i]);

    xen_free_interface(xen);

    printf("Finished processing %u samples\n", total_processed);
    return ret;
}
void QDeclarativeTextLayout::draw(QPainter *painter, const QPointF &p)
{
    QPainterPrivate *priv = QPainterPrivate::get(painter);

    bool paintEngineSupportsTransformations = priv->extended &&
                                              (priv->extended->type() == QPaintEngine::OpenGL2 ||
                                               priv->extended->type() == QPaintEngine::OpenVG ||
                                               priv->extended->type() == QPaintEngine::OpenGL);

    if (!paintEngineSupportsTransformations || !priv->state->matrix.isAffine()) {
        QTextLayout::draw(painter, p);
        return;
    }

    prepare();

    int itemCount = d->items.count();

    if (p != d->position) {
        QFixed fx = QFixed::fromReal(p.x());
        QFixed fy = QFixed::fromReal(p.y());
        QFixed oldX = QFixed::fromReal(d->position.x());
        QFixed oldY = QFixed::fromReal(d->position.y());
        for (int item = 0; item < itemCount; ++item) {
            QStaticTextItem &textItem = d->items[item];

            for (int ii = 0; ii < textItem.numGlyphs; ++ii) {
                textItem.glyphPositions[ii].x += fx - oldX;
                textItem.glyphPositions[ii].y += fy - oldY;
            }
            textItem.userDataNeedsUpdate = true;
        }

        d->position = p;
    }

    QPen oldPen = priv->state->pen;
    QColor currentColor = oldPen.color();
    QColor defaultColor = currentColor;
    for (int ii = 0; ii < itemCount; ++ii) {
        QStaticTextItem &item = d->items[ii];
        if (item.color.isValid() && currentColor != item.color) {
            // up-edge of a <font color="">text</font> tag
            // we set the painter pen to the text item's specified color.
            painter->setPen(item.color);
            currentColor = item.color;
        } else if (!item.color.isValid() && currentColor != defaultColor) {
            // down-edge of a <font color="">text</font> tag
            // we reset the painter pen back to the default color.
            currentColor = defaultColor;
            painter->setPen(currentColor);
        }
        priv->extended->drawStaticTextItem(&item);

        qt_draw_decoration_for_glyphs(painter, item.glyphs, item.glyphPositions,
                                      item.numGlyphs, item.fontEngine(), painter->font(),
                                      QTextCharFormat());
    }
    if (currentColor != oldPen.color())
        painter->setPen(oldPen);
}
Example #26
0
Error StringBuilder::_opNumber(uint32_t op, uint64_t i, uint32_t base, size_t width, uint32_t flags) noexcept {
  if (base < 2 || base > 36)
    base = 10;

  char buf[128];
  char* p = buf + ASMJIT_ARRAY_SIZE(buf);

  uint64_t orig = i;
  char sign = '\0';

  // --------------------------------------------------------------------------
  // [Sign]
  // --------------------------------------------------------------------------

  if ((flags & kStringFormatSigned) != 0 && static_cast<int64_t>(i) < 0) {
    i = static_cast<uint64_t>(-static_cast<int64_t>(i));
    sign = '-';
  }
  else if ((flags & kStringFormatShowSign) != 0) {
    sign = '+';
  }
  else if ((flags & kStringFormatShowSpace) != 0) {
    sign = ' ';
  }

  // --------------------------------------------------------------------------
  // [Number]
  // --------------------------------------------------------------------------

  do {
    uint64_t d = i / base;
    uint64_t r = i % base;

    *--p = StringBuilder_numbers[r];
    i = d;
  } while (i);

  size_t numberLength = (size_t)(buf + ASMJIT_ARRAY_SIZE(buf) - p);

  // --------------------------------------------------------------------------
  // [Alternate Form]
  // --------------------------------------------------------------------------

  if ((flags & kStringFormatAlternate) != 0) {
    if (base == 8) {
      if (orig != 0)
        *--p = '0';
    }
    if (base == 16) {
      *--p = 'x';
      *--p = '0';
    }
  }

  // --------------------------------------------------------------------------
  // [Width]
  // --------------------------------------------------------------------------

  if (sign != 0)
    *--p = sign;

  if (width > 256)
    width = 256;

  if (width <= numberLength)
    width = 0;
  else
    width -= numberLength;

  // --------------------------------------------------------------------------
  // Write]
  // --------------------------------------------------------------------------

  size_t prefixLength = (size_t)(buf + ASMJIT_ARRAY_SIZE(buf) - p) - numberLength;
  char* data = prepare(op, prefixLength + width + numberLength);

  if (!data)
    return DebugUtils::errored(kErrorNoHeapMemory);

  ::memcpy(data, p, prefixLength);
  data += prefixLength;

  ::memset(data, '0', width);
  data += width;

  ::memcpy(data, p + prefixLength, numberLength);
  return kErrorOk;
}
Example #27
0
 void fft::inverse(const channel& input, channel& output, uint16_t points) {
     plan &p = prepare(points, false);
     memcpy(p.input, input.data(), sizeof(fftw_complex)*points);
     fftw_execute(p.plan);
     memcpy(output.data(), p.output, sizeof(fftw_complex)*points);
 }
Example #28
0
/*---------------------------------------------------------------------------*/
static int
send(const void *payload, unsigned short payload_len)
{
  prepare(payload, payload_len);
  return transmit(payload_len);
}
Example #29
0
bool ReadBufferAIO::nextImpl()
{
    /// If the end of the file has already been reached by calling this function,
    /// then the current call is wrong.
    if (is_eof)
        return false;

    std::optional<Stopwatch> watch;
    if (profile_callback)
        watch.emplace(clock_type);

    if (!is_aio)
    {
        synchronousRead();
        is_aio = true;
    }
    else
        receive();

    if (profile_callback)
    {
        ProfileInfo info;
        info.bytes_requested = requested_byte_count;
        info.bytes_read = bytes_read;
        info.nanoseconds = watch->elapsed();
        profile_callback(info);
    }

    is_started = true;

    /// If the end of the file is just reached, do nothing else.
    if (is_eof)
        return bytes_read != 0;

    /// Create an asynchronous request.
    prepare();

#if defined(__FreeBSD__)
    request.aio.aio_lio_opcode = LIO_READ;
    request.aio.aio_fildes = fd;
    request.aio.aio_buf = reinterpret_cast<volatile void *>(buffer_begin);
    request.aio.aio_nbytes = region_aligned_size;
    request.aio.aio_offset = region_aligned_begin;
#else
    request.aio_lio_opcode = IOCB_CMD_PREAD;
    request.aio_fildes = fd;
    request.aio_buf = reinterpret_cast<UInt64>(buffer_begin);
    request.aio_nbytes = region_aligned_size;
    request.aio_offset = region_aligned_begin;
#endif

    /// Send the request.
    try
    {
        future_bytes_read = AIOContextPool::instance().post(request);
    }
    catch (...)
    {
        aio_failed = true;
        throw;
    }

    is_pending_read = true;
    return true;
}
Example #30
0
void EMIModel::loadMesh(Common::SeekableReadStream *data) {
	int strLength = 0; // Usefull for PS2-strings
	
	Common::String nameString = readLAString(*data);
	
	_sphereData = readVector4d(*data);

	_boxData = readVector3d(*data);
	_boxData2 = readVector3d(*data);

	_numTexSets = data->readUint32LE();
	_setType = data->readUint32LE();
	_numTextures = data->readUint32LE();

	_texNames = new Common::String[_numTextures];

	for(uint32 i = 0;i < _numTextures; i++) {
		_texNames[i] = readLAString(*data);
		// Every texname seems to be followed by 4 0-bytes (Ref mk1.mesh,
		// this is intentional)
		data->skip(4);
	}

	// 4 unknown bytes - usually with value 19
	data->skip(4);

	_numVertices = data->readUint32LE();

	// Vertices
	_vertices = readVector3d(*data, _numVertices);
	_normals = readVector3d(*data, _numVertices);
	_colorMap = new EMIColormap[_numVertices];
	for (int i = 0; i < _numVertices; ++i) {
		_colorMap[i].r = data->readByte();
		_colorMap[i].g = data->readByte();
		_colorMap[i].b = data->readByte();
		_colorMap[i].a = data->readByte();
	}
	_texVerts = readVector2d(*data, _numVertices);

	// Faces

	_numFaces = data->readUint32LE();

	// Handle the empty-faced fx/screen?.mesh-files
	if (data->eos()) {
		_numFaces = 0;
		_faces = NULL;
		return;
	}

	_faces = new EMIMeshFace[_numFaces];

	for(uint32 j = 0;j < _numFaces; j++) {
		_faces[j].setParent(this);
		_faces[j].loadFace(data);
	}

	int hasBones = data->readUint32LE();

	// TODO add in the bone-stuff, as well as the skeleton
	prepare(); // <- Initialize materials etc.
}