Example #1
0
void LabelTTF::setFontFile(const std::string& fontFile)
{
	TTFConfig ttfConfig = getTTFConfig();

	if ( FileUtils::getInstance()->isFileExist(fontFile) )
	{
		TTFConfig newConfig(fontFile.c_str(),ttfConfig.fontSize,GlyphCollection::DYNAMIC);
		setTTFConfig(newConfig);
		enableOutline(Color4B::BLACK,2);
	}
}
Example #2
0
void LabelTTF::setFontSize(float fontSize)
{
	TTFConfig ttfConfig = getTTFConfig();

	if ( FileUtils::getInstance()->isFileExist(ttfConfig.fontFilePath) )
	{
		TTFConfig newConfig(ttfConfig.fontFilePath.c_str(),fontSize,GlyphCollection::DYNAMIC);
		setTTFConfig(newConfig);
		enableOutline(Color4B::BLACK,2);
	}
}
bool mitk::InteractionEventHandler::SetEventConfig(const std::string& filename, const Module* module)
{
    EventConfig newConfig(filename, module);
    if (newConfig.IsValid())
    {
        m_EventConfig = newConfig;
        // notify sub-classes that new config is set
        ConfigurationChanged();
        return true;
    }
    return false;
}
Example #4
0
/*!
 \brief

 \fn cdegs_main::connectSlots
*/
void cdegs_main::connectSlots(){
    QObject::connect(ui->actionNew_Project, SIGNAL(triggered()),
                      this,  SLOT(newProject()));

    QObject::connect(ui->actionNew_Config, SIGNAL(triggered()),
                      this,  SLOT(newConfig()));

    QObject::connect(ui->actionOpen_Project, SIGNAL(triggered()),
                      this,  SLOT(openProject()));

    QObject::connect(ui->actionSave_Project, SIGNAL(triggered()),
                      this,  SLOT(saveProject()));

    QObject::connect(ui->actionSave_Project_as, SIGNAL(triggered()),
                      this,  SLOT(saveProjectAs()));

    QObject::connect(ui->actionClose_Project, SIGNAL(triggered()),
                      this,  SLOT(closeProject()));

    QObject::connect(ui->tabProjects, SIGNAL(currentChanged(int)),
                     this, SLOT(changeTab()));

    QObject::connect(ui->tabProjects, SIGNAL(tabCloseRequested(int)),
                     this, SLOT(closeProject(int)));

    QObject::connect(ui->actionAbout, SIGNAL(triggered()),
                     this, SLOT(about()));

    QObject::connect(ui->actionStylesheet, SIGNAL(triggered()),
                     this, SLOT(openStyleDialog()));

    QObject::connect(ui->actionOpen_Config, SIGNAL(triggered()),
                     this, SLOT(openConfigDialog()));

    QObject::connect(ui->actionSave_Config, SIGNAL(triggered()),
                     this, SLOT(saveConfig()));

    QObject::connect(ui->actionClose_Config, SIGNAL(triggered()),
                     this, SLOT(closeConfig()));

    QObject::connect(ui->actionExport_Config, SIGNAL(triggered()),
                     this, SLOT(exportConfig()));

    QObject::connect(ui->actionExport_Config_as, SIGNAL(triggered()),
                     this, SLOT(exportConfigAs()));

    QObject::connect(ui->actionSave_All_Configs, SIGNAL(triggered()),
                     this, SLOT(saveAllConfigs()));
}
bool mitk::EventConfig::AddConfig(const std::string &fileName, const us::Module *module)
{
  if (module == NULL)
  {
    module = us::GetModuleContext()->GetModule();
  }
  us::ModuleResource resource = module->GetResource("Interactions/" + fileName);
  if (!resource.IsValid())
  {
    MITK_ERROR << "Resource not valid. State machine pattern in module " << module->GetName()
               << " not found: /Interactions/" << fileName;
    return false;
  }

  EventConfig newConfig(*this);
  us::ModuleResourceStream stream(resource);
  newConfig.d->m_XmlParser.SetStream(&stream);
  bool success = newConfig.d->m_XmlParser.Parse() && !newConfig.d->m_Errors;
  if (success)
  {
    *this = newConfig;
  }
  return success;
}
Example #6
0
/* ********************************************************************************************* */
RRT::StepResult RRT::tryStepFromNode(const VectorXd &qtry, int NNidx) {

	// Get the configuration of the nearest neighbor and check if already reached
	const VectorXd& qnear = *(configVector[NNidx]);
	if((qtry - qnear).norm() < stepSize) {
		return STEP_REACHED;
	}

	// Create the new node: scale the direction vector to stepSize and add to qnear
	VectorXd qnew = qnear + stepSize * (qtry - qnear).normalized();

	// Check for collision, make changes to the qNew and create intermediate points if necessary
	// NOTE: This is largely implementation dependent and in default, no points are created.
	list<VectorXd> intermediatePoints;
	bool collisionClear = newConfig(intermediatePoints, qnew, qnear, qtry);
	if(!collisionClear) return STEP_COLLISION;

	// Add the intermediate nodes and the final new node to the tree
	list <VectorXd>::iterator it = intermediatePoints.begin();
	for(; it != intermediatePoints.end(); it++) 
		NNidx = addNode(*it, NNidx);
	addNode(qnew, NNidx);
	return STEP_PROGRESS;
}
Example #7
0
        virtual bool run(const string& , BSONObj& cmdObj, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
            log() << "replSet replSetInitiate admin command received from client" << rsLog;

            if( !replSet ) {
                errmsg = "server is not running with --replSet";
                return false;
            }
            if( theReplSet ) {
                errmsg = "already initialized";
                result.append("info", "try querying " + rsConfigNs + " to see current configuration");
                return false;
            }

            {
                // just make sure we can get a write lock before doing anything else.  we'll reacquire one
                // later.  of course it could be stuck then, but this check lowers the risk if weird things
                // are up.
                time_t t = time(0);
                writelock lk("");
                if( time(0)-t > 10 ) {
                    errmsg = "took a long time to get write lock, so not initiating.  Initiate when server less busy?";
                    return false;
                }

                /* check that we don't already have an oplog.  that could cause issues.
                   it is ok if the initiating member has *other* data than that.
                   */
                BSONObj o;
                if( Helpers::getFirst(rsoplog, o) ) {
                    errmsg = rsoplog + string(" is not empty on the initiating member.  cannot initiate.");
                    return false;
                }
            }

            if( ReplSet::startupStatus == ReplSet::BADCONFIG ) {
                errmsg = "server already in BADCONFIG state (check logs); not initiating";
                result.append("info", ReplSet::startupStatusMsg.get());
                return false;
            }
            if( ReplSet::startupStatus != ReplSet::EMPTYCONFIG ) {
                result.append("startupStatus", ReplSet::startupStatus);
                errmsg = "all members and seeds must be reachable to initiate set";
                result.append("info", cmdLine._replSet);
                return false;
            }

            BSONObj configObj;

            if( cmdObj["replSetInitiate"].type() != Object ) {
                result.append("info2", "no configuration explicitly specified -- making one");
                log() << "replSet info initiate : no configuration specified.  Using a default configuration for the set" << rsLog;

                string name;
                vector<HostAndPort> seeds;
                set<HostAndPort> seedSet;
                parseReplsetCmdLine(cmdLine._replSet, name, seeds, seedSet); // may throw...

                bob b;
                b.append("_id", name);
                bob members;
                members.append("0", BSON( "_id" << 0 << "host" << HostAndPort::Me().toString() ));
                for( unsigned i = 0; i < seeds.size(); i++ )
                    members.append(bob::numStr(i+1), BSON( "_id" << i+1 << "host" << seeds[i].toString()));
                b.appendArray("members", members.obj());
                configObj = b.obj();
                log() << "replSet created this configuration for initiation : " << configObj.toString() << rsLog;
            }
            else {
                configObj = cmdObj["replSetInitiate"].Obj();
            }

            bool parsed = false;
            try {
                ReplSetConfig newConfig(configObj);
                parsed = true;

                if( newConfig.version > 1 ) {
                    errmsg = "can't initiate with a version number greater than 1";
                    return false;
                }

                log() << "replSet replSetInitiate config object parses ok, " << newConfig.members.size() << " members specified" << rsLog;

                checkMembersUpForConfigChange(newConfig, true);

                log() << "replSet replSetInitiate all members seem up" << rsLog;

                createOplog();

                writelock lk("");
                bo comment = BSON( "msg" << "initiating set");
                newConfig.saveConfigLocally(comment);
                log() << "replSet replSetInitiate config now saved locally.  Should come online in about a minute." << rsLog;
                result.append("info", "Config now saved locally.  Should come online in about a minute.");
                ReplSet::startupStatus = ReplSet::SOON;
                ReplSet::startupStatusMsg.set("Received replSetInitiate - should come online shortly.");
            }
            catch( DBException& e ) {
                log() << "replSet replSetInitiate exception: " << e.what() << rsLog;
                if( !parsed )
                    errmsg = string("couldn't parse cfg object ") + e.what();
                else
                    errmsg = string("couldn't initiate : ") + e.what();
                return false;
            }

            return true;
        }
