コード例 #1
0
ファイル: setting.cpp プロジェクト: Berlizov/3Deditor
Setting::Setting(QWidget *parent) :
    QWidget(parent)
{
    QGridLayout *layout=new QGridLayout;
    int line=0;

    layout->addWidget(new QLabel("File Open"),line,0,1,1);
    ios=new QCheckBox("iOS");
    layout->addWidget(ios,line,1,1,1);
    line++;

    fileAdress=new QLineEdit;
    layout->addWidget(fileAdress,line,0,1,1);
    QPushButton *browse=new QPushButton("Browse");
    connect(browse,SIGNAL(clicked()),SLOT(getFilePath()));
    layout->addWidget(browse,line,1,1,1);
    line++;

    browse=new QPushButton("Start Server");
    browse->setEnabled(NO);
    layout->addWidget(browse,line,0,1,2);
    line++;

    QFrame* separator = new QFrame();
    separator->setFrameStyle(QFrame::HLine);
    layout->addWidget(separator,line,0,1,2);
    line++;

    layout->addWidget(new QLabel("Settings"),line,0,1,2);
    line++;

    layout->addWidget(new QLabel("Count of calibration frames"),line,0,1,1);
    framesCouns=new QSpinBox();
    framesCouns->setValue(3);
    layout->addWidget(framesCouns,line,1,1,1);
    line++;

    layout->addWidget(new QLabel("Low-pass filter"),line,0,1,1);
    lowPass=new QDoubleSpinBox();
    lowPass->setSingleStep(0.01);
    layout->addWidget(lowPass,line,1,1,1);
    line++;

    layout->addWidget(new QLabel("Linear filter"),line,0,1,1);
    QSpinBox *linFrame=new QSpinBox();
    linFrame->setEnabled(NO);
    layout->addWidget(linFrame,line,1,1,1);
    line++;

    layout->addWidget(new QLabel("Giro"),line,0,1,1);
    gyro=new QCheckBox();
    gyro->setEnabled(NO);
    connect(ios,SIGNAL(stateChanged(int)),SLOT(hasGiro()));
    layout->addWidget(gyro,line,1,1,1);
    line++;

    QPushButton* start=new QPushButton("Start");
    connect(start,SIGNAL(clicked()),SLOT(start()));
    layout->addWidget(start,line,0,1,2);
    line++;

    setLayout(layout);
    setWindowTitle("Settings");
    setMinimumSize(300,300);
}
コード例 #2
0
ファイル: scriptmanager.cpp プロジェクト: 081421/otxserver
bool ScriptManager::loadFromXml(const std::string& file, bool& enabled)
{
	enabled = false;
	xmlDocPtr doc = xmlParseFile(getFilePath(FILE_TYPE_MOD, file).c_str());
	if(!doc)
	{
		std::clog << "[Error - ScriptManager::loadFromXml] Cannot load mod " << file << std::endl;
		std::clog << getLastXMLError() << std::endl;
		return false;
	}

	int32_t intValue;
	std::string strValue;

	xmlNodePtr p, root = xmlDocGetRootElement(doc);
	if(xmlStrcmp(root->name,(const xmlChar*)"mod"))
	{
		std::clog << "[Error - ScriptManager::loadFromXml] Malformed mod " << file << std::endl;
		std::clog << getLastXMLError() << std::endl;

		xmlFreeDoc(doc);
		return false;
	}

	if(!readXMLString(root, "name", strValue))
		strValue = file;

	ModBlock mod;
	mod.enabled = true;
	mod.name = strValue;
	if(readXMLString(root, "enabled", strValue) && !booleanString(strValue))
		mod.enabled = false;

	mod.file = file;
	if(readXMLString(root, "author", strValue))
		mod.author = strValue;

	if(readXMLString(root, "version", strValue))
		mod.version = strValue;

	if(readXMLString(root, "contact", strValue))
		mod.contact = strValue;

	bool supported = true;
	for(p = root->children; p; p = p->next)
	{
		if(xmlStrcmp(p->name, (const xmlChar*)"server"))
			continue;

		supported = false;
		for(xmlNodePtr versionNode = p->children; versionNode; versionNode = versionNode->next)
		{
			std::string id = SOFTWARE_VERSION;
			if(readXMLString(versionNode, "id", strValue))
				id = asLowerCaseString(strValue);

			IntegerVec protocol;
			protocol.push_back(CLIENT_VERSION_MIN);
			if(readXMLString(versionNode, "protocol", strValue))
				protocol = vectorAtoi(explodeString(strValue, "-"));

			int16_t database = VERSION_DATABASE;
			if(readXMLInteger(versionNode, "database", intValue))
				database = intValue;

			if(id == asLowerCaseString(SOFTWARE_VERSION) && database >= VERSION_DATABASE
				&& protocol[0] >= CLIENT_VERSION_MIN && (protocol.size() < 2 || protocol[1] <= CLIENT_VERSION_MAX))
			{
				supported = true;
				break;
			}
		}
	}

	if(!supported)
	{
		std::clog << "[Warning - ScriptManager::loadFromXml] Your server is not supported by mod " << file << std::endl;
		xmlFreeDoc(doc);
		return false;
	}

	if(mod.enabled)
	{
		std::string scriptsPath = getFilePath(FILE_TYPE_MOD, "scripts/");
		for(p = root->children; p; p = p->next)
		{
			if(!xmlStrcmp(p->name, (const xmlChar*)"quest"))
				Quests::getInstance()->parseQuestNode(p, modsLoaded);
			else if(!xmlStrcmp(p->name, (const xmlChar*)"outfit"))
				Outfits::getInstance()->parseOutfitNode(p);
			else if(!xmlStrcmp(p->name, (const xmlChar*)"vocation"))
				Vocations::getInstance()->parseVocationNode(p); //duplicates checking is dangerous, shouldn't be performed until we find some good solution
			else if(!xmlStrcmp(p->name, (const xmlChar*)"group"))
				Groups::getInstance()->parseGroupNode(p); //duplicates checking is dangerous, shouldn't be performed until we find some good solution
			else if(!xmlStrcmp(p->name, (const xmlChar*)"raid"))
				Raids::getInstance()->parseRaidNode(p, modsLoaded, FILE_TYPE_MOD); //TODO: support mods path
			else if(!xmlStrcmp(p->name, (const xmlChar*)"spawn"))
				Spawns::getInstance()->parseSpawnNode(p, modsLoaded);
			else if(!xmlStrcmp(p->name, (const xmlChar*)"channel"))
				g_chat.parseChannelNode(p); //TODO: duplicates- channel destructor needs to send closeChannel to users!
			else if(!xmlStrcmp(p->name, (const xmlChar*)"npc"))
				g_npcs.parseNpcNode(p, FILE_TYPE_MOD);
			else if(!xmlStrcmp(p->name, (const xmlChar*)"monster"))
			{
				std::string path, name;
				if((readXMLString(p, "file", path) || readXMLString(p, "path", path)) && readXMLString(p, "name", name))
					g_monsters.loadMonster(getFilePath(FILE_TYPE_MOD, "monster/" + path), name, true);
			}
			else if(!xmlStrcmp(p->name, (const xmlChar*)"item"))
			{
				if(readXMLInteger(p, "id", intValue))
					Item::items.parseItemNode(p, intValue);
			}
			if(!xmlStrcmp(p->name, (const xmlChar*)"description") || !xmlStrcmp(p->name, (const xmlChar*)"info"))
			{
				if(parseXMLContentString(p->children, strValue))
				{
					replaceString(strValue, "\t", "");
					mod.description = strValue;
				}
			}
			else if(!xmlStrcmp(p->name, (const xmlChar*)"lib") || !xmlStrcmp(p->name, (const xmlChar*)"config"))
			{
				if(!readXMLString(p, "name", strValue))
				{
					if(!xmlStrcmp(p->name, (const xmlChar*)"lib"))
						strValue = mod.name + "-lib";
					else if(!xmlStrcmp(p->name, (const xmlChar*)"config"))
						strValue = mod.name + "-config";
				}
				else
					toLowerCaseString(strValue);

				std::string strLib;
				if(parseXMLContentString(p->children, strLib))
				{
					LibMap::iterator it = libMap.find(strValue);
					if(it == libMap.end())
					{
						LibBlock lb;
						lb.first = file;
						lb.second = strLib;

						libMap[strValue] = lb;
					}
					else
						std::clog << "[Warning - ScriptManager::loadFromXml] Duplicated lib in mod "
							<< strValue << ", previously declared in " << it->second.first << std::endl;
				}
			}
			else if(!g_actions->parseEventNode(p, scriptsPath, modsLoaded))
			{
				if(!g_talkActions->parseEventNode(p, scriptsPath, modsLoaded))
				{
					if(!g_moveEvents->parseEventNode(p, scriptsPath, modsLoaded))
					{
						if(!g_creatureEvents->parseEventNode(p, scriptsPath, modsLoaded))
						{
							if(!g_globalEvents->parseEventNode(p, scriptsPath, modsLoaded))
							{
								if(!g_spells->parseEventNode(p, scriptsPath, modsLoaded))
									g_weapons->parseEventNode(p, scriptsPath, modsLoaded);
							}
						}
					}
				}
			}
		}
	}

	enabled = mod.enabled;
	modMap[mod.name] = mod;

	xmlFreeDoc(doc);
	return true;
}
コード例 #3
0
ファイル: otserv.cpp プロジェクト: novasdream/OpenTibia-EPVP
int main(int argc, char *argv[])
{
	StringVec args = StringVec(argv, argv + argc);
	if(argc > 1 && !argumentsHandler(args))
		return 0;

#else
void serverMain(void* param)
{
	std::cout.rdbuf(&g_logger);
	std::cerr.rdbuf(&g_logger);

#endif
	std::set_new_handler(allocationHandler);
	ServiceManager servicer;
	g_config.startup();

	#ifdef __OTSERV_ALLOCATOR_STATS__
	boost::thread(boost::bind(&allocatorStatsThread, (void*)NULL));
	// TODO: destruct this thread...
	#endif
	#ifdef __EXCEPTION_TRACER__
	ExceptionHandler mainExceptionHandler;
	mainExceptionHandler.InstallHandler();
	#endif
	#ifndef WINDOWS

	// ignore sigpipe...
	struct sigaction sigh;
	sigh.sa_handler = SIG_IGN;
	sigh.sa_flags = 0;
	sigemptyset(&sigh.sa_mask);
	sigaction(SIGPIPE, &sigh, NULL);

	// register signals
	signal(SIGHUP, signalHandler); //save
	signal(SIGTRAP, signalHandler); //clean
	signal(SIGCHLD, signalHandler); //refresh
	signal(SIGUSR1, signalHandler); //close server
	signal(SIGUSR2, signalHandler); //open server
	signal(SIGCONT, signalHandler); //reload all
	signal(SIGQUIT, signalHandler); //save & shutdown
	signal(SIGTERM, signalHandler); //shutdown
	#endif

	Dispatcher::getInstance().addTask(createTask(boost::bind(otserv,
	#if !defined(WINDOWS) || defined(__CONSOLE__)
	args,
	#endif
	&servicer)));
	g_loaderSignal.wait(g_loaderUniqueLock);

	#if !defined(WINDOWS) || defined(__CONSOLE__)
	std::string outPath = g_config.getString(ConfigManager::OUT_LOG), errPath = g_config.getString(ConfigManager::ERROR_LOG);
	if(outPath.length() < 3)
		outPath = "";
	else if(outPath[0] != '/' && outPath[1] != ':')
	{
		outPath = getFilePath(FILE_TYPE_LOG, outPath);
		std::cout << "> Logging output to file: " << outPath << std::endl;
	}

	if(errPath.length() < 3)
		errPath = "";
	else if(errPath[0] != '/' && errPath[1] != ':')
	{
		errPath = getFilePath(FILE_TYPE_LOG, errPath);
		std::cout << "> Logging errors to file: " << errPath << std::endl;
	}

	if(outPath != "")
	{
		boost::shared_ptr<std::ofstream> outFile;
		outFile.reset(new std::ofstream(outPath.c_str(), (g_config.getBool(ConfigManager::TRUNCATE_LOGS) ?
			std::ios::trunc : std::ios::app) | std::ios::out));
		if(!outFile->is_open())
			startupErrorMessage("Could not open output log file for writing!");

		std::cout.rdbuf(outFile->rdbuf());
	}

	if(errPath != "")
	{
		boost::shared_ptr<std::ofstream> errFile;
		errFile.reset(new std::ofstream(errPath.c_str(), (g_config.getBool(ConfigManager::TRUNCATE_LOGS) ?
			std::ios::trunc : std::ios::app) | std::ios::out));
		if(!errFile->is_open())
			startupErrorMessage("Could not open error log file for writing!");

		std::cerr.rdbuf(errFile->rdbuf());
	}
	#endif

	if(servicer.isRunning())
	{
		std::cout << ">> " << g_config.getString(ConfigManager::SERVER_NAME) << " server Online!" << std::endl << std::endl;
		#if defined(WINDOWS) && !defined(__CONSOLE__)
		SendMessage(GUI::getInstance()->m_statusBar, WM_SETTEXT, 0, (LPARAM)">> Status: Online!");
		GUI::getInstance()->m_connections = true;
		#endif
		servicer.run();
	}
	else
	{
		std::cout << ">> " << g_config.getString(ConfigManager::SERVER_NAME) << " server Offline! No services available..." << std::endl << std::endl;
		#if defined(WINDOWS) && !defined(__CONSOLE__)
		SendMessage(GUI::getInstance()->m_statusBar, WM_SETTEXT, 0, (LPARAM)">> Status: Offline!");
		GUI::getInstance()->m_connections = true;
		#endif
	}

#ifdef __EXCEPTION_TRACER__
	mainExceptionHandler.RemoveHandler();
#endif
#if !defined(WINDOWS) || defined(__CONSOLE__)
	return 0;
#endif
}
コード例 #4
0
ファイル: theme_loader.cpp プロジェクト: AsamQi/vlc
bool ThemeLoader::extract( const string &fileName )
{
    bool result = true;
    char *tmpdir = tempnam( NULL, "vlt" );
    string tempPath = sFromLocale( tmpdir );
    free( tmpdir );

    // Extract the file in a temporary directory
    if( ! extractTarGz( fileName, tempPath ) &&
        ! extractZip( fileName, tempPath ) )
    {
        deleteTempFiles( tempPath );
        return false;
    }

    string path;
    string xmlFile;
    OSFactory *pOsFactory = OSFactory::instance( getIntf() );
    // Find the XML file in the theme
    if( findFile( tempPath, DEFAULT_XML_FILE, xmlFile ) )
    {
        path = getFilePath( xmlFile );
    }
    else
    {
        // No XML file, check if it is a winamp2 skin
        string mainBmp;
        if( findFile( tempPath, "main.bmp", mainBmp ) )
        {
            msg_Dbg( getIntf(), "trying to load a winamp2 skin" );
            path = getFilePath( mainBmp );

            // Look for winamp2.xml in the resource path
            list<string> resPath = pOsFactory->getResourcePath();
            list<string>::const_iterator it;
            for( it = resPath.begin(); it != resPath.end(); ++it )
            {
                if( findFile( *it, WINAMP2_XML_FILE, xmlFile ) )
                    break;
            }
        }
    }

    if( !xmlFile.empty() )
    {
        // Parse the XML file
        if (! parse( path, xmlFile ) )
        {
            msg_Err( getIntf(), "error while parsing %s", xmlFile.c_str() );
            result = false;
        }
    }
    else
    {
        msg_Err( getIntf(), "no XML found in theme %s", fileName.c_str() );
        result = false;
    }

    // Clean-up
    deleteTempFiles( tempPath );
    return result;
}
コード例 #5
0
ファイル: raids.cpp プロジェクト: milbradt/TFS
bool Raids::parseRaidNode(xmlNodePtr raidNode, bool checkDuplicate, FileType_t pathing)
{
	if(xmlStrcmp(raidNode->name, (const xmlChar*)"raid"))
		return false;

	int32_t intValue;
	std::string strValue;
	if(!readXMLString(raidNode, "name", strValue))
	{
		std::clog << "[Error - Raids::parseRaidNode] name tag missing for raid." << std::endl;
		return false;
	}

	std::string name = strValue;
	if(!readXMLInteger(raidNode, "interval2", intValue) || intValue <= 0)
	{
		std::clog << "[Error - Raids::parseRaidNode] interval2 tag missing or divided by 0 for raid " << name << std::endl;
		return false;
	}

	uint32_t interval = intValue * 60;
	std::string file;
	if(!readXMLString(raidNode, "file", strValue))
	{
		file = name + ".xml";
		std::clog << "[Warning - Raids::parseRaidNode] file tag missing for raid " << name << ", using default: " << file << std::endl;
	}
	else
		file = strValue;

	file = getFilePath(pathing, "raids/" + file);
	uint64_t margin = 0;
	if(!readXMLInteger(raidNode, "margin", intValue))
		std::clog << "[Warning - Raids::parseRaidNode] margin tag missing for raid " << name << ", using default: " << margin << std::endl;
	else
		margin = intValue * 60 * 1000;

	RefType_t refType = REF_NONE;
	if(readXMLString(raidNode, "reftype", strValue) || readXMLString(raidNode, "refType", strValue))
	{
		std::string tmpStrValue = asLowerCaseString(strValue);
		if(tmpStrValue == "single")
			refType = REF_SINGLE;
		else if(tmpStrValue == "block")
			refType = REF_BLOCK;
		else if(tmpStrValue != "none")
			std::clog << "[Warning - Raids::parseRaidNode] Unknown reftype \"" << strValue << "\" for raid " << name << std::endl;
	}

	bool ref = false;
	if(readXMLString(raidNode, "ref", strValue))
		ref = booleanString(strValue);

	bool enabled = true;
	if(readXMLString(raidNode, "enabled", strValue))
		enabled = booleanString(strValue);

	Raid* raid = new Raid(name, interval, margin, refType, ref, enabled);
	if(!raid || !raid->loadFromXml(file))
	{
		delete raid;
		std::clog << "[Fatal - Raids::parseRaidNode] failed to load raid " << name << std::endl;
		return false;
	}

	if(checkDuplicate)
	{
		for(RaidList::iterator it = raidList.begin(); it != raidList.end(); ++it)
		{
			if((*it)->getName() == name)
				delete *it;
		}
	}

	raidList.push_back(raid);
	return true;
}
コード例 #6
0
int stmd_LogonSelect(int time_type, char *table_type)
{
    char        condBuf[4096], tmpBuf[1024];
    int         sts_code;
    char        str_time[10];
    int         select_cnt = 0, snd_cnt = 0;

    char        query[4096];
    MYSQL_RES   *result;
    MYSQL_ROW   row;

    time_t      now;
    char        tm[DIR_NUM][8];
    char        path[60];
    char        fileName[60];
    FILE        *fp;

    int         i, j, row_index, realSysCnt = 2, realItemCnt = 0;
    char title[7][16]={"SYSTEM", "SM_CH_ID", "LOG_MOD", "LOG_REQ", "LOG_SUCC","LOG_FAIL","SUCC_RATE"}; //uamyd 20110515 succrate_added
	char title1[5][16]={"", "HBIT_0","HBIT_1","HBIT_2", "HBIT_3"}; 
	char title2[5][16]={"", "HBIT_4","HBIT_5","HBIT_6", "HBIT_7"};
	char title3[5][16]={"", "HBIT_8","HBIT_9","HBIT_10", "HBIT_11"};
	char title4[5][16]={"", "HBIT_12","HBIT_13","HBIT_14", "HBIT_15"};
	char title5[5][16]={"", "HBIT_16","HBIT_17","HBIT_18", "HBIT_19"};
	char title6[5][16]={"", "HBIT_20","HBIT_21","HBIT_22", "HBIT_23"};
	char title7[5][16]={"", "HBIT_24","HBIT_25","HBIT_26", "HBIT_27"};
	char title8[5][16]={"", "HBIT_28","HBIT_29","HBIT_30", "HBIT_31"};
	char title10[5][16]={"", "SM_INT_ERR","OP_ERR","OP_TIMEOUT", "ETC_FAIL"};
	char title11[3][16]={"", "API_REQ_ERR","API_TIMEOUT"};
    char SysName[2][8] = {"SCMA","SCMB"};

    now = time(0);
    if(time_type != STMD_WEEK)
        now = now - (printTIME[time_type]*60) - STAT_OFFSET_UNIT;
    else
        now = now - (printTIME[time_type]*60);

    getFilePath (path, tm, &now); // ~/LOG/STAT 까지 만든다.
    makeDirectory (time_type,path,tm);

    sprintf(fileName, "%s", path );
    makeFileName ( fileName, STMD_LOGON, time_type, tm );

    if ( ( fp = fopen(fileName, APPEND ) ) == NULL ){
        sprintf(trcBuf, "%s Open Fail\n", fileName);
        trclib_writeLog(FL, trcBuf);
        return -1;
    }


    switch (time_type) {
        case    STMD_HOUR :
            sts_code = STSCODE_STM_PERIODIC_LOGON_HOUR;
            sprintf (str_time, "%s", STMD_STR_HOUR);
            break;
        case    STMD_DAY :
            sts_code = STSCODE_STM_PERIODIC_LOGON_DAY;
            sprintf (str_time, "%s", STMD_STR_DAY);
            break;
        case    STMD_WEEK :
            sts_code = STSCODE_STM_PERIODIC_LOGON_WEEK;
            sprintf (str_time, "%s", STMD_STR_WEEK);
            break;
        case    STMD_MONTH :
            sts_code = STSCODE_STM_PERIODIC_LOGON_MONTH;
            sprintf (str_time, "%s", STMD_STR_MONTH);
            break;
    }

    sprintf(condBuf,"    %s %s\n    S%04d LOGON PERIODIC STATISTICS MESSAGE\n",
        "SCM", // 현재는 OMP로 고정하지만 실질적인 시스템 이름으로 변경 필요 hslim_oper
        commlib_printTStamp(), // 현재시각 time stamp (년,월,일,시,분,초,요일)
        sts_code);

    sprintf(tmpBuf, "    PERIOD = %s\n    MEASURETIME = %s  -  %s\n\n",
        str_time,
        get_period_start_time(time_type), get_period_end_time(time_type));
    strcat(condBuf,tmpBuf);

    sprintf(tmpBuf, "    ====================================================================\n");
    strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %8s %12s %12s\n","",title[0],title[1],title[2] );
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n","","",title[3],title[4],title[5],title[6] ); //uamyd 20110515 succrate_added
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n", "","", title1[1], title1[2],title1[3],title1[4]);
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n", "","", title2[1], title2[2],title2[3],title2[4]);
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n", "","", title3[1], title3[2],title3[3],title3[4]);
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n", "","", title4[1], title4[2],title4[3],title4[4]);
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n", "","", title5[1], title5[2],title5[3],title5[4]);
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n", "","", title6[1], title6[2],title6[3],title6[4]);
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n", "","", title7[1], title7[2],title7[3],title7[4]);
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n", "","", title8[1], title8[2],title8[3],title8[4]);
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n", "","", title10[1], title10[2],title10[3],title10[4]);
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %8s %12s %12s\n", "","", title11[1], title11[2]);
	strcat(condBuf, tmpBuf);
    sprintf(tmpBuf, "    ====================================================================\n");
    strcat(condBuf, tmpBuf);

    for(i = 0; i < realSysCnt; i++)
	{
		realItemCnt = 1;

	   	sprintf(query, "SELECT system_name, sm_ch_id, log_mod, "
				" ifnull(sum(log_req), 0), ifnull(sum(log_succ), 0), ifnull(sum(log_fail), 0), "
				" ifnull(sum(HBIT_0), 0), ifnull(sum(HBIT_1), 0), ifnull(sum(HBIT_2), 0), "
				" ifnull(sum(HBIT_3), 0),  "
				" ifnull(sum(HBIT_4), 0), ifnull(sum(HBIT_5), 0), ifnull(sum(HBIT_6), 0), "
				" ifnull(sum(HBIT_7), 0),  "
				" ifnull(sum(HBIT_8), 0), ifnull(sum(HBIT_9), 0), ifnull(sum(HBIT_10), 0), "
				" ifnull(sum(HBIT_11), 0),  "
				" ifnull(sum(HBIT_12), 0), ifnull(sum(HBIT_13), 0), ifnull(sum(HBIT_14), 0), "
				" ifnull(sum(HBIT_15), 0),  "
				" ifnull(sum(HBIT_16), 0), ifnull(sum(HBIT_17), 0), ifnull(sum(HBIT_18), 0), "
				" ifnull(sum(HBIT_19), 0),  "
				" ifnull(sum(HBIT_20), 0), ifnull(sum(HBIT_21), 0), ifnull(sum(HBIT_22), 0), "
				" ifnull(sum(HBIT_23), 0),  "
				" ifnull(sum(HBIT_24), 0), ifnull(sum(HBIT_25), 0), ifnull(sum(HBIT_26), 0), "
				" ifnull(sum(HBIT_27), 0),  "
				" ifnull(sum(HBIT_28), 0), ifnull(sum(HBIT_29), 0), ifnull(sum(HBIT_30), 0), "
				" ifnull(sum(HBIT_31), 0),  "
				" ifnull(sum(sm_int_err),0), ifnull(sum(op_err),0), ifnull(sum(op_timeout),0), "
				" ifnull(sum(etc_fail),0), "
				" ifnull(sum(api_req_err),0), ifnull(sum(api_timeout),0) "
			   " from %s "
			   " where system_name = '%s' AND (stat_date = '%s') "
			   " group by system_name, sm_ch_id, log_mod ",
			   table_type, SysName[i], get_period_select_time(time_type));

        if ( trcLogFlag == TRCLEVEL_SQL ) {
            sprintf(trcBuf, "query = %s\n", query);
            trclib_writeLog(FL, trcBuf);
        }
		if (stmd_mysql_query (query) < 0) {
            sprintf(trcBuf,">>> mysql_query fail; err=%s\n", mysql_error(conn));
            trclib_writeLogErr (FL,trcBuf);
            if(fp != NULL) fclose(fp);
            return -1;
        }

        select_cnt = 0;
        result = mysql_store_result(conn);

		if(strlen(condBuf)) {
			stmd_txMsg2Cond(condBuf, (sts_code - STSCODE_TO_MSGID_STATISTICS), 1, snd_cnt++);
			fprintf (fp, "%s",condBuf);
			memset(condBuf, 0x00, sizeof(condBuf));
		}

        while((row = mysql_fetch_row(result)) != NULL) 
		{
			row_index = 1;
			if (select_cnt == 0)
			{
				sprintf(tmpBuf, "%3s %8s SM_CH%7s %12s\n",
						"",SysName[i],row[row_index],!atoi(row[row_index+1])?"LOG_ON":"LOG_OUT");
				strcat(condBuf, tmpBuf);
			} 
			else 
			{
				sprintf(tmpBuf, "%3s %8s SM_CH%7s %12s\n",
						"","",row[row_index],!atoi(row[row_index+1])?"LOG_ON":"LOG_OUT");
				strcat(condBuf, tmpBuf);
			}

			sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12.1f\n", //uamyd 20110515 succrate_added
					"", "", row[row_index+2],row[row_index+3],row[row_index+4],
					atoi(row[row_index+2])==0?0.0:(((float)atoi(row[row_index+3])/(float)atoi(row[row_index+2]))*100)); //uamyd 20110515 succrate_added
			strcat(condBuf, tmpBuf );

			for( j=5; j<34; j+=4 ){
				//j = 5,9,13,17,21,25,29,33
				sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n", 
						"", "", row[row_index+j],row[row_index+j+1],row[row_index+j+2],row[row_index+j+3]);
				strcat(condBuf, tmpBuf );
			}
			sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n", 
					"", "", row[row_index+37],row[row_index+38],row[row_index+39],row[row_index+40]);
			strcat(condBuf, tmpBuf);
			sprintf(tmpBuf, "%3s %8s %12s %12s\n",
					"", "", row[row_index+41],row[row_index+42]);
			strcat(condBuf, tmpBuf);

    		sprintf(tmpBuf, "    ====================================================================\n");
			strcat(condBuf, tmpBuf);
			select_cnt++;

			if(strlen(condBuf)) {
				stmd_txMsg2Cond(condBuf, (sts_code - STSCODE_TO_MSGID_STATISTICS), 1, snd_cnt++);
                fprintf (fp, "%s",condBuf);
                memset(condBuf, 0x00, sizeof(condBuf));
            }
        }
        mysql_free_result(result);

        if (select_cnt == 0) 
		{
			sprintf(tmpBuf, "%3s %8s %12s %12s\n", "",SysName[i], "-","-");
			strcat(condBuf, tmpBuf);
			sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n", "", "", "0","0","0","0"); //uamyd 20110515 succrate_added
			strcat(condBuf, tmpBuf);
			for(j=0;j<9;j++){
				sprintf(tmpBuf, "%3s %8s %12s %12s %12s %12s\n", "", "", "0","0","0","0");
				strcat(condBuf, tmpBuf );
			}
			sprintf(tmpBuf, "%3s %8s %12s %12s\n", 
					"", "", "0","0");
			strcat(condBuf, tmpBuf);
    		sprintf(tmpBuf, "    ====================================================================\n");
            strcat(condBuf, tmpBuf);
        } 
    }

    sprintf(tmpBuf, "    COMPLETED\n\n\n");
    strcat(condBuf, tmpBuf);

    if(fp != NULL) 
	{
        fprintf (fp, "%s",condBuf);
        fclose(fp);
    }
    
    stmd_txMsg2Cond(condBuf, (sts_code - STSCODE_TO_MSGID_STATISTICS), 0, snd_cnt);
    
    return 1;
}
コード例 #7
0
void Knmap::getFilePath( const QString& caption, QString& path, QLineEdit* lineEdit, const bool save )
{	if( getFilePath( caption, path, save ))
		lineEdit->setText( path );
}
コード例 #8
0
ファイル: Deleting.cpp プロジェクト: utkillr/VerController
bool deleteFile(string fileName) {
	string fileDirectory = getFilePath(fileName);
	if (remove((fileDirectory + '\\' + fileName).c_str()) != 0) return false;
	else return true;
}
コード例 #9
0
ファイル: textdomain.c プロジェクト: buddywithgol/visopsys
static int loadMessageFile(const char *domain)
{
	int status = 0;
	char *path = NULL;
	struct stat pathStat;
	int fd = -1;
	messages *msgfile = NULL;
	unsigned fpos = 0;

	memset(&pathStat, 0, sizeof(struct stat));

	// Get the path to the appropriate file
	path = getFilePath(domain);
	if (!path)
	{
		status = ERR_MEMORY;
		goto out;
	}

	// Does it exist?
	status = stat(path, &pathStat);
	if (status < 0)
		goto out;

	fd = open(path, O_RDONLY);
	if (fd < 0)
	{
		status = fd;
		goto out;
	}

	// Get memory for the msgfile structure and its buffer
	msgfile = calloc(1, sizeof(messages));
	if (msgfile)
		msgfile->buffer = calloc(pathStat.st_size, 1);
	if (!msgfile || !msgfile->buffer)
	{
		status = ERR_MEMORY;
		goto out;
	}

	strncpy(msgfile->domain, domain, MAX_NAME_LENGTH);
	strncpy(msgfile->locale, _getLocaleCategory(LC_MESSAGES),
		LOCALE_MAX_NAMELEN);

	while (fpos < pathStat.st_size)
	{
		status = read(fd, msgfile->buffer, (pathStat.st_size - fpos));
		if (status < 0)
			goto out;

		if (!status)
			break;

		fpos += status;
	}

	if (fpos < pathStat.st_size)
	{
		status = ERR_NODATA;
		goto out;
	}

	msgfile->header = msgfile->buffer;

	if (msgfile->header->magic != MESSAGE_MAGIC)
	{
		status = ERR_BADDATA;
		goto out;
	}

	if (msgfile->header->version != MESSAGE_VERSION)
	{
		status = ERR_BADDATA;
		goto out;
	}

	msgfile->origTable = (msgfile->buffer + msgfile->header->origTableOffset);
	msgfile->transTable = (msgfile->buffer + msgfile->header->transTableOffset);

	msgFiles = realloc(msgFiles, ((numFiles + 1) * sizeof(messages *)));
	if (!msgFiles)
	{
		status = ERR_MEMORY;
		goto out;
	}

	msgFiles[numFiles++] = msgfile;

	status = 0;

out:
	if (path)
		free(path);

	if (fd >= 0)
		close(fd);

	if (status && msgfile)
	{
		if (msgfile->buffer)
			free(msgfile->buffer);
		free(msgfile);
	}

	return (status);
}
コード例 #10
0
ファイル: prompt.c プロジェクト: rsingla92/eece-315-proj1
/* Takes the command struct and takes approproate action.
 * Will either execute a shell command, program, or output an error message.
 * @params: command - a struct representing the command
 * @return: false is the command was note found, true otherwise.
 */