bool AutoVersioner::consume(IAaptContext* context, ResourceTable* table) {
    for (auto& package : table->packages) {
        for (auto& type : package->types) {
            if (type->type != ResourceType::kStyle) {
                continue;
            }

            for (auto& entry : type->entries) {
                for (size_t i = 0; i < entry->values.size(); i++) {
                    ResourceConfigValue* configValue = entry->values[i].get();
                    if (configValue->config.sdkVersion >= SDK_LOLLIPOP_MR1) {
                        // If this configuration is only used on L-MR1 then we don't need
                        // to do anything since we use private attributes since that version.
                        continue;
                    }

                    if (Style* style = valueCast<Style>(configValue->value.get())) {
                        Maybe<size_t> minSdkStripped;
                        std::vector<Style::Entry> stripped;

                        auto iter = style->entries.begin();
                        while (iter != style->entries.end()) {
                            assert(iter->key.id && "IDs must be assigned and linked");

                            // Find the SDK level that is higher than the configuration allows.
                            const size_t sdkLevel = findAttributeSdkLevel(iter->key.id.value());
                            if (sdkLevel > std::max<size_t>(configValue->config.sdkVersion, 1)) {
                                // Record that we are about to strip this.
                                stripped.emplace_back(std::move(*iter));

                                // We use the smallest SDK level to generate the new style.
                                if (minSdkStripped) {
                                    minSdkStripped = std::min(minSdkStripped.value(), sdkLevel);
                                } else {
                                    minSdkStripped = sdkLevel;
                                }

                                // Erase this from this style.
                                iter = style->entries.erase(iter);
                                continue;
                            }
                            ++iter;
                        }

                        if (minSdkStripped && !stripped.empty()) {
                            // We found attributes from a higher SDK level. Check that
                            // there is no other defined resource for the version we want to
                            // generate.
                            if (shouldGenerateVersionedResource(entry.get(),
                                                                configValue->config,
                                                                minSdkStripped.value())) {
                                // Let's create a new Style for this versioned resource.
                                ConfigDescription newConfig(configValue->config);
                                newConfig.sdkVersion = minSdkStripped.value();

                                std::unique_ptr<Style> newStyle(style->clone(&table->stringPool));
                                newStyle->setComment(style->getComment());
                                newStyle->setSource(style->getSource());

                                // Move the previously stripped attributes into this style.
                                newStyle->entries.insert(newStyle->entries.end(),
                                                         std::make_move_iterator(stripped.begin()),
                                                         std::make_move_iterator(stripped.end()));

                                // Insert the new Resource into the correct place.
                                entry->findOrCreateValue(newConfig, {})->value =
                                        std::move(newStyle);
                            }
                        }
                    }
                }
            }
        }
    }
    return true;
}
// Commit
//------------------------------------------------------------------------------
/*virtual*/ bool FunctionVCXProject::Commit( const BFFIterator & funcStartIter ) const
{
	// required
	AStackString<> projectOutput;
	AStackString<> rootNamespace;
	AStackString<> projectGuid;
	AStackString<> defaultLanguage;
	AStackString<> applicationEnvironment;
	if ( !GetString( funcStartIter, projectOutput,		".ProjectOutput", true ) ||
		 !GetString( funcStartIter, rootNamespace,		".RootNamespace", false ) ||
		 !GetString( funcStartIter, projectGuid,		".ProjectGuid", false ) ||
		 !GetString( funcStartIter, defaultLanguage,	".DefaultLanguage", false ) ||
		 !GetString( funcStartIter, applicationEnvironment,	".ApplicationEnvironment", false ) )
	{
		return false;
	}

	// optional inputs
	Array< AString > inputPaths;
	Array< AString > inputPathsExclude;
	if ( !GetStrings( funcStartIter, inputPaths,		".ProjectInputPaths", false ) ||
		 !GetStrings( funcStartIter, inputPathsExclude,	".ProjectInputPathsExclude", false ) )
	{
		return false;
	}

	// project base
	Array< AString > basePaths;
	if ( !GetStrings( funcStartIter, basePaths,	".ProjectBasePath", false ) )
	{
		return false;
	}
	CleanFolderPaths( basePaths );

	// references
	Array< AString > references;
	Array< AString > projectReferences;
	if ( !GetStrings( funcStartIter, references,		".ProjectReferences", false ) ||
		 !GetStrings( funcStartIter, projectReferences,	".ProjectProjectReferences", false ) )
	{
		return false;
	}

	// permitted file extensions
	Array< AString > allowedFileExtensions( 8, true );
	if ( !GetStrings( funcStartIter, allowedFileExtensions, ".ProjectAllowedFileExtensions", false ) )
	{
		return true;
	}
	if ( allowedFileExtensions.IsEmpty() )
	{
		const char * extensions[] = { ".cpp", ".hpp", ".cxx",".hxx",".c",".h",".cc",".hh",
									  ".cp",".hp",".cs",".inl",".bff",".rc",".resx",".m",".mm",
									  ".cu",
									  nullptr };
		AStackString<> tmp;
		const char ** item = extensions;
		while ( *item )
		{
			tmp.Assign( *item );
			allowedFileExtensions.Append( tmp );
			++item;
		}
	}

	// files and filesToExclude
	Array< AString > files( 8, true );
	Array< AString > filesToExclude( 8, true );	
	if ( !GetStrings( funcStartIter, files,				".ProjectFiles", false ) ||
 		 !GetStrings( funcStartIter, filesToExclude,	".ProjectFilesToExclude", false ) )
	{
		return false;
	}

	// filetypes
	Array< VSProjectFileType > fileTypes;
	const BFFVariable * projectFileTypes = BFFStackFrame::GetVar( ".ProjectFileTypes" );
	if ( projectFileTypes )
	{
		if ( projectFileTypes->IsArrayOfStructs() == false )
		{
			Error::Error_1050_PropertyMustBeOfType( funcStartIter, this, ".ProjectFileTypes", projectFileTypes->GetType(), BFFVariable::VAR_ARRAY_OF_STRUCTS );
			return false;
		}

		const Array< const BFFVariable * > & structs = projectFileTypes->GetArrayOfStructs();
		const BFFVariable * const * end = structs.End();
		for ( const BFFVariable ** it = structs.Begin(); it != end; ++it )
		{
			const BFFVariable * s = *it;

			VSProjectFileType ft;

			// .FileType must be provided
			if ( !GetStringFromStruct( s, ".FileType",	ft.m_FileType ) )
			{
				// TODO:B custom error
				Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".FileType" ) );
				return false;
			}

			// .Pattern must be provided
			if ( !GetStringFromStruct( s, ".Pattern",	ft.m_Pattern ) )
			{
				// TODO:B custom error
				Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".Pattern" ) );
				return false;
			}

			fileTypes.Append( ft );
		}
	}

	// path cleaning
	CleanFolderPaths( inputPaths );			// input paths
	CleanFolderPaths( inputPathsExclude );	// exclude paths
	CleanFilePaths( files );				// explicit files

	// per-config options
	VSProjectConfig baseConfig;

	// various options
	if ( !GetString( funcStartIter, baseConfig.m_BuildCommand,	".ProjectBuildCommand", false ) ||
		 !GetString( funcStartIter, baseConfig.m_RebuildCommand,".ProjectRebuildCommand", false ) ||
		 !GetString( funcStartIter, baseConfig.m_CleanCommand,	".ProjectCleanCommand", false ) ||
		 !GetString( funcStartIter, baseConfig.m_Output,		".Output", false ) ||
		 !GetString( funcStartIter, baseConfig.m_PreprocessorDefinitions,	".PreprocessorDefinitions", false ) ||
		 !GetString( funcStartIter, baseConfig.m_IncludeSearchPath,		".IncludeSearchPath", false ) ||
		 !GetString( funcStartIter, baseConfig.m_ForcedIncludes,		".ForcedIncludes", false ) ||
		 !GetString( funcStartIter, baseConfig.m_AssemblySearchPath,	".AssemblySearchPath", false ) ||
		 !GetString( funcStartIter, baseConfig.m_ForcedUsingAssemblies,	".ForcedUsingAssemblies", false ) ||
		 !GetString( funcStartIter, baseConfig.m_AdditionalOptions,		".AdditionalOptions", false ) ||
		 !GetString( funcStartIter, baseConfig.m_OutputDirectory,		".OutputDirectory", false ) ||
		 !GetString( funcStartIter, baseConfig.m_IntermediateDirectory,	".IntermediateDirectory", false ) ||
		 !GetString( funcStartIter, baseConfig.m_Xbox360DebuggerCommand,".Xbox360DebuggerCommand", false ) ||
		 !GetString( funcStartIter, baseConfig.m_LayoutDir,				".LayoutDir", false ) ||
		 !GetString( funcStartIter, baseConfig.m_LayoutExtensionFilter,	".LayoutExtensionFilter", false ) ||
		 !GetString( funcStartIter, baseConfig.m_DebuggerFlavor,		".DebuggerFlavor", false ) ||
		 !GetString( funcStartIter, baseConfig.m_AumidOverride,			".AumidOverride", false ) ||
		 !GetString( funcStartIter, baseConfig.m_PlatformToolset,		".PlatformToolset", false ) ||
		 !GetString( funcStartIter, baseConfig.m_DeploymentType,		".DeploymentType", false ) ||
		 !GetString( funcStartIter, baseConfig.m_DeploymentFiles,		".DeploymentFiles", false ) ||
		 !GetString( funcStartIter, baseConfig.m_LocalDebuggerCommandArguments,	".LocalDebuggerCommandArguments", false ) ||
		 !GetString( funcStartIter, baseConfig.m_LocalDebuggerWorkingDirectory,	".LocalDebuggerWorkingDirectory", false ) ||
		 !GetString( funcStartIter, baseConfig.m_LocalDebuggerCommand,			".LocalDebuggerCommand", false ) ||
		 !GetString( funcStartIter, baseConfig.m_LocalDebuggerEnvironment,		".LocalDebuggerEnvironment", false ) )
	{
		return false;
	}

	// create configs
	Array< VSProjectConfig > configs( 16, true );

	const BFFVariable * projectConfigs = BFFStackFrame::GetVar( ".ProjectConfigs" );
	if ( projectConfigs )
	{
		if ( projectConfigs->IsArrayOfStructs() == false )
		{
			Error::Error_1050_PropertyMustBeOfType( funcStartIter, this, ".ProjectConfigs", projectConfigs->GetType(), BFFVariable::VAR_ARRAY_OF_STRUCTS );
			return false;
		}

		const Array< const BFFVariable * > & structs = projectConfigs->GetArrayOfStructs();
		const BFFVariable * const * end = structs.End();
		for ( const BFFVariable ** it = structs.Begin(); it != end; ++it )
		{
			const BFFVariable * s = *it;

			// start with the base configuration
			VSProjectConfig newConfig( baseConfig );

			// .Platform must be provided
			if ( !GetStringFromStruct( s, ".Platform",	newConfig.m_Platform ) )
			{
				// TODO:B custom error
				Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".Platform" ) );
				return false;
			}

			// .Config must be provided
			if ( !GetStringFromStruct( s, ".Config",	newConfig.m_Config ) )
			{
				// TODO:B custom error
				Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".Config" ) );
				return false;
			}

			GetStringFromStruct( s, ".ProjectBuildCommand",		newConfig.m_BuildCommand );
			GetStringFromStruct( s, ".ProjectRebuildCommand",	newConfig.m_RebuildCommand );
			GetStringFromStruct( s, ".ProjectCleanCommand",		newConfig.m_CleanCommand );
			GetStringFromStruct( s, ".Output",					newConfig.m_Output );
			GetStringFromStruct( s, ".PreprocessorDefinitions",	newConfig.m_PreprocessorDefinitions );
			GetStringFromStruct( s, ".IncludeSearchPath",		newConfig.m_IncludeSearchPath );
			GetStringFromStruct( s, ".ForcedIncludes",			newConfig.m_ForcedIncludes );
			GetStringFromStruct( s, ".AssemblySearchPath",		newConfig.m_AssemblySearchPath );
			GetStringFromStruct( s, ".ForcedUsingAssemblies",	newConfig.m_ForcedUsingAssemblies );
			GetStringFromStruct( s, ".AdditionalOptions",		newConfig.m_AdditionalOptions );
			GetStringFromStruct( s, ".OutputDirectory",			newConfig.m_OutputDirectory );
			GetStringFromStruct( s, ".IntermediateDirectory",	newConfig.m_IntermediateDirectory );
		 	GetStringFromStruct( s, ".LayoutDir",				newConfig.m_LayoutDir );
			GetStringFromStruct( s, ".LayoutExtensionFilter",	newConfig.m_LayoutExtensionFilter );
			GetStringFromStruct( s, ".Xbox360DebuggerCommand",	newConfig.m_Xbox360DebuggerCommand );
			GetStringFromStruct( s, ".DebuggerFlavor",			newConfig.m_DebuggerFlavor );
			GetStringFromStruct( s, ".AumidOverride",			newConfig.m_AumidOverride );
			GetStringFromStruct( s, ".PlatformToolset",			newConfig.m_PlatformToolset );
			GetStringFromStruct( s, ".DeploymentType",			newConfig.m_DeploymentType );
			GetStringFromStruct( s, ".DeploymentFiles",			newConfig.m_DeploymentFiles );
			GetStringFromStruct( s, ".LocalDebuggerCommandArguments",	newConfig.m_LocalDebuggerCommandArguments );
			GetStringFromStruct( s, ".LocalDebuggerWorkingDirectory",	newConfig.m_LocalDebuggerWorkingDirectory );
			GetStringFromStruct( s, ".LocalDebuggerCommand",			newConfig.m_LocalDebuggerCommand );
			GetStringFromStruct( s, ".LocalDebuggerEnvironment",		newConfig.m_LocalDebuggerEnvironment );

			configs.Append( newConfig );
		}
	}
	else
	{
		// no user specified configs, make some defaults

		// start from the default
		VSProjectConfig config( baseConfig );

		// make the configs
		config.m_Platform	= "Win32";
		config.m_Config		= "Debug";
		configs.Append( config );
		config.m_Config		= "Release";
		configs.Append( config );
		config.m_Platform	= "x64";
		configs.Append( config );
		config.m_Config		= "Debug";
		configs.Append( config );
	}

	NodeGraph & ng = FBuild::Get().GetDependencyGraph();

	// create all of the DirectoryListNodes we need
	Dependencies dirNodes( inputPaths.GetSize() );
	if ( !GetDirectoryListNodeList( funcStartIter, inputPaths, Array< AString >(), Array< AString >(), true, nullptr, "ProjectInputPaths", dirNodes ) )
	{
		return false; // GetDirectoryListNodeList will have emitted an error
	}

	// Check for existing node
	if ( ng.FindNode( projectOutput ) )
	{
		Error::Error_1100_AlreadyDefined( funcStartIter, this, projectOutput );
		return false;
	}

	VCXProjectNode * pn = ng.CreateVCXProjectNode( projectOutput,
												   basePaths,
												   dirNodes,
												   inputPathsExclude, // TODO:B Remove this (handled by DirectoryListNode now)
												   allowedFileExtensions, // TODO:B Remove this (handled by DirectoryListNode now)
												   files,
												   filesToExclude,
												   rootNamespace,
												   projectGuid,
												   defaultLanguage,
												   applicationEnvironment,
												   configs,
												   fileTypes,
												   references,
												   projectReferences );

	ASSERT( pn );

	return ProcessAlias( funcStartIter, pn );
}
/*
 * The routeTcpMessage() receives messages from any TCP connection. The Daemon can be connected with server and deskApp at the same time, but it will know which connection received data.
 * Any message arrive by TCP must to have two parts. The first part defines the data size of the coming package (second part) and must to be an 8 bytes String (always 8 bytes).
 *
 * The algoritm works like this:
 * When some data arrive it verifies (using the hasPackage variable) if is the first part or the second one of the complete message;
 * If hasPackage is true then is especting the second part of the message, otherwise the dada just arrived is the size information.
 *
 * The information of size correspond to the size of the message package. So, when more data arrive it verifies if the size is greater than or equals to the expected size.
 * If true the message is all here and can go on, otherwise the message is coming and it will wait for more data.
 *
 * When all the message arrives it will interpret and route it (by message type) to the right way.
 *
 */
void RFIDMonitorDaemon::routeTcpMessage()
{
    QTcpSocket *connection = (QTcpSocket *) QObject::sender();

    static bool hasPackage = false;
    static quint64 packageSize = 0;

    if( ! hasPackage){

        if((quint64)connection->bytesAvailable() < sizeof(quint64))
            return;

        //    	m_tcpSocket->read((char *)&packageSize, sizeof(quint64));
        QString packageSizeStr(connection->read(sizeof(quint64)));
        packageSize = packageSizeStr.toULongLong();

        qDebug() <<  QString("Message = %1 - Size of coming package: %2").arg(packageSizeStr).arg(QString::number(packageSize));
        hasPackage = true;
    }

    if((quint64)connection->bytesAvailable() >=  packageSize){
        QByteArray data(connection->read(packageSize));

        json::NodeJSMessage nodeMessage;

        nodeMessage.read(QJsonDocument::fromJson(data).object());
        QString messageType(nodeMessage.type());

        qDebug() << QString("New Message Received: %1").arg(QString(data));


        if(messageType == "SYN-ALIVE"){

            tcpSendMessage(connection, buildMessage(m_configManager->identification(), "ACK-ALIVE").toJson());
            qDebug() << QString("New Message Received: %1").arg(messageType);
        }
        else if (messageType == "ACK-SYN") {

            QJsonObject obj(nodeMessage.jsonData());
            if(!obj.isEmpty()){
                m_configManager->setIdentification(obj);
            }

            bool statusDateTime = m_configManager->setDateTime(nodeMessage.dateTime());
            QJsonObject response = m_configManager->identification();
            response["success"] = QJsonValue(statusDateTime);

            tcpSendMessage(connection, buildMessage(response, "ACK").toJson());

            // Informe RFIDMonitor that server is now connected. Wait 2 seconds;
            if(connection->objectName() == "server"){
                isConnected = true;
                QTimer *timer = new QTimer();
                timer->setSingleShot(true);
                timer->setInterval(2000);
                connect(timer, &QTimer::timeout, [=](){
                    ipcSendMessage(buildMessage(QJsonObject(), "SYNC").toJson());
                    timer->deleteLater();
                });
                timer->start();
            }
        }else if (messageType == "GET-CONFIG") {
            tcpSendMessage(connection, buildMessage(m_configManager->currentConfig(), "CONFIG").toJson());

        }else if (messageType == "READER-COMMAND") {

            QJsonObject command(nodeMessage.jsonData());
            /*
             * When a 'reader command' message is received is because someone is sending a command to the reader. So it needs to send also who is doing this.
             * To perform this it uses a field called 'sender' that carry the name of who is sending the 'command message'.
             * And based on that, it will respond to the server connection or to the deskApp connection
             *
             * see reoutIcpMessage (messageType == "READER-RESPONSE")
             */
            if(connection->objectName() == "server")
                command.insert("sender", QString("server"));
            else
                command.insert("sender", QString("app"));

            ipcSendMessage(buildMessage(command, "READER-COMMAND").toJson());

        }else if (messageType == "NEW-CONFIG") {

            QJsonObject newConfig(nodeMessage.jsonData());
            bool ackConf;
            if(m_configManager->newConfig(newConfig))
            {
                // Send a message to stop the RFIDMonitor
                emit restartMonitor();
                ackConf = true;
            }else{
                ackConf = false;
            }
            QJsonObject dataObj;
            dataObj.insert("success", QJsonValue(ackConf));
            tcpSendMessage(connection, buildMessage(dataObj, "ACK-NEW-CONFIG").toJson());

            if(m_tcpAppSocket->isOpen())
                m_tcpAppSocket->close();

        }else if (messageType == "DATETIME") {

            QJsonObject dataObj;
            dataObj["success"] =  QJsonValue(m_configManager->setDateTime(nodeMessage.dateTime()));
            tcpSendMessage(connection, buildMessage(dataObj, "ACK").toJson());

        }else if (messageType == "ACK-DATA") {
            // A ACK-DATA message means that the server is trying to inform the RFIDMonitor that some data is now synced. So, it just send this message to the RFIDMonitor.
            ipcSendMessage(data);

        }else if (messageType == "GET-NET-CONFIG") {
            // Only return the network configuration.
            tcpSendMessage(connection, buildMessage(m_configManager->netConfig(), "NET-CONFIG").toJson());

        }else if (messageType == "NEW-NET") {

            QJsonObject network = nodeMessage.jsonData();
            // Receive a new configuration for the network (ssid and password).
            QJsonObject dataObj;
            dataObj.insert("success", QJsonValue(m_configManager->setNetConfig(network)));

            // returns a message ACK-NET to inform the sender that the new configuration was set
            tcpSendMessage(connection, buildMessage(dataObj, "ACK-NET").toJson());

            // Try to restar the network service to already use the new configuration
            bool resetNet = m_configManager->restartNetwork();
            qDebug() <<  QString(resetNet? "Network restarted" : "Networkt Don't restarted");

        }else if (messageType == "ACK-UNKNOWN") {
            QJsonDocument unknown(nodeMessage.jsonData());
            QJsonObject oldMessage(unknown.object().value("unknownmessage").toObject());
            qDebug() <<  "The server don't understand the message type: " << oldMessage.value("type").toString();
            qDebug() <<  "ERROR message: " << unknown.object().value("errorinfo").toString();

        }else if (messageType == "FULL-READ"){
            ipcSendMessage(data);

        }else{
            /* When receives a message that can't be interpreted like any type is an unknown message.
             * In this case an ACK-UNKNOWN message is built and sent to the connection that received this message
             */
            qDebug() <<  "UNKNOWN MESSAGE";
            QJsonObject unknownObj;
            unknownObj.insert("unknownmessage", QJsonValue(QJsonDocument::fromJson(data).object()));
            unknownObj.insert("errorinfo", QString("Unknown message received"));
            tcpSendMessage(connection, buildMessage(unknownObj, "ACK-UNKNOWN").toJson());
        }

        /* when all the process is done, reset the expecting message size to zero and the haspackage to false.
         * Then when more data arrive it must to be the size information again.
         */
        packageSize = 0;
        hasPackage = false;
    }
}
    Status LegacyReplicationCoordinator::processReplSetReconfig(OperationContext* txn,
                                                                const ReplSetReconfigArgs& args,
                                                                BSONObjBuilder* resultObj) {

        if( args.force && !theReplSet ) {
            _settings.reconfig = args.newConfigObj.getOwned();
            resultObj->append("msg",
                              "will try this config momentarily, try running rs.conf() again in a "
                                      "few seconds");
            return Status::OK();
        }

        // TODO(dannenberg) once reconfig processing has been figured out in the impl, this should
        // be moved out of processReplSetReconfig and into the command body like all other cmds
        Status status = checkReplEnabledForCommand(resultObj);
        if (!status.isOK()) {
            return status;
        }

        if( !args.force && !theReplSet->box.getState().primary() ) {
            return Status(ErrorCodes::NotMaster,
                          "replSetReconfig command must be sent to the current replica set "
                                  "primary.");
        }

        try {
            {
                // just make sure we can get a write lock before doing anything else.  we'll
                // reacquire one later.  of course it could be stuck then, but this check lowers the
                // risk if weird things are up - we probably don't want a change to apply 30 minutes
                // after the initial attempt.
                time_t t = time(0);
                Lock::GlobalWrite lk(txn->lockState());
                if( time(0)-t > 20 ) {
                    return Status(ErrorCodes::ExceededTimeLimit,
                                  "took a long time to get write lock, so not initiating.  "
                                          "Initiate when server less busy?");
                }
            }


            scoped_ptr<ReplSetConfig> newConfig(ReplSetConfig::make(args.newConfigObj, args.force));

            log() << "replSet replSetReconfig config object parses ok, " <<
                    newConfig->members.size() << " members specified" << rsLog;

            Status status = ReplSetConfig::legalChange(theReplSet->getConfig(), *newConfig);
            if (!status.isOK()) {
                return status;
            }

            checkMembersUpForConfigChange(*newConfig, *resultObj, false);

            log() << "replSet replSetReconfig [2]" << rsLog;

            theReplSet->haveNewConfig(txn, *newConfig, true);
            ReplSet::startupStatusMsg.set("replSetReconfig'd");
        }
        catch(const DBException& e) {
            log() << "replSet replSetReconfig exception: " << e.what() << rsLog;
            return e.toStatus();
        }

        resetSlaveCache();
        return Status::OK();
    }