bool processCommand(command_t* command, char* pEnv[]){

   char* defaultDir = getenv("HOME");

   if( strcmp(command->name, "cd") == CMP_OK) {
       if( command->argc == 1 ) {
	   changeDirectory(defaultDir);
       } else {
	   changeDirectory(command->argv[1]);
       }
   } else if( strcmp(command->name,"help") == CMP_OK) {
       help();
   } else if( strcmp(command->name, "senv") == CMP_OK) {
       char* envName = NULL;
       char* envVal = NULL;

       if( command->argc > 1) {
           envName = command->argv[1];
       } 

       if( command->argc > 2) {
           envVal = command->argv[2];
       }

       setEnvVar(envName,envVal);

   } else if( strcmp(command->name, "usenv") == CMP_OK) {
       char* envName = NULL;
       if( command->argc > 1) {
	       envName = command->argv[1];
       }
       unsetEnvVar(envName);

   } else if( strcmp(command->name, "genv") == CMP_OK) {
       char* envName = NULL;
       if( command-> argc > 1) {
	       envName = command->argv[1];
       }
       getEnvVar(envName);
   } else {
       char* filePath = getFilePath(command->name);
       if(filePath != NULL) {
	   pid_t pid_command = fork();

           if(pid_command < CHILD) { // ERROR
	       fprintf(stderr, "Fork failure!\n");
  	   } else if ( pid_command == CHILD) {
	       if(command->isBg) {
		   freopen("/dev/null","w",stdout);
	           freopen("/dev/null","w",stderr);
	       }

	       execve(filePath, command->argv, pEnv);
	   } else {
	       if(!command->isBg) {
		   int stat;
		   waitpid(pid_command, &stat, 0);
	       } else {
			   printf("Process ID: %d\n", pid_command);
		   }
           }
       } else if(strcmp(command->name, "quit") == CMP_OK ||
		 strcmp(command->name, "exit") == CMP_OK ||
		 strcmp(command->name, "q") == CMP_OK ) {
	   return false;
       } else {
   	   printf("%s: Command not found\n", command->name);
	   return false;
       }
   }  
   return true;
}
コード例 #11
0
ファイル: placedetection.cpp プロジェクト: cagbal/SSG-C-
void PlaceDetection::processImages()
{
    static Mat img1, img2;
    Mat img_seg1, img_seg2;
    vector<NodeSig> ns1, ns2;
    vector<vector<NodeSig> > ns_vec;  //Stores last tau_w node signatures
    float matching_cost = 0;

    bool in_place = false; //Flag whether we are in place or transition

    isProcessing = true;

    //Process all images
    for(int frame_no = START_IDX; frame_no < END_IDX-1; frame_no++)
    {
        //Wait until process_next_frame set to true
        while(frameByFrameProcess == true && process_next_frame == false)
        {
            waitKey(1);
        }
        //Set it back to false
        process_next_frame = false;

        //getFilePath returns the path of the file given frame number
        string filepath1 = getFilePath(DATASET_FOLDER, DATASET_NO, IMG_FILE_PREFIX, frame_no);
        string filepath2 = getFilePath(DATASET_FOLDER, DATASET_NO, IMG_FILE_PREFIX, frame_no+1);

        //Segment images
        if(frame_no == START_IDX)
        {
            img2 = imread(filepath1);
            resize(img2, img2, cv::Size(0,0), IMG_RESCALE_RAT, IMG_RESCALE_RAT);
            ns2 = seg_track->seg->segmentImage(img2,img_seg2);
        }
        ns1 = ns2;
        img1 = img2;
        img_seg1 = img_seg2;

        img2 = imread(filepath2);
        resize(img2, img2, cv::Size(0,0), IMG_RESCALE_RAT, IMG_RESCALE_RAT);
        ns2 = seg_track->seg->segmentImage(img2,img_seg2);


        //Show original images on the window
        //emit seg_track->shshowImg1(mat2QImage(img1));
        //emit seg_track->showImg2(mat2QImage(img2));

        if(frame_no == START_IDX)
        {
            //Initialize M matrix (Existence "M"ap)
            seg_track->M = Mat(ns1.size(), 1, CV_32S, -1);

            for(int i = 0; i < ns1.size(); i++)
            {
                seg_track->M.at<int>(i,0) = i; //Nodes are placed in order in the first column of M

                //Initialize avg node signatures list
                pair<NodeSig, int> new_node(ns1[i], 1);

                seg_track->M_ns.push_back(new_node);
            }

            //Insert first node sig for the first time
            ns_vec.push_back(ns1);
        }

        //Insert next node sig
        ns_vec.push_back(ns2);

        //Keep max size tau_w
        if(ns_vec.size() > seg_track->tau_w)
        {
            ns_vec.erase(ns_vec.begin());
        }

        //Drawing purposes only
        seg_track->gm->drawMatches(ns1, ns2, img_seg1, img_seg2);

        //Fill node existence map
        matching_cost = seg_track->fillNodeMap(seg_track->M, seg_track->M_ns, ns_vec);


        //Plot connectivity map
        seg_track->plotMap(seg_track->M);

        //Calculate coherency based on existence map
        calcCohScore(seg_track->M, seg_track->M_ns, coherency_scores);

        //Decide last frame is whether transition or place
        //Results are written into detected places
        int detection_result = detectPlace(coherency_scores,detected_places_unfiltered,detected_places);

        //If started for new place
        //Create new SSG
        if(detection_result == 1)
        {
            SSG new_ssg;
            SSGs.push_back(new_ssg);
            in_place = true;
        }
        else if(detection_result == -1)
        {
            in_place = false;
        }

        //Fill SSG if frame is as place
        if(in_place)
        {
            SSGProc::updateSSG(SSGs.back(), ns2, seg_track->M);
        }

        //Show last SSG
        if(SSGs.size() > 0)
        {
            img2 = imread(filepath2);
            //emit showSSG(mat2QImage(SSGProc::drawSSG(SSGs.back(), img2)));
        }

        //Plot transition and place regions
        plotPlaces(coherency_scores, detected_places);

        //Wait a little for GUI processing
        waitKey(1);
    }

    isProcessing = false;
}
コード例 #12
0
ファイル: hPixels32Import.cpp プロジェクト: liujw/SceneEditor
inline static void* loadImageFile(const char* fileName,long* out_width,long* out_height){
    long strLength=(long)strlen(fileName);
    String path=getFilePath(fileName, strLength);
    return _loadImageFile(getFileNameNoPath(fileName, strLength),path.c_str(),out_width,out_height);
}
コード例 #13
0
int stmd_FlowSelect(int time_type, char *table_type)
{
    char        condBuf[4096], tmpBuf[1024];
    int         sts_code;
    char        str_time[10];
    int         select_cnt = 0;

    char        query[4096];
    MYSQL_RES   *result;
    MYSQL_ROW   row;

    time_t      now;
    char        tm[DIR_NUM][8];
    char        path[60];
    char        fileName[60];
    FILE        *fp;

    int         i;
    char title[4][16]={"SYSTEM", "AVG_FLOW", "MIN_FLOW","MAX_FLOW"};
    int row_index;
    char SysName[2][8] = {"SCEA","SCEB"};
    int realSysCnt =2;
    int realItemCnt =0;

    now = time(0);
    if(time_type != STMD_WEEK)
        now = now - (printTIME[time_type]*60) - STAT_OFFSET_UNIT;
    else
        now = now - (printTIME[time_type]*60);

    getFilePath (path, tm, &now); // ~/LOG/STAT 까지 만든다.
    makeDirectory (time_type,path,tm);

    sprintf(fileName, "%s", path );
    makeFileName ( fileName, STMD_FLOW, time_type, tm );

    if ( ( fp = fopen(fileName, APPEND ) ) == NULL ){
        sprintf(trcBuf, "%s Open Fail\n", fileName);
        trclib_writeLog(FL, trcBuf);
        return -1;
    }


    switch (time_type) {
        case    STMD_HOUR :
            sts_code = STSCODE_STM_PERIODIC_FLOW_HOUR;
            sprintf (str_time, "%s", STMD_STR_HOUR);
            break;
        case    STMD_DAY :
            sts_code = STSCODE_STM_PERIODIC_FLOW_DAY;
            sprintf (str_time, "%s", STMD_STR_DAY);
            break;
        case    STMD_WEEK :
            sts_code = STSCODE_STM_PERIODIC_FLOW_WEEK;
            sprintf (str_time, "%s", STMD_STR_WEEK);
            break;
        case    STMD_MONTH :
            sts_code = STSCODE_STM_PERIODIC_FLOW_MONTH;
            sprintf (str_time, "%s", STMD_STR_MONTH);
            break;
    }

    sprintf(condBuf,"    %s %s\n    S%04d FLOW PERIODIC STATISTICS MESSAGE\n",
        "SCM", // 현재는 OMP로 고정하지만 실질적인 시스템 이름으로 변경 필요 hslim_oper
        commlib_printTStamp(), // 현재시각 time stamp (년,월,일,시,분,초,요일)
        sts_code);

    sprintf(tmpBuf, "    PERIOD = %s\n    MEASURETIME = %s  -  %s\n\n",
        str_time,
        get_period_start_time(time_type), get_period_end_time(time_type));
    strcat(condBuf,tmpBuf);

    sprintf(tmpBuf, "    ====================================================================\n");
    strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %8s %12s %12s %12s\n","",title[0],title[1],title[2],title[3] );
	strcat(condBuf, tmpBuf);
    sprintf(tmpBuf, "    ====================================================================\n");
    strcat(condBuf, tmpBuf);

    for(i = 0; i < realSysCnt; i++)
	{
		realItemCnt = 1;

	   	sprintf(query, "SELECT system_name, "
				" round(ifnull(avg(avg_flow), 0),0), ifnull(min(min_flow), 0), ifnull(max(max_flow), 0) "
			   " from %s "
			   " where system_name = '%s' AND (stat_date = '%s') "
			   " group by system_name ",
			   table_type, SysName[i], get_period_select_time(time_type));

        if ( trcLogFlag == TRCLEVEL_SQL ) {
            sprintf(trcBuf, "query = %s\n", query);
            trclib_writeLog(FL, trcBuf);
        }
		if (stmd_mysql_query (query) < 0) {
            sprintf(trcBuf,">>> mysql_query fail; err=%s\n", mysql_error(conn));
            trclib_writeLogErr (FL,trcBuf);
            if(fp != NULL) fclose(fp);
            return -1;
        }

        select_cnt = 0;
        result = mysql_store_result(conn);
        while((row = mysql_fetch_row(result)) != NULL) 
		{
			row_index = 1;
			if (select_cnt == 0)
			{
				sprintf(tmpBuf, "%3s %8s %12s %12s %12s\n",
						"",SysName[i],row[row_index],row[row_index+1],row[row_index+2]);
				strcat(condBuf, tmpBuf);
			} 
			else 
			{
				sprintf(tmpBuf, "%3s %8s %12s %12s %12s\n",
						"","",row[row_index],row[row_index+1],row[row_index+2]);
				strcat(condBuf, tmpBuf);
			}

    		sprintf(tmpBuf, "    ====================================================================\n");
			strcat(condBuf, tmpBuf);
			select_cnt++;
        }
        mysql_free_result(result);

        if (select_cnt == 0) 
		{
			sprintf(tmpBuf, "%3s %8s %12s %12s %12s\n",
					"",SysName[i], "0","0","0");
			strcat(condBuf, tmpBuf);
    		sprintf(tmpBuf, "    ====================================================================\n");
            strcat(condBuf, tmpBuf);
        } 
    }

    sprintf(tmpBuf, "    COMPLETED\n\n\n");
    strcat(condBuf, tmpBuf);

    if(fp != NULL) 
	{
        fprintf (fp, "%s",condBuf);
        fclose(fp);
    }
    
    stmd_txMsg2Cond(condBuf, (sts_code - STSCODE_TO_MSGID_STATISTICS), 0, 1);
    
    return 1;
}
コード例 #14
0
ファイル: stmd_periodic_sms.c プロジェクト: lanian09/mysource
int stmd_SmsSelect(int time_type, char *table_type)
{
    char        condBuf[4096], tmpBuf[1024];
    int         sts_code;
    char        str_time[10];
    int         select_cnt = 0;

    char        query[4096];
    MYSQL_RES   *result;
    MYSQL_ROW   row;

    time_t      now;
    char        tm[DIR_NUM][8];
    char        path[60];
    char        fileName[60];
    FILE        *fp;

    int         i,j;
    char title[5][16]={"SYSTEM", "SMSC_IP", "REQ", "SUCC","FAIL"};
	char title1[6][16]={"", "", "SMPP_ERR","SVR_ERR","SMSC_ERR","ETC_ERR"};
    int row_index;
    char SysName[2][8] = {"SCMA", "SCMB"};
    int realSysCnt =2;
    int realItemCnt[2] = {0, 0};
	char smsc_ip[2][16];
	int	exist = 0;

    now = time(0);
    if(time_type != STMD_WEEK)
        now = now - (printTIME[time_type]*60) - STAT_OFFSET_UNIT;
    else
        now = now - (printTIME[time_type]*60);

    getFilePath (path, tm, &now); // ~/LOG/STAT 까지 만든다.
    makeDirectory (time_type,path,tm);

    sprintf(fileName,"%s", path );
    makeFileName ( fileName, STMD_SMS, time_type, tm );

    if ( ( fp = fopen(fileName, APPEND ) ) == NULL ){
        sprintf(trcBuf, "%s Open Fail\n", fileName);
        trclib_writeLog(FL, trcBuf);
        return -1;
    }

    switch (time_type) {
        case    STMD_HOUR :
            sts_code = STSCODE_STM_PERIODIC_SMS_HOUR;
            sprintf(str_time, "%s", STMD_STR_HOUR);
            break;
        case    STMD_DAY :
            sts_code = STSCODE_STM_PERIODIC_SMS_DAY;
            sprintf(str_time, "%s", STMD_STR_DAY);
            break;
        case    STMD_WEEK :
            sts_code = STSCODE_STM_PERIODIC_SMS_WEEK;
            sprintf (str_time, "%s", STMD_STR_WEEK);
            break;
        case    STMD_MONTH :
            sts_code = STSCODE_STM_PERIODIC_SMS_MONTH;
            sprintf (str_time, "%s", STMD_STR_MONTH);
            break;
    }

    sprintf(condBuf,"    %s %s\n    S%04d SMS PERIODIC STATISTICS MESSAGE\n",
        "SCM", // 현재는 OMP로 고정하지만 실질적인 시스템 이름으로 변경 필요 hslim_oper
        commlib_printTStamp(), // 현재시각 time stamp (년,월,일,시,분,초,요일)
        sts_code);

    sprintf(tmpBuf, "    PERIOD = %s\n    MEASURETIME = %s  -  %s\n\n",
        str_time,
        get_period_start_time(time_type), get_period_end_time(time_type));

    strcat(condBuf,tmpBuf);

    sprintf(tmpBuf, "    ====================================================================================\n");
    strcat(condBuf, tmpBuf);
    sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s\n","",title[0],title[1],title[2],title[3],title[4] );
    strcat(condBuf, tmpBuf);
    sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s %12s\n", "","", "", title1[2],title1[3],title1[4],title1[5]);
    strcat(condBuf, tmpBuf);
    sprintf(tmpBuf, "    ====================================================================================\n");
    strcat(condBuf, tmpBuf);

	memset(smsc_ip, 0x00, sizeof(smsc_ip));
    for(i = 0; i < realSysCnt; i++)
	{
	   sprintf(query, "SELECT code, count(*) from ip_code_tbl where type = 2 group by code");

		if (stmd_mysql_query (query) < 0) {
            sprintf(trcBuf,">>> mysql_query fail; err=%s\n", mysql_error(conn));
            trclib_writeLogErr (FL,trcBuf);
            if(fp != NULL) fclose(fp);
            return -1;
	   }
	   result = mysql_store_result(conn);
	   row = mysql_fetch_row(result);
	   if( row == NULL )
	   {
		   exist = 0;
		   realItemCnt[i] = 0;
		   mysql_free_result(result);
		   continue;
	   }
	   else
	   {
		   exist = 1;
		   realItemCnt[i] = atoi(row[1]);
		   sprintf(smsc_ip[i], "%s", row[0]);
		   mysql_free_result(result);
	   }
	   
	   sprintf(query, "SELECT system_name, smsc_ip, "
			   " IFNULL(SUM(req), 0), IFNULL(SUM(succ), 0), IFNULL(SUM(fail), 0), "
			   " IFNULL(SUM(smpp_err), 0), " 
			   " IFNULL(SUM(svr_err), 0), IFNULL(SUM(smsc_err), 0), " 
			   " IFNULL(SUM(etc_err), 0) "
			   " from %s "
			   " where system_name = '%s' AND (stat_date = '%s') "
			   " group by system_name, smsc_ip ",
			   table_type, SysName[i], get_period_select_time(time_type));

        if ( trcLogFlag == TRCLEVEL_SQL ) {
            sprintf(trcBuf, "query = %s\n", query);
            trclib_writeLog(FL, trcBuf);
        }
		if (stmd_mysql_query (query) < 0) {
            sprintf(trcBuf,">>> mysql_query fail; err=%s\n", mysql_error(conn));
            trclib_writeLogErr (FL,trcBuf);
            if(fp != NULL) fclose(fp);
            return -1;
        }

		logPrint(trcLogId, FL, "SMS Period query : %s\n", query);

        result = mysql_store_result(conn);

		select_cnt = 0;
        while((row = mysql_fetch_row(result)) != NULL) 
		{
            row_index = 2;
			if (select_cnt==0)
			{
				sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s\n",
						"", row[0], row[1], row[row_index],row[row_index+1],row[row_index+2]);
				strcat(condBuf, tmpBuf);
				sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s %12s\n",
						"", "", "", row[row_index+3],row[row_index+4],row[row_index+5],row[row_index+6]);
				strcat(condBuf, tmpBuf);
			} 
			else 
			{
				sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s\n",
						"", "", row[1], row[row_index],row[row_index+1],row[row_index+2]);
				strcat(condBuf, tmpBuf);
				sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s %12s\n",
						"", "", "", row[row_index+3], row[row_index+4],row[row_index+5],row[row_index+6] );
				strcat(condBuf, tmpBuf);
			}

    		sprintf(tmpBuf, "    ====================================================================================\n");
            strcat(condBuf, tmpBuf);

            select_cnt++;
        }
        mysql_free_result(result);

        if (select_cnt == 0) 
		{
			for( j = 0; j < realItemCnt[i]; j++ )
			{
				if (j==0)
				{
					sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s\n",
							"", SysName[i], smsc_ip[j], "0", "0", "0");
					strcat(condBuf, tmpBuf);
					sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s %12s\n",
							"", "", "", "0", "0", "0","0" );
					strcat(condBuf, tmpBuf);
				}
				else 
				{
					sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s\n",
							"", "", smsc_ip[j], "0", "0", "0");
					strcat(condBuf, tmpBuf);
					sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s %12s\n",
							"", "", "", "0", "0", "0","0" );
					strcat(condBuf, tmpBuf);
				}
			}
    		sprintf(tmpBuf, "    ====================================================================================\n");
            strcat(condBuf, tmpBuf);
        } 
    }

    sprintf(tmpBuf, "    COMPLETED\n\n\n");
    strcat(condBuf, tmpBuf);

    if(fp != NULL) 
	{
        fprintf (fp, "%s",condBuf);
        fclose(fp);
    }
    
    stmd_txMsg2Cond(condBuf, (sts_code - STSCODE_TO_MSGID_STATISTICS), 0, 1);
    
    return 1;
}
コード例 #15
0
ファイル: hangMan.c プロジェクト: bartmnz/hangMan
int main (int argc, char* argv[]){
	char theSecret[MAXSIZE], theGuess[MAXSIZE], knownStr[MAXSIZE], filePath[MAXFILE], statsPath[MAXFILE], theStats[MAXFILE];

	int numGuess = 0;
	FILE *filePointer = NULL, *statsPointer = NULL;
	getFilePath(filePath, argc == 2 ? argv[1] : ".words");
	filePointer = fopen(filePath, "r");
	int games, wins, losses;
	float average;
	getFilePath(statsPath, ".hangman");
	statsPointer = fopen(statsPath, "a+");
	getStats(statsPointer, theStats);
	char* remainder;
	games = strtol(theStats, &remainder,10);
	strcpy(theStats, remainder);
	wins = strtol(theStats, &remainder,10);
	strcpy(theStats, remainder);
	losses = games - wins;
	average = strtof(theStats, &remainder);
	char winString[5], losString[7];
	wins == 1 ? strcpy(winString, "Win") : strcpy(winString, "Wins");
	losses == 1 ? strcpy(losString, "Loss") : strcpy(losString, "Losses");
	printf("Game %d  %s: %d %s: %d Average:%.1f\n", games, winString, wins, losString, losses, average); 
	if (!filePointer || !statsPointer){
                printf("ERROR: file does not exist in home directory\n");
                exit(0);
        }
	getLine(filePointer, theSecret);
	int size=(int)strlen(theSecret)-1;
	int wordLen = size < MAXSIZE ? size : MAXSIZE;
	setTo_(knownStr, wordLen);
	while(true){
		printf("%d  %s: ",numGuess, knownStr);
		getGuess(theGuess);//{//no body to loop
		//}
		int check = checkGuess(theSecret, knownStr, theGuess);
		if(!check){
			numGuess++;
		}else if (check == 1){
			char misses[7];
			numGuess == 1 ? strcpy(misses, "miss") : strcpy(misses, "misses");
			printf("   %s\n", theSecret);
			printf("You win! You had %d %s.\n", numGuess, misses);
			wins++;
			games++;
			average = (average*(games-1) + numGuess)/games;
			break;
		}
		printGallows(numGuess);
		if( numGuess == 6){
			printf("  %s\n", theSecret);
			printf("You lose\n");
			losses++;
			games++;
			average = (average*(games-1) + numGuess)/games;
			break;
		}
	}
	fprintf(statsPointer, "\n%d %d %f", games, wins, average);
	fclose(filePointer);
	fclose(statsPointer);
}
コード例 #16
0
ファイル: tiio_3gpM.cpp プロジェクト: AmEv7Fam/opentoonz
void TLevelWriter3gp::save(const TImageP &img, int frameIndex)
{
	if (m_cancelled)
		return;

	TRasterImageP image(img);
	int lx = image->getRaster()->getLx();
	int ly = image->getRaster()->getLy();
	//void *buffer = image->getRaster()->getRawData();
	int pixSize = image->getRaster()->getPixelSize();
	if (pixSize != 4)
		throw TImageException(getFilePath(), "Unsupported pixel type");

	QMutexLocker sl(&m_mutex);

	if (!m_properties)
		m_properties = new Tiio::MovWriterProperties();

	Tiio::MovWriterProperties *prop = (Tiio::MovWriterProperties *)(m_properties);

	//CodecType compression = StandardCompressionType;  prop->getCurrentCodec();
	//CodecQ quality = StandardQualityType;  prop->getCurrentQuality();

	if (!m_initDone) {
		//FSSpec fspec;
		Rect frame;
		long max_compressed_size;
		QDErr err;

		m_videoTrack = NewMovieTrack(m_movie, FixRatio((short)lx, 1), FixRatio((short)ly, 1), kNoVolume);

		if ((err = GetMoviesError() != noErr))
			throw TImageException(getFilePath(), "can't create video track");

		m_dataRef = nil;
		m_hMovieData = NewHandle(0);

		// Construct the Handle data reference
		err = PtrToHand(&m_hMovieData, &m_dataRef, sizeof(Handle));

		if ((err = GetMoviesError() != noErr))
			throw TImageException(getFilePath(), "can't create Data Ref");

		m_videoMedia = NewTrackMedia(m_videoTrack, VideoMediaType, (TINT32)m_frameRate, m_dataRef, HandleDataHandlerSubType);

		OpenADefaultComponent(MovieExportType, '3gpp', &m_myExporter);

		//  err = (short)MovieExportDoUserDialog(m_myExporter, m_movie, 0, 0, 0, &m_cancelled);

		//  if (m_cancelled)
		//	  throw TImageException(getFilePath(), "User abort of 3GP render");
		if ((err = GetMoviesError() != noErr))
			throw TImageException(getFilePath(), "can't create video media");
		if ((err = BeginMediaEdits(m_videoMedia)) != noErr)
			throw TImageException(getFilePath(), "can't begin edit video media");
		frame.left = 0;
		frame.top = 0;
		frame.right = lx;
		frame.bottom = ly;

#if 0
  if ((err = NewGWorld(&(m_gworld), pixSize * 8, &frame, 0, 0, 0))!=noErr)
#else /* Mac OSX 10.7 later */
		if ((err = QTNewGWorld(&(m_gworld), pixSize * 8, &frame, 0, 0, 0)) != noErr)
#endif
		throw TImageException(getFilePath(), "can't create movie buffer");
#ifdef WIN32
		LockPixels(m_gworld->portPixMap);
		if ((err = GetMaxCompressionSize(m_gworld->portPixMap, &frame, 0,
										 quality, compression, anyCodec,
										 &max_compressed_size)) != noErr)
			throw TImageException(getFilePath(), "can't get max compression size");

#else

#if 0
  PixMapHandle pixmapH = GetPortPixMap (m_gworld);
  LockPixels(pixmapH);
#else
		PixMapHandle pixmapH = NULL;
#endif
		max_compressed_size = lx * ly * 4 * 20;

/*if ((err = GetMaxCompressionSize(pixmapH, &frame, 0, 
                                quality,  compression,anyCodec, 
				 &max_compressed_size))!=noErr)
    throw TImageException(getFilePath(), "can't get max compression size");*/
#endif

		m_compressedData = NewHandle(max_compressed_size);

		if ((err = MemError()) != noErr)
			throw TImageException(getFilePath(), "can't allocate compressed data for movie");

		MoveHHi(m_compressedData);
		HLock(m_compressedData);
		if ((err = MemError()) != noErr)
			throw TImageException(getFilePath(), "can't allocate img handle");

#if 0
  m_pixmap = GetGWorldPixMap(m_gworld);
  
  
  if (!LockPixels(m_pixmap))
    throw TImageException(getFilePath(), "can't lock pixels");

  buf    = (PixelXRGB*) GetPixBaseAddr(m_pixmap);
#else
		m_pixmap = NULL;
		buf = NULL;
#endif
		buf_lx = lx;
		buf_ly = ly;

		m_initDone = true;
	}

	unsigned short rowBytes = (unsigned short)(((short)(*(m_pixmap))->rowBytes & ~(3 << 14)));

	Rect frame;
	ImageDescriptionHandle img_descr;
	Ptr compressed_data_ptr;
	QDErr err;

	frame.left = 0;
	frame.top = 0;
	frame.right = lx;
	frame.bottom = ly;

	TRasterP ras = image->getRaster();
#ifdef WIN32
	compressed_data_ptr = StripAddress(*(m_compressedData));
	copy(ras, buf, buf_lx, buf_ly);
#else
	compressed_data_ptr = *m_compressedData;
	copy(ras, buf, buf_lx, buf_ly, rowBytes);
#endif
	img_descr = (ImageDescriptionHandle)NewHandle(4);

#ifdef WIN32
	if ((err = CompressImage(m_gworld->portPixMap,
							 &frame,
							 quality, compression,
							 img_descr, compressed_data_ptr)) != noErr)
		throw TImageException(getFilePath(), "can't compress image");
#else

#if 0
 PixMapHandle pixmapH = GetPortPixMap (m_gworld);
 if ((err = CompressImage(pixmapH, 
	                 &frame, 
  			 codecNormalQuality, kJPEGCodecType,
			 img_descr, compressed_data_ptr))!=noErr)
	{
  throw TImageException(getFilePath(), "can't compress image");
}
#endif
#endif

	if ((err = AddMediaSample(m_videoMedia, m_compressedData, 0,
							  (*img_descr)->dataSize, 1,
							  (SampleDescriptionHandle)img_descr,
							  1, 0, 0)) != noErr)
		throw TImageException(getFilePath(), "can't add image to movie media");

	DisposeHandle((Handle)img_descr);
}
コード例 #17
0
ファイル: dcfili.cpp プロジェクト: omsys-dev/original-source
DCirfile *
DCirfile::SetConfigTemplate(const char *sect, const char *setting,
		                        bool link)
{
	DCirfile *bottomIni = SecFile ? SecFile : this;
	bool secfound = false;
	char *startdir =  _getcwd(NewName(1024), 1024);
	char *currdir = startdir;
	char *newdir = NULL;
	int startdrive = _getdrive();
	int currdrive = startdrive;
	int newdrive = 0;

	IniLevel = 0;

	if (!LogEventFunc)
		LastConfigSetting = NewName(setting);

	if (SecFile != NULL) {
		IniFileList.add(SecFile, ++IniLevel);
		IniNameList.add(SecFile->getBaseName(), IniLevel);
		IniChainList.add(SecFile->getFilePath(), IniLevel);
	}
	IniFileList.add(this, ++IniLevel);
	IniNameList.add(getBaseName(), IniLevel);
	IniChainList.add(getFilePath(), IniLevel);

	DCirfile *configTpl = NULL;
	char *configTplName = NULL;

	// SecFile (specific ini) overrides tpl choice in this
	DCirfile *topIni = this;
	secfound = Section(sect);

	if (secfound
	 && Find("Scope"))
		Scope = StrRight();

	if (secfound
	 && !stricmp(setting, "configs")
	 && Find("Document")) {   // insert document chain here
		DCirfile *topdoc = this;
		while (topdoc->Section(sect)) {
			if (!topdoc->Find("Document"))
				break;  // end of chain with no end flag ****
			char *nm = topdoc->StrRight();
			if (!nm)
				break;  // end of chain with no end flag ****
			if (!stricmp(nm, "end")) {
				DeleteName(nm);
				topdoc->ChainEnded = true;
				break;  // end of chain with end flag
			}
			DeleteName(nm);
			if ((configTplName = topdoc->PathRight()) == NULL)
				break;  // end of chain with no end flag ****
			if ((configTpl = new DCirfile(configTplName)) == NULL) {
				LogEvent(logwarn, 1, topdoc->getFilePath(), " refers to unopenable ",
					"Document template", " ", NewName(configTplName));
				DeleteName(configTplName);
				configTplName = NULL;
				break;
			}
			if (configTpl->FErr() != fok) {
				LogEvent(logwarn, 1, topdoc->getFilePath(), " refers to nonexistent ",
					"Document template", " ", NewName(configTpl->getFilePath()));
				DeleteName(configTplName);
				configTplName = NULL;
				delete configTpl;
				break;  // file not found
			}
			newdir = configTpl->getBasePath();
			if (*(newdir + 1) == ':')
				newdrive = (toupper(*newdir) - 'A') + 1;
			if (newdrive
			 && (currdrive != newdrive))
				_chdrive(currdrive = newdrive);
			if (stricmp(newdir, currdir))
				_chdir(currdir = newdir);

			if (IniNameList(configTpl->getBaseName())) {
				LogEvent(logwarn, 1, topdoc->getFilePath(), " repeats ",
					"Document template", " ", NewName(configTpl->getFilePath()));
				DeleteName(configTplName);
				configTplName = NULL;
				delete configTpl;
				break;  // deja vu, end of the line
			}

			topdoc = configTpl;  // step up
			if (topdoc->Section("Templates")
			 && topdoc->Find("Scope"))
				topdoc->Scope = topdoc->StrRight();
			DeleteName(configTplName);
			configTplName = NULL;
			IniFileList.add(topdoc, ++IniLevel);
			IniNameList.add(topdoc->getBaseName(), IniLevel);
			IniChainList.add(topdoc->getFilePath(), IniLevel);
		}
	}

	if (!secfound
	 || !Find(setting)) {  // check for old setting
		if (!stricmp(setting, "configs")) {
			if (Section("Setup")
			 && Find("ConfigTemplate")) {
				sect = "Setup";
				setting = "ConfigTemplate";
			}
			else if (Section("FDK")
			 && Find("ConfigTemplate")) {
				sect = "FDK";
				setting = "ConfigTemplate";
			}
		}
		else if (!stricmp(setting, "languages")) {
			if (Section("Setup")
			 && Find("LanguageText"))
				sect = "Setup";
				setting = "LanguageText";
		}
		else if (!stricmp(setting, "macros")) {
			if (Section("Macros")
			 && Find("MacroFile")) {
				sect = "Macros";
				setting = "MacroFile";
			}
		}
	}

	while (topIni->Section(sect)) {
		if (!topIni->Find(setting))
			break;  // end of chain with no end flag ****
		char *nm = topIni->StrRight();
		if (!nm)
			break;  // end of chain with no end flag ****
		if (!stricmp(nm, "end")) {
			DeleteName(nm);
			topIni->ChainEnded = true;
			break;  // end of chain with end flag
		}
		DeleteName(nm);
		if ((configTplName = topIni->PathRight()) == NULL)
			break;  // end of chain with no end flag ****
		if ((configTpl = new DCirfile(configTplName)) == NULL) {
			LogEvent(logwarn, 1, topIni->getFilePath(), " refers to unopenable ",
				setting, " ", NewName(configTplName));
			DeleteName(configTplName);
			configTplName = NULL;
			break;  // can't open file
		}
		if (configTpl->FErr() != fok) {
			LogEvent(logwarn, 1, topIni->getFilePath(), " refers to nonexistent ",
				setting, " ", NewName(configTpl->getFilePath()));
			DeleteName(configTplName);
			configTplName = NULL;
			delete configTpl;
			break;  // file not found
		}
		newdir = configTpl->getBasePath();
		if (*(newdir + 1) == ':')
			newdrive = (toupper(*newdir) - 'A') + 1;
		if (newdrive
		 && (currdrive != newdrive))
			_chdrive(currdrive = newdrive);
		if (stricmp(newdir, currdir))
			_chdir(currdir = newdir);

		if (IniNameList(configTpl->getBaseName())) {
			LogEvent(logwarn, 1, topIni->getFilePath(), " repeats ",
				setting, " ", NewName(configTpl->getFilePath()));
			DeleteName(configTplName);
			configTplName = NULL;
			delete configTpl;
			break;  // deja vu, end of the line
		}

		topIni = configTpl;  // step up
		if (topIni->Section("Templates")
		 && topIni->Find("Scope"))
			topIni->Scope = topIni->StrRight();
		DeleteName(configTplName);
		configTplName = NULL;
		IniFileList.add(topIni, ++IniLevel);
		IniNameList.add(topIni->getBaseName(), IniLevel);
		IniChainList.add(topIni->getFilePath(), IniLevel);
	}

	// topIni is now at the top of the chain, and
	// bottomIni is at the bottom, which may be same.
	if (link) {
		DCirfile *ifl = bottomIni;
		DCirfile *ift = NULL;
		for (long ilev = 1; ilev < IniLevel; ilev++) {
			ift = (DCirfile *) IniFileList.find(ilev + 1);
			if (!ift)
				break;
			ift->SetSecFile(ifl);
			ifl = ift;
			//if (ifl == topIni)
			//	break;
		}
	}

	WriteIniChain(setting);

	if (currdrive != startdrive)
		_chdrive(startdrive);
	if (stricmp(startdir, currdir))
		_chdir(startdir);

	if (this != topIni) {
		topIni->IniFileList = IniFileList;
		topIni->IniNameList = IniNameList;
		topIni->IniChainList = IniChainList;
		topIni->IniLevel = IniLevel;
	}

	return topIni;
}
コード例 #18
0
ファイル: tiio_3gpM.cpp プロジェクト: AmEv7Fam/opentoonz
void TLevelWriter3gp::saveSoundTrack(TSoundTrack *st)
{
	Track theTrack;
	OSErr myErr = noErr;
	SoundDescriptionV1Handle mySampleDesc;
	Media myMedia;
	Handle myDestHandle;
	SoundComponentData sourceInfo;
	SoundComponentData destInfo;
	SoundConverter converter;
	CompressionInfo compressionInfo;
	int err;

	if (!st)
		throw TException("null reference to soundtrack");

	if (st->getBitPerSample() != 16) {
		throw TImageException(m_path, "Only 16 bits per sample is supported");
	}

	theTrack = NewMovieTrack(m_movie, 0, 0, kFullVolume);
	myErr = GetMoviesError();
	if (myErr != noErr)
		throw TImageException(m_path, "error creating audio track");

	FailIf(myErr != noErr, CompressErr);

	myDestHandle = NewHandle(0);

	FailWithAction(myDestHandle == NULL, myErr = MemError(), NoDest);

	*myDestHandle = (char *)st->getRawData();

	//////////
	//
	// create a media for the track passed in
	//
	//////////

	// set new track to be a sound track
	m_soundDataRef = nil;
	m_hSoundMovieData = NewHandle(0);

	// Construct the Handle data reference
	err = PtrToHand(&m_hSoundMovieData, &m_soundDataRef, sizeof(Handle));

	if ((err = GetMoviesError() != noErr))
		throw TImageException(getFilePath(), "can't create Data Ref");

	myMedia = NewTrackMedia(theTrack, SoundMediaType, st->getSampleRate(), m_soundDataRef, HandleDataHandlerSubType); //track->rate >> 16

	myErr = GetMoviesError();
	if (myErr != noErr)
		throw TImageException(m_path, "error setting audio track");
	FailIf(myErr != noErr, Exit);

	// start a media editing session
	myErr = BeginMediaEdits(myMedia);
	if (myErr != noErr)
		throw TImageException(m_path, "error beginning edit audio track");

	FailIf(myErr != noErr, Exit);

	sourceInfo.flags = 0x0;
	sourceInfo.format = kSoundNotCompressed;
	sourceInfo.numChannels = st->getChannelCount();
	sourceInfo.sampleSize = st->getBitPerSample();
	sourceInfo.sampleRate = st->getSampleRate();
	sourceInfo.sampleCount = st->getSampleCount();
	sourceInfo.buffer = (unsigned char *)st->getRawData();
	sourceInfo.reserved = 0x0;

	destInfo.flags = kNoSampleRateConversion | kNoSampleSizeConversion |
					 kNoSampleFormatConversion | kNoChannelConversion |
					 kNoDecompression | kNoVolumeConversion |
					 kNoRealtimeProcessing;

	destInfo.format = k16BitNativeEndianFormat;

	destInfo.numChannels = st->getChannelCount();
	destInfo.sampleSize = st->getBitPerSample();
	destInfo.sampleRate = st->getSampleRate();
	destInfo.sampleCount = st->getSampleCount();
	destInfo.buffer = (unsigned char *)st->getRawData();
	destInfo.reserved = 0x0;

	SoundConverterOpen(&sourceInfo, &destInfo, &converter);

	myErr = SoundConverterGetInfo(converter, siCompressionFactor, &compressionInfo);
	if (myErr != noErr)
		throw TImageException(m_path, "error getting audio converter info");

	myErr = GetCompressionInfo(fixedCompression, sourceInfo.format, sourceInfo.numChannels, sourceInfo.sampleSize, &compressionInfo);
	if (myErr != noErr)
		throw TImageException(m_path, "error getting audio compression info");
	FailIf(myErr != noErr, ConverterErr);

	compressionInfo.bytesPerFrame = compressionInfo.bytesPerPacket * destInfo.numChannels;

	//////////
	//
	// create a sound sample description
	//
	//////////

	// use the SoundDescription format 1 because it adds fields for data size information
	// and is required by AddSoundDescriptionExtension if an extension is required for the compression format

	mySampleDesc = (SoundDescriptionV1Handle)NewHandleClear(sizeof(SoundDescriptionV1));
	FailWithAction(myErr != noErr, myErr = MemError(), Exit);

	(**mySampleDesc).desc.descSize = sizeof(SoundDescriptionV1);
	(**mySampleDesc).desc.dataFormat = destInfo.format;
	(**mySampleDesc).desc.resvd1 = 0;
	(**mySampleDesc).desc.resvd2 = 0;
	(**mySampleDesc).desc.dataRefIndex = 1;
	(**mySampleDesc).desc.version = 1;
	(**mySampleDesc).desc.revlevel = 0;
	(**mySampleDesc).desc.vendor = 0;
	(**mySampleDesc).desc.numChannels = destInfo.numChannels;
	(**mySampleDesc).desc.sampleSize = destInfo.sampleSize;
	(**mySampleDesc).desc.compressionID = 0;
	(**mySampleDesc).desc.packetSize = 0;
	(**mySampleDesc).desc.sampleRate = st->getSampleRate() << 16;
	(**mySampleDesc).samplesPerPacket = compressionInfo.samplesPerPacket;
	(**mySampleDesc).bytesPerPacket = compressionInfo.bytesPerPacket;
	(**mySampleDesc).bytesPerFrame = compressionInfo.bytesPerFrame;
	(**mySampleDesc).bytesPerSample = compressionInfo.bytesPerSample;

	//////////
	//
	// add samples to the media
	//
	//////////

	myErr = AddMediaSample(myMedia, myDestHandle,
						   0,
						   destInfo.sampleCount * compressionInfo.bytesPerFrame,
						   1,
						   (SampleDescriptionHandle)mySampleDesc,
						   destInfo.sampleCount * compressionInfo.samplesPerPacket,
						   0,
						   NULL);

	if (myErr != noErr)
		throw TImageException(m_path, "error adding audio samples");

	FailIf(myErr != noErr, MediaErr);

	myErr = EndMediaEdits(myMedia);
	if (myErr != noErr)
		throw TImageException(m_path, "error ending audio edit");

	FailIf(myErr != noErr, MediaErr);

	//////////
	//
	// insert the media into the track
	//
	//////////

	myErr = InsertMediaIntoTrack(theTrack, 0, 0, GetMediaDuration(myMedia), fixed1);
	if (myErr != noErr)
		throw TImageException(m_path, "error inserting audio track");

	FailIf(myErr != noErr, MediaErr);
	goto Done;

ConverterErr:
NoDest:
CompressErr:
Exit:

Done:

MediaErr:
	if (mySampleDesc != NULL)
		DisposeHandle((Handle)mySampleDesc);

	if (converter)
		SoundConverterClose(converter);

	if (myErr != noErr)
		throw TImageException(m_path, "error saving audio track");
}
コード例 #19
0
ファイル: DataManager.cpp プロジェクト: wctstc/EarthExplore
bool CBlockMatrix::LoadConfig()
{
#ifdef _FILESYSTEM
  char* fileName = "BlockMatrix.txt";
  if (!IsFileExist(fileName, TXT_PATH))
    copyFile(fileName, TXT_PATH);
  string fullFilePath = getFilePath(fileName, TXT_PATH);
  int fileLen = strlen(fullFilePath.c_str());
  if (!fileLen)
    return false;
  char buffer[256];  
  ifstream in(fullFilePath);  
  if (! in.is_open())  
  { 
    cout << "Error opening file BlockMatrix"; 
    return false; 
  }
  int Line = 0;
  while (EOF != in.peek() )  
  { 
    in.getline (buffer,256);
    GParse GP(buffer);
    BlockMap Item;
    Item.Idx = GP.getInt();
    Item.Id = GP.getInt();
    BlockMaps.push_back(Item);
  }
  return true;
#endif;
  /*
  char* fileName = "BlockMatrix.lua";
  if (!IsFileExist(fileName, LUA_PATH))
    copyFile(fileName, LUA_PATH);
  string fullFilePath = getFilePath(fileName, LUA_PATH);
  int fileLen = strlen(fullFilePath.c_str());
  if (!fileLen)
    return false;
  if (luaL_dofile(GLuaState, fullFilePath.c_str()))
  {
    CCLOG("BlockMatrix.lua file error!");
    return false;
  }
  CLuaObject LuaObject = CLuaObject("BlockMatrix", GLuaState);
  BEGIN_LUA(LuaObject)
  {
    BlockMap Item;
    Item.Idx = LuaObject.getInt("Idx");
    Item.Id = LuaObject.getInt("Id");
    BlockMaps.push_back(Item);
  }
  END_LUA(LuaObject)

  CLuaObject LuaProObject = CLuaObject("PropertySet", GLuaState);
  BEGIN_LUA(LuaProObject)
  {
    PropertySet Property;
    Property.Idx = LuaProObject.getInt("Idx");
    Property.Id = LuaProObject.getInt("Id");
    PropertySets.push_back(Property);
  }
  END_LUA(LuaProObject)*/
  return true;
}
コード例 #20
0
int stmd_RuleEntSelect(int time_type, int duration, char *table_type)
{
    char        condBuf[4096], tmpBuf[1024];
    int         sts_code;
    char        str_time[10];

    char        query[4096], query_head[4096]; 
    MYSQL_RES   *result;
    MYSQL_ROW   row;

    time_t      now;
    char        tm[DIR_NUM][8];
    char        path[60];
    char        fileName[60];
    FILE        *fp;

    int         i;
	char title[4][16] = {"SYSTEM", "ITEM", "Session", "Block"};
	char title1[5][16] = {"", "", "UpStream(Mbps)", "DnStream(Mbps)", "Total(Mbps)"};
	char title2[5][16] = {"", "", "UpByte(MBytes)", "DnByte(MBytes)", "Total(MBytes)"};

    int row_index;
    char SysName[2][8];
    int realSysCnt =0;
    int realItemCnt =0, row_cnt=0 ;

	int     snd_cnt = 1;


    now = time(0);
    if(time_type != STMD_WEEK)
        now = now - (printTIME[time_type]*60) - STAT_OFFSET_UNIT;
    else
        now = now - (printTIME[time_type]*60);

    getFilePath (path, tm, &now); // ~/LOG/STAT 까지 만든다.
    makeDirectory (time_type,path,tm);

    sprintf(fileName, "%s", path );
    makeFileName ( fileName, STMD_RULE_ENT, time_type, tm );

    if ( ( fp = fopen(fileName, APPEND ) ) == NULL )
	{
        sprintf(trcBuf, "%s Open Fail\n", fileName);
        trclib_writeLog(FL, trcBuf);
        return -1;
    }

	//char title[4][16] = {"SYSTEM", "ITEM", "Session", "Block"};
	//char title1[5][16] = {"", "", "UpStream(Mbps)", "DnStream(Mbps)", "Total(Mbps)"};
	//char title2[5][16] = {"", "", "UpByte(MBytes)", "DnByte(MBytes)", "Total(MBytes)"};
    switch (time_type) {
        case    STMD_HOUR :
            sts_code = STSCODE_STM_PERIODIC_RULEENT_HOUR;
            sprintf(str_time, "%s", STMD_STR_HOUR);
			sprintf(query_head, "SELECT record_source, rule_ent_id, rule_ent_name, "
					" IFNULL(SUM(session),0), IFNULL(SUM(block_cnt),0), "
					" ROUND(IFNULL(SUM(upstream_volume)*8/1024/1024/3600,0),3), "
					" ROUND(IFNULL(SUM(downstream_volume)*8/1024/1024/3600,0),3), "
					" ROUND((IFNULL(SUM(upstream_volume),0) + IFNULL(SUM(downstream_volume),0))*8/1024/1024/3600,3), "
					" ROUND(IFNULL(SUM(upstream_volume)/1024/1024 ,0),3), "
					" ROUND(IFNULL(SUM(downstream_volume)/1024/1024 ,0),3), "
					" ROUND((IFNULL(SUM(upstream_volume),0) + IFNULL(SUM(downstream_volume),0))/1024/1024,3) "
                	" from %s ", table_type);
            break;
        case    STMD_DAY :
            sts_code = STSCODE_STM_PERIODIC_RULEENT_DAY;
            sprintf(str_time, "%s", STMD_STR_DAY);
			sprintf(query_head, "SELECT record_source, rule_ent_id, rule_ent_name, "
					" IFNULL(SUM(session),0), IFNULL(SUM(block_cnt),0), "
					" ROUND(IFNULL(SUM(upstream_volume)*8/1024/1024/86400,0),3), "
					" ROUND(IFNULL(SUM(downstream_volume)*8/1024/1024/86400,0),3), "
					" ROUND((IFNULL(SUM(upstream_volume),0) + IFNULL(SUM(downstream_volume),0))*8/1024/1024/86400,3), "
					" ROUND(IFNULL(SUM(upstream_volume)/1024/1024 ,0),3), "
					" ROUND(IFNULL(SUM(downstream_volume)/1024/1024 ,0),3), "
					" ROUND((IFNULL(SUM(upstream_volume),0) + IFNULL(SUM(downstream_volume),0))/1024/1024,3) "
                	" from %s ", table_type);
            break;
        case    STMD_WEEK :
            sts_code = STSCODE_STM_PERIODIC_RULEENT_WEEK;
            sprintf(str_time, "%s", STMD_STR_WEEK);
			sprintf(query_head, "SELECT record_source, rule_ent_id, rule_ent_name, "
					" IFNULL(SUM(session),0), IFNULL(SUM(block_cnt),0), "
					" ROUND(IFNULL(SUM(upstream_volume)*8/1024/1024/86400*7,0),3), "
					" ROUND(IFNULL(SUM(downstream_volume)*8/1024/1024/86400*7,0),3), "
					" ROUND((IFNULL(SUM(upstream_volume),0) + IFNULL(SUM(downstream_volume),0))*8/1024/1024/86400*7,3), "
					" ROUND(IFNULL(SUM(upstream_volume)/1024/1024 ,0),3), "
					" ROUND(IFNULL(SUM(downstream_volume)/1024/1024 ,0),3), "
					" ROUND((IFNULL(SUM(upstream_volume),0) + IFNULL(SUM(downstream_volume),0))/1024/1024,3) "
                	" from %s ", table_type);
            break;
        case    STMD_MONTH :
            sts_code = STSCODE_STM_PERIODIC_RULEENT_MONTH;
            sprintf(str_time, "%s", STMD_STR_MONTH);
			sprintf(query_head, "SELECT record_source, rule_ent_id, rule_ent_name, "
					" IFNULL(SUM(session),0), IFNULL(SUM(block_cnt),0), "
					" ROUND(IFNULL(SUM(upstream_volume)*8/1024/1024/86400*30,0),3), "
					" ROUND(IFNULL(SUM(downstream_volume)*8/1024/1024/86400*30,0),3), "
					" ROUND((IFNULL(SUM(upstream_volume),0) + IFNULL(SUM(downstream_volume),0))*8/1024/1024/86400*30,3), "
					" ROUND(IFNULL(SUM(upstream_volume)/1024/1024 ,0),3), "
					" ROUND(IFNULL(SUM(downstream_volume)/1024/1024 ,0),3), "
					" ROUND((IFNULL(SUM(upstream_volume),0) + IFNULL(SUM(downstream_volume),0))/1024/1024,3) "
                	" from %s ", table_type);
            break;
    }

    sprintf(condBuf,"    %s %s\n    S%04d RULE ENTRY PERIODIC STATISTICS MESSAGE\n",
        "SCE", // 현재는 OMP로 고정하지만 실질적인 시스템 이름으로 변경 필요 hslim_oper
        commlib_printTStamp(), // 현재시각 time stamp (년,월,일,시,분,초,요일)
        sts_code);

    sprintf(tmpBuf, "    PERIOD = %s\n    MEASURETIME = %s  -  %s\n\n",
        str_time,
        get_period_start_time(time_type), get_period_end_time(time_type));
    strcat(condBuf,tmpBuf);

	sprintf(tmpBuf, "    =======================================================================================\n");
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %6s %-38s %-15s %-15s \n","",title[0],title[1],title[2],title[3]);
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %6s %-38s %-15s %-15s %-15s\n","","","",title1[2],title1[3],title1[4]);
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "%3s %6s %-38s %-15s %-15s %-15s\n","","","",title2[2],title2[3],title2[4]);
	strcat(condBuf, tmpBuf);
	sprintf(tmpBuf, "    =======================================================================================\n");
	strcat(condBuf, tmpBuf);

    for(i=0; i<SCE_CNT; i++ )
	{
        sprintf(SysName[i], "%s", g_stSCE[i].sce_name);
        realSysCnt++;
    }

    for(i = 0; i < realSysCnt; i++)
	{
		realItemCnt = g_stSCEEntry[i].ruleEntryCnt;

        sprintf(query, "%s  "
                " where record_source = '%s' AND (stat_date = '%s') "
				" group by record_source, rule_ent_id, rule_ent_name "
				" order by record_source, rule_ent_id, rule_ent_name ", query_head,
            	SysName[i], get_period_select_time(time_type));

		logPrint(trcLogId, FL, "periodic query: %s \n",query);

        if ( trcLogFlag == TRCLEVEL_SQL ) 
		{
            sprintf(trcBuf, "query = %s\n", query);
            trclib_writeLog(FL, trcBuf);
        }

		if (stmd_mysql_query (query) < 0) {
            sprintf(trcBuf,">>> mysql_query fail; query:%s, err=%s\n", query,mysql_error(conn));
            trclib_writeLogErr (FL,trcBuf);
            if(fp != NULL) fclose(fp);
            return -1;
        }

        row_cnt = 0;                                                                                              
        result = mysql_store_result(conn);
        while( (row = mysql_fetch_row(result)) != NULL)
		{
			row_index = 3;

			if(strlen(condBuf) > 3000) {
	            strcat(condBuf, "\nCONTINUE\n");
				stmd_txMsg2Cond (condBuf, (sts_code - STSCODE_TO_MSGID_STATISTICS), 1, snd_cnt++);
        		fprintf (fp, "%s",condBuf);
				memset(condBuf, 0x00, sizeof(condBuf));
			}

			if( row_cnt == 0 )
			{
				sprintf(tmpBuf, "%3s %6s %-38s %-15s %-15s \n",
						"", row[0], row[2], row[row_index],row[row_index+1]);
				strcat(condBuf, tmpBuf);
			}
			else
			{
				sprintf(tmpBuf, "%3s %6s %-38s %-15s %-15s\n",
						"","", row[2], row[row_index],row[row_index+1]);
				strcat(condBuf, tmpBuf);
			}
			if(strlen(condBuf) > 3000) {
	            strcat(condBuf, "\nCONTINUE\n");
				stmd_txMsg2Cond (condBuf, (sts_code - STSCODE_TO_MSGID_STATISTICS), 1, snd_cnt++);
        		fprintf (fp, "%s",condBuf);
				memset(condBuf, 0x00, sizeof(condBuf));
			}

            sprintf(tmpBuf, "%3s %6s %-28s %15s %15s %15s\n",
                    "", "", "", row[row_index+2], row[row_index+3], row[row_index+4] );
            strcat(condBuf, tmpBuf);                                             

			if(strlen(condBuf) > 3000) {
	            strcat(condBuf, "\nCONTINUE\n");
				stmd_txMsg2Cond (condBuf, (sts_code - STSCODE_TO_MSGID_STATISTICS), 1, snd_cnt++);
        		fprintf (fp, "%s",condBuf);
				memset(condBuf, 0x00, sizeof(condBuf));
			}

            sprintf(tmpBuf, "%3s %6s %-28s %15s %15s %15s\n",
                    "", "", "", row[row_index+5], row[row_index+6], row[row_index+7] );
            strcat(condBuf, tmpBuf);                                             

		
			if(strlen(condBuf) > 3000) {
	            strcat(condBuf, "\nCONTINUE\n");
				stmd_txMsg2Cond (condBuf, (sts_code - STSCODE_TO_MSGID_STATISTICS), 1, snd_cnt++);
        		fprintf (fp, "%s",condBuf);
				memset(condBuf, 0x00, sizeof(condBuf));
			}
			row_cnt++;
        }
        mysql_free_result(result);

		// ?????
		// 여기는 수행되면 안됨. 5분 통계에서 이미 다 들어 가있음. 
#if 0
        if( row_cnt == 0 ) // no query result set
        {
            for( j = 0; j < realItemCnt; j++ )
            {
				if( g_stSCEEntry[i].stEntry[j].real == 1 && g_stSCEEntry[i].stEntry[j].eName != NULL )
				{
					if( j == 0 )
					{
						sprintf(tmpBuf, "%3s %6s %-38s %-15s %-15s\n",
								"", SysName[i], g_stSCEEntry[i].stEntry[j].eName, "0","0","0");
						strcat(condBuf, tmpBuf);
						sprintf(tmpBuf, "%3s %6s %-38s %-15s %-15s %-15s\n",
								"", "", "", "0.000","0.000","0.000");
						strcat(condBuf, tmpBuf);                                                             
						sprintf(tmpBuf, "%3s %6s %-38s %-15s %-15s %-15s\n",
								"", "", "", "0","0","0");
						strcat(condBuf, tmpBuf);
						sprintf(tmpBuf, "    --------------------------------------------------------------------------------------\n");
						strcat(condBuf, tmpBuf);
					}
					else
					{
						sprintf(tmpBuf, "%3s %6s %-38s %-15s %-15s\n",
								"", "", g_stSCEEntry[i].stEntry[j].eName, "0","0","0");
						strcat(condBuf, tmpBuf);
						sprintf(tmpBuf, "%3s %6s %-38s %-15s %-15s %-15s\n",
								"", "", "", "0.000","0.000","0.000");
						strcat(condBuf, tmpBuf);                                                             
						sprintf(tmpBuf, "%3s %6s %-38s %-15s %-15s %-15s\n",
								"", "", "", "0","0","0");
						strcat(condBuf, tmpBuf);
						sprintf(tmpBuf, "    ---------------------------------------------------------------------------------------\n");
					}
				}
				if(strlen(condBuf) > 3000) {
					stmd_cron_txMsg2Cond (condBuf, (sts_code - STSCODE_TO_MSGID_STATISTICS), 1, snd_cnt);
        			fprintf (fp, "%s",condBuf);
					sprintf(condBuf, "");
				}
            }
        }
#endif

		sprintf(tmpBuf, "    =======================================================================================\n");
		strcat(condBuf, tmpBuf);

    }

    sprintf(tmpBuf, "    COMPLETED\n\n\n");
    strcat(condBuf, tmpBuf);

    if(fp != NULL) 
	{
        fprintf (fp, "%s",condBuf);
        fclose(fp);
    }
    
    stmd_txMsg2Cond(condBuf, (sts_code - STSCODE_TO_MSGID_STATISTICS), 0, snd_cnt);
    
    return 1;
}
コード例 #21
0
ファイル: theme_loader.cpp プロジェクト: AsamQi/vlc
bool ThemeLoader::extractFileInZip( unzFile file, const string &rootDir,
                                    bool isWsz )
{
    // Read info for the current file
    char filenameInZip[256];
    unz_file_info fileInfo;
    if( unzGetCurrentFileInfo( file, &fileInfo, filenameInZip,
                               sizeof( filenameInZip), NULL, 0, NULL, 0 )
        != UNZ_OK )
    {
        return false;
    }

    // Convert the file name to lower case, because some winamp skins
    // use the wrong case...
    if( isWsz )
        for( size_t i = 0; i < strlen( filenameInZip ); i++ )
            filenameInZip[i] = tolower( (unsigned char)filenameInZip[i] );

    // Allocate the buffer
    void *pBuffer = malloc( ZIP_BUFFER_SIZE );
    if( !pBuffer )
        return false;

    // Get the path of the file
    OSFactory *pOsFactory = OSFactory::instance( getIntf() );
    string fullPath = rootDir
        + pOsFactory->getDirSeparator()
        + fixDirSeparators( filenameInZip );
    string basePath = getFilePath( fullPath );

    // Extract the file if is not a directory
    if( basePath != fullPath )
    {
        if( unzOpenCurrentFile( file ) )
        {
            free( pBuffer );
            return false;
        }
        makedir( basePath.c_str() );
        FILE *fout = fopen( fullPath.c_str(), "wb" );
        if( fout == NULL )
        {
            msg_Err( getIntf(), "error opening %s", fullPath.c_str() );
            free( pBuffer );
            return false;
        }

        // Extract the current file
        int n;
        do
        {
            n = unzReadCurrentFile( file, pBuffer, ZIP_BUFFER_SIZE );
            if( n < 0 )
            {
                msg_Err( getIntf(), "error while reading zip file" );
                fclose(fout);
                free( pBuffer );
                return false;
            }
            else if( n > 0 )
            {
                if( fwrite( pBuffer, n , 1, fout) != 1 )
                {
                    msg_Err( getIntf(), "error while writing %s",
                             fullPath.c_str() );
                    fclose(fout);
                    free( pBuffer );
                    return false;
                }
            }
        } while( n > 0 );

        fclose(fout);

        if( unzCloseCurrentFile( file ) != UNZ_OK )
        {
            free( pBuffer );
            return false;
        }
    }

    free( pBuffer );
    return true;
}
コード例 #22
0
ファイル: filedialog.cpp プロジェクト: h2so5/PaintField
QString FileDialog::getFilePath(QWidget *parent, const QString &title, Mode mode, const QString &filterText, const QStringList &filterSuffixes)
{
	return getFilePath(parent, title, mode, { QPair<QString, QStringList>(filterText, filterSuffixes) });
}
コード例 #23
0
bool CCompiler::setCompiler(const string& compiler)
{
    mCompilerName = getFileName(compiler);
    mCompilerLocation = getFilePath(compiler);
    return true;
}
コード例 #24
0
ファイル: filedialog.cpp プロジェクト: h2so5/PaintField
QString FileDialog::getOpenFilePath(QWidget *parent, const QString &title, const QString &filterText, const QStringList &filterSuffixes)
{
	return getFilePath(parent, title, OpenFile, filterText, filterSuffixes);
}
コード例 #25
0
ファイル: scriptmanager.cpp プロジェクト: Fir3element/035
bool ScriptingManager::loadFromXml(const std::string& file, bool& enabled)
{
	std::string modPath = getFilePath(FILE_TYPE_MOD, file);
	xmlDocPtr doc = xmlParseFile(modPath.c_str());
	if(!doc)
	{
		std::cout << "[Error - ScriptingManager::loadFromXml] Cannot load mod " << modPath << std::endl;
		std::cout << getLastXMLError() << std::endl;
		return false;
	}

	int32_t intValue;
	std::string strValue;

	xmlNodePtr p, root = xmlDocGetRootElement(doc);
	if(xmlStrcmp(root->name,(const xmlChar*)"mod"))
	{
		std::cout << "[Error - ScriptingManager::loadFromXml] Malformed mod " << modPath << std::endl;
		std::cout << getLastXMLError() << std::endl;

		xmlFreeDoc(doc);
		return false;
	}

	if(!readXMLString(root, "name", strValue))
	{
		std::cout << "[Warning - ScriptingManager::loadFromXml] Empty name in mod " << modPath << std::endl;
		xmlFreeDoc(doc);
		return false;
	}

	ModBlock mod;
	mod.enabled = false;
	if(readXMLString(root, "enabled", strValue) && booleanString(strValue))
		mod.enabled = true;

	mod.file = file;
	mod.name = strValue;
	if(readXMLString(root, "author", strValue))
		mod.author = strValue;
	if(readXMLString(root, "version", strValue))
		mod.version = strValue;
	if(readXMLString(root, "contact", strValue))
		mod.contact = strValue;

	if(mod.enabled)
	{
		std::string scriptsPath = getFilePath(FILE_TYPE_MOD, "scripts/");
		p = root->children;
		while(p)
		{
			if(!xmlStrcmp(p->name, (const xmlChar*)"quest"))
				Quests::getInstance()->parseQuestNode(p, modsLoaded);
			else if(!xmlStrcmp(p->name, (const xmlChar*)"outfit"))
				Outfits::getInstance()->parseOutfitNode(p); //TODO: duplicates (I just don't remember how it works here)
			else if(!xmlStrcmp(p->name, (const xmlChar*)"vocation"))
				Vocations::getInstance()->parseVocationNode(p); //duplicates checking is dangerous, shouldn't be performed
			else if(!xmlStrcmp(p->name, (const xmlChar*)"group"))
				Groups::getInstance()->parseGroupNode(p); //duplicates checking is dangerous, shouldn't be performed
			else if(!xmlStrcmp(p->name, (const xmlChar*)"raid"))
				Raids::getInstance()->parseRaidNode(p, modsLoaded, FILE_TYPE_MOD);
			else if(!xmlStrcmp(p->name, (const xmlChar*)"spawn"))
				Spawns::getInstance()->parseSpawnNode(p, modsLoaded);
			else if(!xmlStrcmp(p->name, (const xmlChar*)"channel"))
				g_chat.parseChannelNode(p); //TODO: duplicates (channel destructor needs sending self close to users)
			else if(!xmlStrcmp(p->name, (const xmlChar*)"monster"))
			{
				std::string file, name;
				if(readXMLString(p, "file", file) && readXMLString(p, "name", name))
				{
					file = getFilePath(FILE_TYPE_MOD, "monster/" + file);
					g_monsters.loadMonster(file, name, true);
				}
			}
			else if(!xmlStrcmp(p->name, (const xmlChar*)"item"))
			{
				if(readXMLInteger(p, "id", intValue))
					Item::items.parseItemNode(p, intValue); //duplicates checking isn't necessary here
			}
			if(!xmlStrcmp(p->name, (const xmlChar*)"description") || !xmlStrcmp(p->name, (const xmlChar*)"info"))
			{
				if(parseXMLContentString(p->children, strValue))
				{
					replaceString(strValue, "\t", "");
					mod.description = strValue;
				}
			}
			else if(!xmlStrcmp(p->name, (const xmlChar*)"lib") || !xmlStrcmp(p->name, (const xmlChar*)"config"))
			{
				if(!readXMLString(p, "name", strValue))
				{
					std::cout << "[Warning - ScriptingManager::loadFromXml] Lib without name in mod " << strValue << std::endl;
					p = p->next;
					continue;
				}

				toLowerCaseString(strValue);
				std::string strLib;
				if(parseXMLContentString(p->children, strLib))
				{
					LibMap::iterator it = libMap.find(strValue);
					if(it == libMap.end())
					{
						LibBlock lb;
						lb.first = file;
						lb.second = strLib;

						libMap[strValue] = lb;
					}
					else
						std::cout << "[Warning - ScriptingManager::loadFromXml] Duplicated lib in mod "
							<< strValue << ", previously declared in " << it->second.first << std::endl;
				}
			}
			else if(!g_actions->parseEventNode(p, scriptsPath, modsLoaded))
			{
				if(!g_talkActions->parseEventNode(p, scriptsPath, modsLoaded))
				{
					if(!g_moveEvents->parseEventNode(p, scriptsPath, modsLoaded))
					{
						if(!g_creatureEvents->parseEventNode(p, scriptsPath, modsLoaded))
						{
							if(!g_globalEvents->parseEventNode(p, scriptsPath, modsLoaded))
							{
								if(!g_spells->parseEventNode(p, scriptsPath, modsLoaded))
									g_weapons->parseEventNode(p, scriptsPath, modsLoaded);
							}
						}
					}
				}
			}

			p = p->next;
		}
	}

	enabled = mod.enabled;
	modMap[mod.name] = mod;
	xmlFreeDoc(doc);
	return true;
}
コード例 #26
0
ファイル: filedialog.cpp プロジェクト: h2so5/PaintField
QString FileDialog::getSaveFilePath(QWidget *parent, const QString &title, const QString &filterText, const QString &filterSuffix)
{
	return getFilePath(parent, title, SaveFile, filterText, {filterSuffix});
}
コード例 #27
0
ファイル: appnet_response.c プロジェクト: lchb369/appnet
void httpResponseStaticProc( httpHeader *req_header )
{
	
	int len,cllen,ctlen;
	char path[1024] =
			{0};
	headerOut header_out;
	memset( &header_out , 0 , sizeof( header_out ) );
	header_out.req = req_header;
	
	getFilePath( req_header->uri , path );
	struct stat stat_file;
	int ret = stat( path , &stat_file );
	
	if (ret < 0)
	{
		respErrorPage( &header_out , 404 );
		return;
	}
	
	createCommonHeader( &header_out , 200 );
	headerAppendLength( &header_out , stat_file.st_size );
	appendRespHeader( &header_out , HEADER_END_LINE );
	
	int nwritten = write( req_header->connfd , header_out.data , header_out.length );
	if (nwritten <= 0)
	{
		printf( "I/O error writing to client connfd=%d,len=%d: %s \n" ,
				req_header->connfd , header_out.length , strerror( errno ) );
		return;
	}
	
	if (req_header->nobody == AE_TRUE)
	{
		httpClose( req_header , 1 );
		return;
	}
	
	int fd = open( path , O_RDONLY );
	if (fd < 0)
	{
		printf( "Open file Error:%s,errno=%d \n" , strerror( errno ) , errno );
		return;
	}
	
	// setsockopt (fd, SOL_TCP, TCP_CORK, &on, sizeof (on));
	off_t offset = 0;
	int force_close = 0;
	while (offset < stat_file.st_size)
	{
		int sendn =
				sendfile( req_header->connfd , fd , &offset , stat_file.st_size - offset );
		
		if (sendn < 0)
		{
			//如果socket缓冲区不可用,则挂起等待可用
			if (errno == EAGAIN || errno == EINTR)
			{
				if (anetHandup( req_header->connfd , 5000 , AE_WRITABLE ) < 0)
				{
					//如果超时,退出
					printf( "Sendfile anetHandup timeout.......\n" );
					force_close = 1;
					break;
				}
				else
				{
					//否则继续发送
					continue;
				}
			}
			else
			{
				break;
			}
		}
	}
	close( fd );
	httpClose( req_header , force_close );
}
コード例 #28
0
ファイル: tools.win.cpp プロジェクト: UIKit0/et-engine
std::string et::applicationPath()
{
	char ExePath[MAX_PATH] = { };
	GetModuleFileNameA(nullptr, ExePath, MAX_PATH);
	return getFilePath(normalizeFilePath(ExePath));
}
コード例 #29
0
int main(int argc, char** argv)
{
	// graphite::AlignmentManager< HTSLibAlignmentReader > tmp;
	unsigned long milliseconds_since_epoch = std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1);
	graphite::Params params;
	params.parseGSSW(argc, argv);
	if (params.showHelp() || !params.validateRequired())
	{
		params.printHelp();
		exit(0);
	}
	auto bamPaths = params.getBAMPaths();
	auto fastaPath = params.getFastaPath();
	auto vcfPaths = params.getInVCFPaths();
	auto outputDirectory = params.getOutputDirectory();
	auto paramRegionPtr = params.getRegion();
	auto swPercent = params.getPercent();
	auto threadCount = params.getThreadCount();
	auto matchValue = params.getMatchValue();
	auto misMatchValue = params.getMisMatchValue();
	auto gapOpenValue = params.getGapOpenValue();
	auto gapExtensionValue = params.getGapExtensionValue();
	auto excludeDuplicates = params.getExcludeDuplicates();
	auto graphSize = params.getGraphSize();
	graphite::FileType fileType = graphite::FileType::ASCII;

	graphite::ThreadPool::Instance()->setThreadCount(threadCount);

	std::vector< graphite::Region::SharedPtr > regionPtrs;
	if (paramRegionPtr == nullptr)
	{
		regionPtrs = graphite::VCFFileReader::GetAllRegionsInVCF(vcfPaths);
	}
	else
	{
		regionPtrs.emplace_back(paramRegionPtr);
	}

	uint32_t readLength = graphite::BamAlignmentManager::GetReadLength(bamPaths);
	graphite::SampleManager::SharedPtr sampleManagerPtr = std::make_shared< graphite::SampleManager >(graphite::BamAlignmentManager::GetSamplePtrs(bamPaths));

	std::unordered_map< std::string, graphite::IFileWriter::SharedPtr > vcfoutPaths;
	for (auto vcfPath : vcfPaths)
	{
		std::string path = vcfPath.substr(vcfPath.find_last_of("/") + 1);
		std::string filePath = outputDirectory + "/" + path;
		uint32_t counter = 1;
		while (graphite::IFile::fileExists(filePath, false))
		{
			std::string extension = vcfPath.substr(vcfPath.find_last_of(".") + 1);
			std::string fileNameWithoutExtension = path.substr(0, path.find_last_of("."));
			filePath = outputDirectory + "/" + fileNameWithoutExtension + "." + std::to_string(counter) + "." + extension;
			++counter;
		}
		// filePath += ".tmp";
		graphite::IFileWriter::SharedPtr fileWriterPtr;
		if (fileType == graphite::FileType::BGZF)
		{
			fileWriterPtr = std::make_shared< graphite::BGZFFileWriter >(filePath);
		}
		else
		{
			fileWriterPtr = std::make_shared< graphite::ASCIIFileWriter >(filePath);
		}
		fileWriterPtr->open();
		vcfoutPaths[vcfPath] = fileWriterPtr;
	}

	std::unordered_set< std::string > outputPaths;
	bool firstTime = true;

	for (uint32_t regionCount = 0; regionCount < regionPtrs.size(); ++regionCount)
	{
		auto alignmentReaderManagerPtr = std::make_shared< graphite::AlignmentReaderManager< graphite::BamAlignmentReader > >(bamPaths, threadCount); // this used to go above this loop but it caused issues with loading bam regions from out-of-order VCFs
		auto regionPtr = regionPtrs[regionCount];
		auto fastaReferencePtr = std::make_shared< graphite::FastaReference >(fastaPath, regionPtr);

		// load variants from vcf
		auto variantManagerPtr = std::make_shared< graphite::VCFManager >(vcfPaths, regionPtr, fastaReferencePtr, readLength);
		variantManagerPtr->asyncLoadVCFs(); // begin the process of loading the vcfs asynchronously

		variantManagerPtr->waitForVCFsToLoadAndProcess(); // wait for vcfs to load into memory

		// load bam alignments
		auto bamAlignmentManager = std::make_shared< graphite::BamAlignmentManager >(sampleManagerPtr, regionPtr, alignmentReaderManagerPtr, excludeDuplicates);
		bamAlignmentManager->loadAlignments(variantManagerPtr);
		// bamAlignmentManager->asyncLoadAlignments(variantManagerPtr, graphSize); // begin the process of loading the alignments asynchronously
		// bamAlignmentManager->waitForAlignmentsToLoad(); // wait for alignments to load into memory

		variantManagerPtr->releaseResources(); // releases the vcf file memory, we no longer need the file resources
		bamAlignmentManager->releaseResources(); // release the bam file into memory, we no longer need the file resources

		std::deque< std::shared_ptr< std::future< void > > > variantManagerFutureFunctions;
		for (auto& iter : variantManagerPtr->getVCFReadersAndVariantListsMap())
		{
			auto futureFunct = graphite::ThreadPool::Instance()->enqueue(std::bind(&graphite::IVariantList::processOverlappingAlleles, iter.second));
			variantManagerFutureFunctions.push_back(futureFunct);
		}
		while (!variantManagerFutureFunctions.empty())
		{
			variantManagerFutureFunctions.front()->wait();
			variantManagerFutureFunctions.pop_front();
		}

		milliseconds_since_epoch = std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1);

		// create an adjudicator for the graph
		auto gsswAdjudicator = std::make_shared< graphite::GSSWAdjudicator >(swPercent, matchValue, misMatchValue, gapOpenValue, gapExtensionValue);

		// the gsswGraphManager adjudicates on the variantManager's variants
		auto gsswGraphManager = std::make_shared< graphite::GraphManager >(fastaReferencePtr, variantManagerPtr, bamAlignmentManager, gsswAdjudicator);
		// auto gsswGraphManager = std::make_shared< graphite::GraphManager >(fastaReferencePtr, variantManagerPtr, alignmentManager, gsswAdjudicator);
		gsswGraphManager->buildGraphs(fastaReferencePtr->getRegion(), readLength);

		graphite::MappingManager::Instance()->evaluateAlignmentMappings(gsswAdjudicator);
		graphite::MappingManager::Instance()->clearRegisteredMappings();

		std::vector< std::shared_ptr< std::thread > > fileWriters;
		auto vcfPathsAndVariantListPtrsMap = variantManagerPtr->getVCFReadersAndVariantListsMap();
		std::deque< std::shared_ptr< std::future< void > > > vcfWriterFutureFunctions;
		for (auto& iter : vcfPathsAndVariantListPtrsMap)
		{
			auto vcfReaderPtr = iter.first;
			auto vcfPath = vcfReaderPtr->getFilePath();
			graphite::IFileWriter::SharedPtr fileWriter = vcfoutPaths[vcfPath];
			std::string currentVCFOutPath = fileWriter->getFilePath();
			auto variantListPtr = iter.second;
			auto vcfHeaderPtr = vcfReaderPtr->getVCFHeader();

			vcfHeaderPtr->registerActiveSample(sampleManagerPtr);
			if (firstTime)
			{
				outputPaths.emplace(currentVCFOutPath);
			}
			auto funct = std::bind(&graphite::VariantList::writeVariantList, variantListPtr, fileWriter, vcfHeaderPtr, firstTime);
			auto functFuture = graphite::ThreadPool::Instance()->enqueue(funct);
			vcfWriterFutureFunctions.push_back(functFuture);
		}

		while (!vcfWriterFutureFunctions.empty())
		{
			vcfWriterFutureFunctions.front()->wait();
			vcfWriterFutureFunctions.pop_front();
		}

		firstTime = false;
	}

	for (auto& iter : vcfoutPaths)
	{
		graphite::IFileWriter::SharedPtr fileWriter = iter.second;
		fileWriter->close();
	}

	// graphite::GSSWAdjudicator* adj_p;
	// std::cout << "adj counts: " << (uint32_t)adj_p->s_adj_count << " [total]" << std::endl;

	return 0;
}
コード例 #30
0
bool EmulatedCameraHotplugThread::threadLoop() {

    // If requestExit was already called, mRunning will be false
    while (mRunning) {
        char buffer[EVENT_BUF_LEN];
        int length = TEMP_FAILURE_RETRY(
                        read(mInotifyFd, buffer, EVENT_BUF_LEN));

        if (length < 0) {
            ALOGE("%s: Error reading from inotify FD, error: '%s' (%d)",
                 __FUNCTION__, strerror(errno),
                 errno);
            mRunning = false;
            break;
        }

        ALOGV("%s: Read %d bytes from inotify FD", __FUNCTION__, length);

        int i = 0;
        while (i < length) {
            inotify_event* event = (inotify_event*) &buffer[i];

            if (event->mask & IN_IGNORED) {
                Mutex::Autolock al(mMutex);
                if (!mRunning) {
                    ALOGV("%s: Shutting down thread", __FUNCTION__);
                    break;
                } else {
                    ALOGE("%s: File was deleted, aborting",
                          __FUNCTION__);
                    mRunning = false;
                    break;
                }
            } else if (event->mask & IN_CLOSE_WRITE) {
                int cameraId = getCameraId(event->wd);

                if (cameraId < 0) {
                    ALOGE("%s: Got bad camera ID from WD '%d",
                          __FUNCTION__, event->wd);
                } else {
                    // Check the file for the new hotplug event
                    String8 filePath = getFilePath(cameraId);
                    /**
                     * NOTE: we carefully avoid getting an inotify
                     * for the same exact file because it's opened for
                     * read-only, but our inotify is for write-only
                     */
                    int newStatus = readFile(filePath);

                    if (newStatus < 0) {
                        mRunning = false;
                        break;
                    }

                    int halStatus = newStatus ?
                        CAMERA_DEVICE_STATUS_PRESENT :
                        CAMERA_DEVICE_STATUS_NOT_PRESENT;
                    gEmulatedCameraFactory.onStatusChanged(cameraId,
                                                           halStatus);
                }

            } else {
                ALOGW("%s: Unknown mask 0x%x",
                      __FUNCTION__, event->mask);
            }

            i += EVENT_SIZE + event->len;
        }
    }

    if (!mRunning) {
        close(mInotifyFd);
        return false;
    }

    return true;
}