Example #12
0
// Commit
//------------------------------------------------------------------------------
/*virtual*/ bool FunctionSLN::Commit( const BFFIterator & funcStartIter ) const
{
    AStackString<> solutionOutput;
    Array< AString > solutionProjects( 8, true );
    if ( !GetString( funcStartIter, solutionOutput,     ".SolutionOutput", true ) ||
         !GetStrings( funcStartIter, solutionProjects,  ".SolutionProjects", false ) )
    {
        return false;
    }

    // optional inputs
    AString solutionBuildProject;
    AString solutionVisualStudioVersion;
    AString solutionMinimumVisualStudioVersion;
    if ( !GetString( funcStartIter, solutionBuildProject,                 ".SolutionBuildProject", false ) ||
         !GetString( funcStartIter, solutionVisualStudioVersion,          ".SolutionVisualStudioVersion", false ) ||
         !GetString( funcStartIter, solutionMinimumVisualStudioVersion,   ".SolutionMinimumVisualStudioVersion", false ) )
    {
        return false;
    }

    // base config
    VSProjectConfig baseConfig;

    // create configs
    Array< VSProjectConfig > configs( 16, true );

    const BFFVariable * solutionConfigs = BFFStackFrame::GetVar( ".SolutionConfigs" );
    if ( solutionConfigs )
    {
        if ( solutionConfigs->IsArrayOfStructs() == false )
        {
            Error::Error_1050_PropertyMustBeOfType( funcStartIter, this, ".SolutionConfigs", solutionConfigs->GetType(), BFFVariable::VAR_ARRAY_OF_STRUCTS );
            return false;
        }

        const Array< const BFFVariable * > & structs = solutionConfigs->GetArrayOfStructs();
        const BFFVariable * const * end = structs.End();
        for ( const BFFVariable ** it = structs.Begin(); it != end; ++it )
        {
            const BFFVariable * s = *it;

            // start with the base configuration
            VSProjectConfig newConfig( baseConfig );

            // .Platform must be provided
            if ( !GetStringFromStruct( s, ".Platform",  newConfig.m_Platform ) )
            {
                // TODO:B custom error
                Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".Platform" ) );
                return false;
            }

            // .Config must be provided
            if ( !GetStringFromStruct( s, ".Config",    newConfig.m_Config ) )
            {
                // TODO:B custom error
                Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".Config" ) );
                return false;
            }

            configs.Append( newConfig );
        }
    }
    else
    {
        // no user specified configs, make some defaults

        // start from the default
        VSProjectConfig config( baseConfig );

        // make the configs
        config.m_Platform   = "Win32";
        config.m_Config     = "Debug";
        configs.Append( config );
        config.m_Config     = "Release";
        configs.Append( config );
        config.m_Platform   = "x64";
        configs.Append( config );
        config.m_Config     = "Debug";
        configs.Append( config );
    }

    // sort project configs by config and by platform (like visual)
    configs.Sort( VSProjectConfigComp() );

    // create solution folders
    Array< SLNSolutionFolder > folders( 16, true );

    const BFFVariable * solutionFolders = BFFStackFrame::GetVar( ".SolutionFolders" );
    if ( solutionFolders )
    {
        if ( solutionFolders->IsArrayOfStructs() == false )
        {
            Error::Error_1050_PropertyMustBeOfType( funcStartIter, this, ".SolutionFolders", solutionFolders->GetType(), BFFVariable::VAR_ARRAY_OF_STRUCTS );
            return false;
        }

        const Array< const BFFVariable * > & structs = solutionFolders->GetArrayOfStructs();
        const BFFVariable * const * end = structs.End();
        for ( const BFFVariable ** it = structs.Begin(); it != end; ++it )
        {
            const BFFVariable * s = *it;

            // start with the base configuration
            SLNSolutionFolder newFolder;

            // .Path must be provided
            if ( !GetStringFromStruct( s, ".Path", newFolder.m_Path ) )
            {
                // TODO:B custom error
                Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".Path" ) );
                return false;
            }

            newFolder.m_Path.Replace( OTHER_SLASH, NATIVE_SLASH );

            // check if this path was already defined
            {
                const SLNSolutionFolder * const end2 = folders.End();
                for ( const SLNSolutionFolder * it2 = folders.Begin() ; it2 != end2 ; ++it2 )
                {
                    if ( it2->m_Path == newFolder.m_Path  )
                    {
                        // TODO:B custom error
                        Error::Error_1100_AlreadyDefined( funcStartIter, this, it2->m_Path );
                        return false;
                    }
                }
            }

            // .Projects must be provided
            if ( !GetStringOrArrayOfStringsFromStruct( funcStartIter, s, ".Projects", newFolder.m_ProjectNames ) )
            {
                return false; // GetStringOrArrayOfStringsFromStruct has emitted an error
            }

            // check if this project is included in the solution
            for ( const AString & projectName : newFolder.m_ProjectNames )
            {
                if ( solutionProjects.Find( projectName ) == nullptr )
                {
					solutionProjects.Append( projectName );
                }
            }

            folders.Append( newFolder );
        }
    }

    NodeGraph & ng = FBuild::Get().GetDependencyGraph();

    // Check for existing node
    if ( ng.FindNode( solutionOutput ) )
    {
        Error::Error_1100_AlreadyDefined( funcStartIter, this, solutionOutput );
        return false;
    }

    // resolves VCXProject nodes associated to solutionProjects
    Array< VCXProjectNode * > projects( solutionProjects.GetSize(), false );
    {
        const AString * const end = solutionProjects.End();
        for ( const AString * it = solutionProjects.Begin(); it != end; ++it )
        {
            VCXProjectNode * project = ResolveVCXProject( funcStartIter, *it );
            if ( project == nullptr )
            {
                return false; // ResolveVCXProject will have emitted error
            }

            // check that this project contains all .SolutionConfigs
            const Array< VSProjectConfig > & projectConfigs = project->GetConfigs();

            const size_t configsSize = configs.GetSize();
            for ( size_t i = 0 ; i < configsSize ; ++i )
            {
                bool containsConfig = false;

                const VSProjectConfig * const config = &configs[i];
                const VSProjectConfig * const end2 = projectConfigs.End();
                for ( const VSProjectConfig * it2 = projectConfigs.Begin(); it2 != end2; ++it2 )
                {
                    if ( it2->m_Platform == config->m_Platform &&
                         it2->m_Config   == config->m_Config )
                    {
                        containsConfig = true;
                        break;
                    }
                }

                if ( containsConfig == false )
                {
                    // TODO: specific error message "ProjectConfigNotFound"
                    AStackString<> configName;
                    configName.Format( "%s|%s", config->m_Platform.Get(), config->m_Config.Get() );
                    Error::Error_1104_TargetNotDefined( funcStartIter, this, configName.Get(), project->GetName() );
                    return false;
                }
            }

            // append vcxproject node to solution
            projects.Append( project );
        }
    }

    // sort projects by name (like visual)
    projects.Sort( VCXProjectNodeComp() );

    // resolves VCXProject nodes associated to solutionFolders
    {
        SLNSolutionFolder * const end = folders.End();
        for ( SLNSolutionFolder * it = folders.Begin(); it != end; ++it )
        {
            // retrieves full path of contained vcxprojects

            AString * const end2 = it->m_ProjectNames.End();
            for ( AString * it2 = it->m_ProjectNames.Begin(); it2 != end2; ++it2 )
            {
				// Get associate project file
				VCXProjectNode * project = ResolveVCXProject( funcStartIter, *it2 );
				if ( project == nullptr )
				{
					return false; // ResolveVCXProjectRecurse will have emitted error
				}

                ASSERT( projects.Find( project ) ); // Sanity check in global list

				// fixup name to be to final project
                *it2 = project->GetName();
            }
        }
    }

    // resolves VCXProject node referenced by solutionBuildProject
    if ( solutionBuildProject.GetLength() > 0 )
    {
		// Get associate project file
		const VCXProjectNode * project = ResolveVCXProject( funcStartIter, solutionBuildProject );
		if ( project == nullptr )
		{
			return false; // ResolveVCXProject will have emitted error
		}

        if ( projects.Find( project ) == nullptr )
        {
            // project referenced in .SolutionBuildProject is not referenced in .SolutionProjects
            Error::Error_1104_TargetNotDefined( funcStartIter, this, ".SolutionBuildProject", project->GetName() );
            return false;
        }

        solutionBuildProject = project->GetName();
    }

    // Project Dependencies
    Array< SLNDependency > slnDeps( 0, true );
    const BFFVariable * projectDepsVar = BFFStackFrame::GetVar( ".SolutionDependencies" );
    if ( projectDepsVar )
    {
        if ( projectDepsVar->IsArrayOfStructs() == false )
        {
            Error::Error_1050_PropertyMustBeOfType( funcStartIter, this, ".SolutionDependencies", projectDepsVar->GetType(), BFFVariable::VAR_ARRAY_OF_STRUCTS );
            return false;
        }
	
		slnDeps.SetCapacity( projectDepsVar->GetArrayOfStructs().GetSize() );
		for ( const BFFVariable * s : projectDepsVar->GetArrayOfStructs() )
		{
            // .Projects must be provided
            // .Dependencies must be provided
			SLNDependency deps;
            if ( !GetStringOrArrayOfStringsFromStruct( funcStartIter, s, ".Projects", deps.m_Projects ) ||
				 !GetStringOrArrayOfStringsFromStruct( funcStartIter, s, ".Dependencies", deps.m_Dependencies ) )
            {
                return false; // GetStringOrArrayOfStringsFromStruct has emitted an error
            }

			// fixup
			for ( AString & projectName : deps.m_Projects )
			{
				// Get associated project file
				const VCXProjectNode * project = ResolveVCXProject( funcStartIter, projectName );
				if ( project == nullptr )
				{
					return false; // ResolveVCXProject will have emitted error
				}
				projectName = project->GetName();
			}
			for ( AString & projectName : deps.m_Dependencies )
			{
				// Get associated project file
				const VCXProjectNode * project = ResolveVCXProject( funcStartIter, projectName );
				if ( project == nullptr )
				{
					return false; // ResolveVCXProject will have emitted error
				}
				projectName = project->GetName();
			}

			slnDeps.Append( deps );
		}
	}

    SLNNode * sln = ng.CreateSLNNode(   solutionOutput,
                                        solutionBuildProject,
                                        solutionVisualStudioVersion,
                                        solutionMinimumVisualStudioVersion,
                                        configs,
                                        projects,
										slnDeps,
                                        folders );

    ASSERT( sln );

    return ProcessAlias( funcStartIter, sln );
}
Example #13
0
void ZDLInterface::startRead(){
	emit readChildren(this);
	newConfig();
}
Example #14
0
std::pair<double, Util::gridconfig_t> GridFitter::GradientDescent::step(candidate_set &bestGrids, Util::gridconfig_t const& config, double error, const GridFitter::GradientDescent::StepParameter param)
{
	// when adjusting one of the position parameters, we can not adjust the step
	// size based on the difference between of the errors and the learning rate
	// (because the coordinates are discrete values).
	// instead, in each step we only change the position by either 1 or -1.
	// furthermore, if the error does not improve after a position change,
	// instead of just applying the reverse direction, we check if the error
	// acutally improves when going in the reverse direction.

	static const std::array<int, 2> directions {-1, 1};

	const double alpha     = _settings.alpha;
	const double eps_scale = _settings.eps_scale;
	const int eps_pos      = _settings.eps_pos;
	const double eps_angle = _settings.eps_angle;

	for (int direction : directions) {
		Util::gridconfig_t newConfig(config);
		// adjust parameter
		switch (param) {
		case SCALE:
			newConfig.radius = newConfig.radius + direction * eps_scale;
			break;
		case POSX:
			newConfig.center = newConfig.center + cv::Point2i(direction * eps_pos, 0);
			break;
		case POSY:
			newConfig.center = newConfig.center + cv::Point2i(0, direction * eps_pos);
			break;
		case ANGLE_X:
			newConfig.angle_x = newConfig.angle_x + direction * eps_angle;
			break;
		case ANGLE_Y:
			newConfig.angle_y = newConfig.angle_y + direction * eps_angle;
			break;
		case ANGLE_Z:
			newConfig.angle_z = newConfig.angle_z + direction * eps_angle;
			break;
		default:
			assert(false);
			break;
		}

		// TODO: don't construct new Grid in each step
		PipelineGrid newGrid(newConfig);
		double newError = evaluateCandidate(newGrid, _roi, _binarizedRoi, _edgeRoiX, _edgeRoiY, _settings);

		// adjust parameter based on learning rate and new error
		if (param != POSX && param != POSY) {
			switch (param) {
			case SCALE:
				newConfig.radius = config.radius + direction * alpha * (error - newError);
				break;
			case ANGLE_X:
				newConfig.angle_x = config.angle_x + direction * alpha * (error - newError);
				break;
			case ANGLE_Y:
				newConfig.angle_y = config.angle_y + direction * alpha * (error - newError);
				break;
			case ANGLE_Z:
				newConfig.angle_z = config.angle_z + direction * alpha * (error - newError);
				break;
			default:
				break;
			}

			PipelineGrid newGrid(newConfig);
			newError = evaluateCandidate(newGrid, _roi, _binarizedRoi, _edgeRoiX, _edgeRoiY, _settings);

			bestGrids.insert({newError, newConfig});
			return {newError, newConfig};
		} else if (newError < error) {
			bestGrids.insert({newError, newConfig});
			return {newError, newConfig};
		}
	}
	return {error, config};
}