Exemplo n.º 1
0
	void dotag()
	{
		last_tag = current;
		std::string name;
		nextword(name);

		int spc = next();
		if (spc == '>')
			unget(spc);
		else if (!isspace(spc))
			throw CoreException("Invalid character in tag name");

		if (name.empty())
			throw CoreException("Empty tag name");

		ConfigItems* items;
		tag = ConfigTag::create(name, current.filename, current.line, items);

		while (kv(items))
		{
			// Do nothing here (silences a GCC warning).
		}

		if (name == mandatory_tag)
		{
			// Found the mandatory tag
			mandatory_tag.clear();
		}

		if (name == "include")
		{
			stack.DoInclude(tag, flags);
		}
		else if (name == "files")
		{
			for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
			{
				stack.DoReadFile(i->first, i->second, flags, false);
			}
		}
		else if (name == "execfiles")
		{
			for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
			{
				stack.DoReadFile(i->first, i->second, flags, true);
			}
		}
		else if (name == "define")
		{
			if (flags & FLAG_USE_COMPAT)
				throw CoreException("<define> tags may only be used in XML-style config (add <config format=\"xml\">)");
			std::string varname = tag->getString("name");
			std::string value = tag->getString("value");
			if (varname.empty())
				throw CoreException("Variable definition must include variable name");
			stack.vars[varname] = value;
		}
		else if (name == "config")
		{
			std::string format = tag->getString("format");
			if (format == "xml")
				flags &= ~FLAG_USE_COMPAT;
			else if (format == "compat")
				flags |= FLAG_USE_COMPAT;
			else if (!format.empty())
				throw CoreException("Unknown configuration format " + format);
		}
		else
		{
			stack.output.insert(std::make_pair(name, tag));
		}
		// this is not a leak; reference<> takes care of the delete
		tag = NULL;
	}
Exemplo n.º 2
0
int main(int argc, char **argv)
{
    bool force_selector = false;
    bool no_variadic = false;
    bool no_macro = false;
    bool no_include = false;
    char const *author = "Unknown Author";
    char const *hwprefix = "";

    if(argc <= 1)
        usage();

    while(1)
    {
        static struct option long_options[] =
        {
            {"help", no_argument, 0, '?'},
            {"selector", no_argument, 0, 's'},
            {"no-macro", no_argument, 0, 'm'},
            {"no-include", no_argument, 0, 'i'},
            {"no-variadic", no_argument, 0, 'v'},
            {"reg-prefix", required_argument, 0, 'p'},
            {"author", required_argument, 0, 'a'},
            {0, 0, 0, 0}
        };

        int c = getopt_long(argc, argv, "?smivp:a:", long_options, NULL);
        if(c == -1)
            break;
        switch(c)
        {
            case -1:
                break;
            case '?':
                usage();
                break;
            case 's':
                force_selector = true;
                break;
            case 'm':
                no_macro = true;
                break;
            case 'i':
                no_include = true;
                break;
            case 'v':
                no_variadic = true;
                break;
            case 'a' :
                author = optarg;
                break;
            case 'p' :
                hwprefix = optarg;
                break;
            default:
                abort();
        }
    }

    std::vector< soc_t > socs;
    for(int i = optind; i < argc - 1; i++)
    {
        soc_t s;
        if(!parse_xml(argv[i], s))
        {
            printf("Cannot parse %s\n", argv[i]);
            return 1;
        }
        socs.push_back(s);
    }

    g_gen_selector = force_selector || socs.size() > 1;

    if(!no_macro)
    {
        g_macro_filename = std::string(argv[argc - 1]) + "/regs-macro.h";
        gen_macro(g_macro_filename, !no_variadic, author, hwprefix);
        g_macro_filename = "regs-macro.h";
        if(no_include)
           g_macro_filename.clear();
    }
    if(g_gen_selector)
    {
        gen_selectors(argv[argc - 1], socs, author);
        g_macro_filename.clear();
    }
    gen_headers(argv[argc - 1], socs, author, hwprefix);
    return 0;
}
Exemplo n.º 3
0
// CancelWithHUD
bool mwseCancelWithHUD::execute(mwseInstruction *_this)
{
    currentHUDName.clear();
    currentHUD = MGEhud::invalid_hud_id;
     return true;
}
Exemplo n.º 4
0
 virtual void process(const std::string& message)
 {
     mFormattedMessage.clear();
     MessageFormatParser::process(message);
 }
Exemplo n.º 5
0
 virtual void sendImpl(const void *data, int size, int code, bool chunked) {
   m_response.clear();
   m_response.append((const char *)data, size);
   m_code = code;
 }
Exemplo n.º 6
0
			bool AuthManagerImpl::GetServer(std::string &_ipAddress, std::string &_port)
			{
				//获取server.ini绝对路径
				char path[MAX_PATH] = {0};
				GetModuleFileNameA(GetModuleHandleA(AUTH_IMPL_DLL), path, MAX_PATH);

				std::string sPath(path);
				sPath = sPath.substr(0, sPath.rfind("\\")+1);
				sPath.append(SERVER_INI_FILE);

				//先清空
				_ipAddress.clear();
				_port.clear();

				const int IP_LENGTH = 16;
				char acIPAddr[IP_LENGTH] = {0};

				const int PORT_LENGTH = 8;
				char acPort[PORT_LENGTH] = {0};				

				//读取server.ini文件中的SSO Server IP和端口号
				DWORD dwNum = ::GetPrivateProfileStringA(NODE_STRING,IP_STRING,"",acIPAddr,IP_LENGTH,sPath.c_str());
				DWORD dwNum1 = ::GetPrivateProfileStringA(NODE_STRING,PORT_STRING,"",acPort,PORT_LENGTH,sPath.c_str());
				if ((0 == dwNum) || (0 == dwNum1))
				{
					//读取eSpace当前使用的服务器,server1 or server2
					const int SERVER_LENGTH = 16;
					char acServer[SERVER_LENGTH] = {0};
					dwNum = ::GetPrivateProfileStringA(NODE_STRING,SERVER_STRING,"",acServer,SERVER_LENGTH,sPath.c_str());
					if (0 == dwNum)
					{
						return false;
					}

					//判断当前使用的服务器是server1还是server2
					if (0 == _stricmp(acServer, "server1"))
					{
						//读取server1的IP和端口号
						dwNum = ::GetPrivateProfileStringA(NODE_STRING,SERVER1IP_STRING,"",acIPAddr,IP_LENGTH,sPath.c_str());
						dwNum1 = ::GetPrivateProfileStringA(NODE_STRING,SERVER1PORT_STRING,"",acPort,PORT_LENGTH,sPath.c_str());
						if ((0 == dwNum) || (0 == dwNum1))
						{
							//读取server1备用的IP和端口号
							dwNum = ::GetPrivateProfileStringA(NODE_STRING,SERVER1IPBAK_STRING,"",acIPAddr,IP_LENGTH,sPath.c_str());
							dwNum1 = ::GetPrivateProfileStringA(NODE_STRING,SERVER1PORTBAK_STRING,"",acPort,PORT_LENGTH,sPath.c_str());
							if ((0 == dwNum) || (0 == dwNum1))
							{
								return false;
							}
						}
					}
					else if (0 == _stricmp(acServer, "server2"))
					{
						//读取server2的IP和端口号
						dwNum = ::GetPrivateProfileStringA(NODE_STRING,SERVER2IP_STRING,"",acIPAddr,IP_LENGTH,sPath.c_str());
						dwNum1 = ::GetPrivateProfileStringA(NODE_STRING,SERVER2PORT_STRING,"",acPort,PORT_LENGTH,sPath.c_str());
						if ((0 == dwNum) || (0 == dwNum1))
						{
							//读取server2备用的IP和端口号
							dwNum = ::GetPrivateProfileStringA(NODE_STRING,SERVER2IPBAK_STRING,"",acIPAddr,IP_LENGTH,sPath.c_str());
							dwNum1 = ::GetPrivateProfileStringA(NODE_STRING,SERVER2PORTBAK_STRING,"",acPort,PORT_LENGTH,sPath.c_str());
							if ((0 == dwNum) || (0 == dwNum1))
							{
								return false;
							}
						}

					}
					else
					{
						return false;
					}					
				}

				//检查IP地址和端口的合法性
				bool bRet = CheckIpAndPort(acIPAddr, acPort);
				if (!bRet)
				{
					return false;
				}

				_ipAddress = acIPAddr;
				_port = acPort;
				return true;
			}
Exemplo n.º 7
0
bool EasyDarwinDeviceSnapUpdateReq::GetImageData(std::string &sImageBase64Data)
{
	sImageBase64Data.clear();
	sImageBase64Data = GetBodyValue("Img");
	return !sImageBase64Data.empty();
}
Exemplo n.º 8
0
		~logger()
		{
			mutex::scoped_lock l(file_mutex);
			log_file.close();
			open_filename.clear();
		}
Exemplo n.º 9
0
bool CDlgEventLog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin CDlgEventLog member initialisation
    CMainDocument* pDoc     = wxGetApp().GetDocument();
    wxASSERT(pDoc);
    wxASSERT(wxDynamicCast(pDoc, CMainDocument));
    
    m_iPreviousRowCount = 0;
    m_iTotalDocCount = 0;
    m_iPreviousFirstMsgSeqNum = pDoc->GetFirstMsgSeqNum();
    m_iPreviousLastMsgSeqNum = m_iPreviousFirstMsgSeqNum - 1;

    m_iNumDeletedFilteredRows = 0;
    m_iTotalDeletedFilterRows = 0;
    
    if (!s_bIsFiltered) {
        s_strFilteredProjectName.clear();
    }
    m_iFilteredIndexes.Clear();
	m_bProcessingRefreshEvent = false;
    m_bWasConnected = false;
    m_bEventLogIsOpen = true;
////@end CDlgEventLog member initialisation

    CSkinAdvanced* pSkinAdvanced = wxGetApp().GetSkinManager()->GetAdvanced();
    wxPoint oTempPoint;
    wxSize  oTempSize;

    wxASSERT(pSkinAdvanced);
    wxASSERT(wxDynamicCast(pSkinAdvanced, CSkinAdvanced));

    if ((pos == wxDefaultPosition) && (size == wxDefaultSize)) {
        // Get size and position from the previous configuration
        GetWindowDimensions( oTempPoint, oTempSize );

#ifdef __WXMSW__
        // Get the current display space for the current window
		int iDisplay = wxNOT_FOUND;
		if ( wxGetApp().GetFrame() != NULL ) iDisplay = wxDisplay::GetFromWindow(wxGetApp().GetFrame());
		if ( iDisplay == wxNOT_FOUND ) iDisplay = 0;
        wxDisplay *display = new wxDisplay(iDisplay);
        wxRect rDisplay = display->GetClientArea();

		// Check that the saved height and width is not larger than the displayable space.
		// If it is, then reduce the size.
        if ( oTempSize.GetWidth() > rDisplay.width ) oTempSize.SetWidth(rDisplay.width);
        if ( oTempSize.GetHeight() > rDisplay.height ) oTempSize.SetHeight(rDisplay.height);

        // Check if part of the display was going to be off the screen, if so, center the 
        // display on that axis
		if ( oTempPoint.x < rDisplay.x ) {
			oTempPoint.x = rDisplay.x;
		} else if ( oTempPoint.x + oTempSize.GetWidth() > rDisplay.x + rDisplay.width ) {
			oTempPoint.x = rDisplay.x + rDisplay.width - oTempSize.GetWidth();
		}

		if ( oTempPoint.y < rDisplay.y ) {
			oTempPoint.y = rDisplay.y;
		} else if ( oTempPoint.y + oTempSize.GetHeight() > rDisplay.y + rDisplay.height ) {
			oTempPoint.y = rDisplay.y + rDisplay.height - oTempSize.GetHeight();
		}

        delete display;
#endif

#ifdef __WXMAC__
        // If the user has changed the arrangement of multiple 
        // displays, make sure the window title bar is still on-screen.
    if (!IsWindowOnScreen(oTempPoint.x, oTempPoint.y, oTempSize.GetWidth(), oTempSize.GetHeight())) {
        oTempPoint.y = oTempPoint.x = 30;
    }
#endif  // ! __WXMAC__
    } else {
        oTempPoint = pos;
        oTempSize = size;
    }

    wxDialog::Create( parent, id, caption, oTempPoint, oTempSize, style );

    SetExtraStyle(GetExtraStyle()|wxWS_EX_BLOCK_EVENTS);

    // Initialize Application Title
    wxString strCaption = caption;
    if (strCaption.IsEmpty()) {
        strCaption.Printf(_("%s - Event Log"), pSkinAdvanced->GetApplicationName().c_str());
    }
    SetTitle(strCaption);

    // Initialize Application Icon
    wxIconBundle icons;
    icons.AddIcon(*pSkinAdvanced->GetApplicationIcon());
    icons.AddIcon(*pSkinAdvanced->GetApplicationIcon32());
    SetIcons(icons);

    CreateControls();

	// Create List Pane Items
    m_pList->InsertColumn(COLUMN_PROJECT, _("Project"), wxLIST_FORMAT_LEFT, 109);
    m_pList->InsertColumn(COLUMN_TIME, _("Time"), wxLIST_FORMAT_LEFT, 130);
    m_pList->InsertColumn(COLUMN_MESSAGE, _("Message"), wxLIST_FORMAT_LEFT, 378);

    m_pMessageInfoAttr = new wxListItemAttr(
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT),
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW),
        wxNullFont
    );
    m_pMessageErrorAttr = new wxListItemAttr(
        *wxRED,
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW),
        wxNullFont
    );
#if EVENT_LOG_STRIPES
    m_pMessageInfoGrayAttr = new wxListItemAttr(
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT),
        wxColour(240, 240, 240),
        wxNullFont
    );
    m_pMessageErrorGrayAttr = new wxListItemAttr(*wxRED, wxColour(240, 240, 240), wxNullFont);
#else
    m_pMessageInfoGrayAttr = new wxListItemAttr(*m_pMessageInfoAttr);
    m_pMessageErrorGrayAttr = new wxListItemAttr(*m_pMessageErrorAttr);
#endif

    SetTextColor();
    RestoreState();
    OnRefresh();
    // Register that we had the Event Log open immediately
    SaveState();
    return true;
}
Exemplo n.º 10
0
DumpReturn PlayerDumpReader::LoadDump(std::string const& file, uint32 account, std::string name, uint32 guid)
{
    uint32 charcount = AccountMgr::GetCharactersCount(account);
    if (charcount >= 10)
        return DUMP_TOO_MANY_CHARS;

    FILE* fin = fopen(file.c_str(), "r");
    if (!fin)
        return DUMP_FILE_OPEN_ERROR;

    char newguid[20], chraccount[20], newpetid[20], currpetid[20], lastpetid[20];

    // make sure the same guid doesn't already exist and is safe to use
    bool incHighest = true;
    if (guid != 0 && guid < sObjectMgr->_hiCharGuid)
    {
        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_GUID);
        stmt->setUInt32(0, guid);
        PreparedQueryResult result = CharacterDatabase.Query(stmt);

        if (result)
            guid = sObjectMgr->_hiCharGuid;                     // use first free if exists
        else incHighest = false;
    }
    else
        guid = sObjectMgr->_hiCharGuid;

    // normalize the name if specified and check if it exists
    if (!normalizePlayerName(name))
        name.clear();

    if (ObjectMgr::CheckPlayerName(name, true) == CHAR_NAME_SUCCESS)
    {
        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME);
        stmt->setString(0, name);
        PreparedQueryResult result = CharacterDatabase.Query(stmt);

        if (result)
            name.clear();                                       // use the one from the dump
    }
    else
        name.clear();

    // name encoded or empty

    snprintf(newguid, 20, "%u", guid);
    snprintf(chraccount, 20, "%u", account);
    snprintf(newpetid, 20, "%u", sObjectMgr->GeneratePetNumber());
    snprintf(lastpetid, 20, "%s", "");

    std::map<uint32, uint32> items;
    std::map<uint32, uint32> mails;
    char buf[32000] = "";

    typedef std::map<uint32, uint32> PetIds;                // old->new petid relation
    typedef PetIds::value_type PetIdsPair;
    PetIds petids;

    uint8 gender = GENDER_NONE;
    uint8 race = RACE_NONE;
    uint8 playerClass = 0;
    uint8 level = 1;

    SQLTransaction trans = CharacterDatabase.BeginTransaction();
    while (!feof(fin))
    {
        if (!fgets(buf, 32000, fin))
        {
            if (feof(fin))
                break;
            ROLLBACK(DUMP_FILE_BROKEN);
        }

        std::string line; line.assign(buf);

        // skip empty strings
        size_t nw_pos = line.find_first_not_of(" \t\n\r\7");
        if (nw_pos == std::string::npos)
            continue;

        // skip logfile-side dump start notice, the important notes and dump end notices
        if ((line.substr(nw_pos, 16) == "== START DUMP ==") ||
            (line.substr(nw_pos, 15) == "IMPORTANT NOTE:") ||
            (line.substr(nw_pos, 14) == "== END DUMP =="))
            continue;

        // add required_ check
        /*
        if (line.substr(nw_pos, 41) == "UPDATE character_db_version SET required_")
        {
            if (!CharacterDatabase.Execute(line.c_str()))
                ROLLBACK(DUMP_FILE_BROKEN);

            continue;
        }
        */

        // determine table name and load type
        std::string tn = gettablename(line);
        if (tn.empty())
        {
            TC_LOG_ERROR("misc", "LoadPlayerDump: Can't extract table name from line: '%s'!", line.c_str());
            ROLLBACK(DUMP_FILE_BROKEN);
        }

        DumpTableType type = DumpTableType(0);
        uint8 i;
        for (i = 0; i < DUMP_TABLE_COUNT; ++i)
        {
            if (tn == dumpTables[i].name)
            {
                type = dumpTables[i].type;
                break;
            }
        }

        if (i == DUMP_TABLE_COUNT)
        {
            TC_LOG_ERROR("misc", "LoadPlayerDump: Unknown table: '%s'!", tn.c_str());
            ROLLBACK(DUMP_FILE_BROKEN);
        }

        // change the data to server values
        switch (type)
        {
            case DTT_CHARACTER:
            {
                if (!changenth(line, 1, newguid))           // characters.guid update
                    ROLLBACK(DUMP_FILE_BROKEN);

                if (!changenth(line, 2, chraccount))        // characters.account update
                    ROLLBACK(DUMP_FILE_BROKEN);

                race = uint8(atol(getnth(line, 4).c_str()));
                playerClass = uint8(atol(getnth(line, 5).c_str()));
                gender = uint8(atol(getnth(line, 6).c_str()));
                level = uint8(atol(getnth(line, 7).c_str()));
                if (name.empty())
                {
                    // check if the original name already exists
                    name = getnth(line, 3);

                    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME);
                    stmt->setString(0, name);
                    PreparedQueryResult result = CharacterDatabase.Query(stmt);

                    if (result)
                        if (!changenth(line, 37, "1"))       // characters.at_login set to "rename on login"
                            ROLLBACK(DUMP_FILE_BROKEN);
                }
                else if (!changenth(line, 3, name.c_str())) // characters.name
                    ROLLBACK(DUMP_FILE_BROKEN);

                const char null[5] = "NULL";
                if (!changenth(line, 69, null))             // characters.deleteInfos_Account
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!changenth(line, 70, null))             // characters.deleteInfos_Name
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!changenth(line, 71, null))             // characters.deleteDate
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_CHAR_TABLE:
            {
                if (!changenth(line, 1, newguid))           // character_*.guid update
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_EQSET_TABLE:
            {
                if (!changenth(line, 1, newguid))
                    ROLLBACK(DUMP_FILE_BROKEN);             // character_equipmentsets.guid

                char newSetGuid[24];
                snprintf(newSetGuid, 24, UI64FMTD, sObjectMgr->GenerateEquipmentSetGuid());
                if (!changenth(line, 2, newSetGuid))
                    ROLLBACK(DUMP_FILE_BROKEN);             // character_equipmentsets.setguid
                break;
            }
            case DTT_INVENTORY:
            {
                if (!changenth(line, 1, newguid))           // character_inventory.guid update
                    ROLLBACK(DUMP_FILE_BROKEN);

                if (!changeGuid(line, 2, items, sObjectMgr->_hiItemGuid, true))
                    ROLLBACK(DUMP_FILE_BROKEN);             // character_inventory.bag update
                if (!changeGuid(line, 4, items, sObjectMgr->_hiItemGuid))
                    ROLLBACK(DUMP_FILE_BROKEN);             // character_inventory.item update
                break;
            }
            case DTT_MAIL:                                  // mail
            {
                if (!changeGuid(line, 1, mails, sObjectMgr->_mailId))
                    ROLLBACK(DUMP_FILE_BROKEN);             // mail.id update
                if (!changenth(line, 6, newguid))           // mail.receiver update
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_MAIL_ITEM:                             // mail_items
            {
                if (!changeGuid(line, 1, mails, sObjectMgr->_mailId))
                    ROLLBACK(DUMP_FILE_BROKEN);             // mail_items.id
                if (!changeGuid(line, 2, items, sObjectMgr->_hiItemGuid))
                    ROLLBACK(DUMP_FILE_BROKEN);             // mail_items.item_guid
                if (!changenth(line, 3, newguid))           // mail_items.receiver
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_ITEM:
            {
                // item, owner, data field:item, owner guid
                if (!changeGuid(line, 1, items, sObjectMgr->_hiItemGuid))
                   ROLLBACK(DUMP_FILE_BROKEN);              // item_instance.guid update
                if (!changenth(line, 3, newguid))           // item_instance.owner_guid update
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_ITEM_GIFT:
            {
                if (!changenth(line, 1, newguid))           // character_gifts.guid update
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!changeGuid(line, 2, items, sObjectMgr->_hiItemGuid))
                    ROLLBACK(DUMP_FILE_BROKEN);             // character_gifts.item_guid update
                break;
            }
            case DTT_PET:
            {
                //store a map of old pet id to new inserted pet id for use by type 5 tables
                snprintf(currpetid, 20, "%s", getnth(line, 1).c_str());
                if (*lastpetid == '\0')
                    snprintf(lastpetid, 20, "%s", currpetid);
                if (strcmp(lastpetid, currpetid) != 0)
                {
                    snprintf(newpetid, 20, "%u", sObjectMgr->GeneratePetNumber());
                    snprintf(lastpetid, 20, "%s", currpetid);
                }

                std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));

                if (petids_iter == petids.end())
                {
                    petids.insert(PetIdsPair(atoi(currpetid), atoi(newpetid)));
                }

                if (!changenth(line, 1, newpetid))          // character_pet.id update
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!changenth(line, 3, newguid))           // character_pet.owner update
                    ROLLBACK(DUMP_FILE_BROKEN);

                break;
            }
            case DTT_PET_TABLE:                             // pet_aura, pet_spell, pet_spell_cooldown
            {
                snprintf(currpetid, 20, "%s", getnth(line, 1).c_str());

                // lookup currpetid and match to new inserted pet id
                std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));
                if (petids_iter == petids.end())             // couldn't find new inserted id
                    ROLLBACK(DUMP_FILE_BROKEN);

                snprintf(newpetid, 20, "%d", petids_iter->second);

                if (!changenth(line, 1, newpetid))
                    ROLLBACK(DUMP_FILE_BROKEN);

                break;
            }
            default:
                TC_LOG_ERROR("misc", "Unknown dump table type: %u", type);
                break;
        }

        fixNULLfields(line);

        trans->Append(line.c_str());
    }

    CharacterDatabase.CommitTransaction(trans);

    // in case of name conflict player has to rename at login anyway
    sWorld->AddCharacterNameData(ObjectGuid(HIGHGUID_PLAYER, guid), name, gender, race, playerClass, level);

    sObjectMgr->_hiItemGuid += items.size();
    sObjectMgr->_mailId     += mails.size();

    if (incHighest)
        ++sObjectMgr->_hiCharGuid;

    fclose(fin);

    return DUMP_SUCCESS;
}
Exemplo n.º 11
0
// 发送webservice调用消息
int CTMSSensor::SendAndRecvResponse(bool bTMSWS,const std::string &request, std::string &response, int delayTime)
{
	if(m_strIP.empty())
	{
		return 0;
	}

	TcpTransport tcp;
	int result= -1;
	std::string strIP;
	if(bTMSWS)
	{
		strIP="127.0.0.1";
	}
	else
	{
		strIP=m_strIP;
	}

	result = tcp.TcpConnect(strIP.c_str(), m_nTMSWBPort,delayTime);
	if(result < 0)
	{	
		LOGFMT(ULOG_ERROR,"CTMSSensor::SendAndRecvResponse TcpConnect %s:%d Fail !\n",strIP.c_str(), m_nTMSWBPort);
		if(!bTMSWS)
		{
			
			IPMgr::GetInstance()->GetNextOtherIP(strIP);
			if(strIP!=m_strIP)
			{
				result = tcp.TcpConnect(strIP.c_str(), m_nTMSWBPort,delayTime);
				if(result < 0)
				{
					LOGFMT(ULOG_ERROR,"CTMSSensor::SendAndRecvResponse TcpConnect %s:%d Fail !\n",strIP.c_str(), m_nTMSWBPort);
					return  ERROR_SENSOR_TCP_CONNECT;
				}
				else
				{
					m_strIP=strIP;
					LOGFMT(ULOG_ERROR,"CTMSSensor::Set Default Other IP=%s!\n",strIP.c_str());
				}
			}
		}
		
		if(result < 0)
		{
			return  ERROR_SENSOR_TCP_CONNECT;
		}
		
	}

	result = tcp.BlockSend(request.c_str(), request.size());
	if(result < 0)
	{
		LOGFMT(ULOG_ERROR,"CTMSSensor::SendAndRecvResponse Tcp Send %s Fail(%s:%d) !\n",request.c_str(),
			m_strIP.c_str(),m_nTMSWBPort);
		return  ERROR_SENSOR_TCP_SEND;
	}


	char buffer[1024];
	timeval timeOut;
	timeOut.tv_sec = delayTime;
	timeOut.tv_usec = 0;
	response.clear();
	while((result = tcp.SelectRecv(buffer, 1024-1, timeOut)) >= 0)
	{
		if(result == 0)
			break;
		buffer[result] = 0;
		response += buffer;

		if(response.find(":Envelope>") != std::string::npos)
			break;
		timeOut.tv_sec = 2;
		timeOut.tv_usec = 0;
	}

	return result <0 ? ERROR_SENSOR_TCP_RECV : 0;

}
Exemplo n.º 12
0
int _define_ship(lua_State *L, ShipType::Tag tag, std::vector<ShipType::Type> *list)
{
	if (s_currentShipFile.empty())
		return luaL_error(L, "ship file contains multiple ship definitions");

	ShipType s;
	s.tag = tag;

	LUA_DEBUG_START(L);
	_get_string_attrib(L, "name", s.name, "");
	_get_string_attrib(L, "model", s.lmrModelName, "");
	_get_float_attrib(L, "reverse_thrust", s.linThrust[ShipType::THRUSTER_REVERSE], 0.0f);
	_get_float_attrib(L, "forward_thrust", s.linThrust[ShipType::THRUSTER_FORWARD], 0.0f);
	_get_float_attrib(L, "up_thrust", s.linThrust[ShipType::THRUSTER_UP], 0.0f);
	_get_float_attrib(L, "down_thrust", s.linThrust[ShipType::THRUSTER_DOWN], 0.0f);
	_get_float_attrib(L, "left_thrust", s.linThrust[ShipType::THRUSTER_LEFT], 0.0f);
	_get_float_attrib(L, "right_thrust", s.linThrust[ShipType::THRUSTER_RIGHT], 0.0f);
	_get_float_attrib(L, "angular_thrust", s.angThrust, 0.0f);
	// invert values where necessary
	s.linThrust[ShipType::THRUSTER_FORWARD] *= -1.f;
	s.linThrust[ShipType::THRUSTER_LEFT] *= -1.f;
	s.linThrust[ShipType::THRUSTER_DOWN] *= -1.f;
	// angthrust fudge (XXX: why?)
	s.angThrust = s.angThrust / 2;

	_get_vec_attrib(L, "camera_offset", s.cameraOffset, vector3d(0.0));

	for (int i=0; i<Equip::SLOT_MAX; i++) s.equipSlotCapacity[i] = 0;
	_get_int_attrib(L, "max_cargo", s.equipSlotCapacity[Equip::SLOT_CARGO], 0);
	_get_int_attrib(L, "max_engine", s.equipSlotCapacity[Equip::SLOT_ENGINE], 1);
	_get_int_attrib(L, "max_laser", s.equipSlotCapacity[Equip::SLOT_LASER], 1);
	_get_int_attrib(L, "max_missile", s.equipSlotCapacity[Equip::SLOT_MISSILE], 0);
	_get_int_attrib(L, "max_ecm", s.equipSlotCapacity[Equip::SLOT_ECM], 1);
	_get_int_attrib(L, "max_scanner", s.equipSlotCapacity[Equip::SLOT_SCANNER], 1);
	_get_int_attrib(L, "max_radarmapper", s.equipSlotCapacity[Equip::SLOT_RADARMAPPER], 1);
	_get_int_attrib(L, "max_hypercloud", s.equipSlotCapacity[Equip::SLOT_HYPERCLOUD], 1);
	_get_int_attrib(L, "max_hullautorepair", s.equipSlotCapacity[Equip::SLOT_HULLAUTOREPAIR], 1);
	_get_int_attrib(L, "max_energybooster", s.equipSlotCapacity[Equip::SLOT_ENERGYBOOSTER], 1);
	_get_int_attrib(L, "max_atmoshield", s.equipSlotCapacity[Equip::SLOT_ATMOSHIELD], 1);
	_get_int_attrib(L, "max_cabin", s.equipSlotCapacity[Equip::SLOT_CABIN], 50);
	_get_int_attrib(L, "max_shield", s.equipSlotCapacity[Equip::SLOT_SHIELD], 9999);
	_get_int_attrib(L, "max_fuelscoop", s.equipSlotCapacity[Equip::SLOT_FUELSCOOP], 1);
	_get_int_attrib(L, "max_cargoscoop", s.equipSlotCapacity[Equip::SLOT_CARGOSCOOP], 1);
	_get_int_attrib(L, "max_lasercooler", s.equipSlotCapacity[Equip::SLOT_LASERCOOLER], 1);
	_get_int_attrib(L, "max_cargolifesupport", s.equipSlotCapacity[Equip::SLOT_CARGOLIFESUPPORT], 1);
	_get_int_attrib(L, "max_autopilot", s.equipSlotCapacity[Equip::SLOT_AUTOPILOT], 1);

	_get_int_attrib(L, "capacity", s.capacity, 0);
	_get_int_attrib(L, "hull_mass", s.hullMass, 100);
	_get_int_attrib(L, "fuel_tank_mass", s.fuelTankMass, 5);
	_get_float_attrib(L, "thruster_fuel_use", s.thrusterFuelUse, 1.f);
	_get_int_attrib(L, "price", s.baseprice, 0);
	s.baseprice *= 100; // in hundredths of credits

	s.equipSlotCapacity[Equip::SLOT_ENGINE] = Clamp(s.equipSlotCapacity[Equip::SLOT_ENGINE], 0, 1);

	{
		int hyperclass;
		_get_int_attrib(L, "hyperdrive_class", hyperclass, 1);
		if (!hyperclass) {
			s.hyperdrive = Equip::NONE;
		} else {
			s.hyperdrive = Equip::Type(Equip::DRIVE_CLASS1+hyperclass-1);
		}
	}

	lua_pushstring(L, "gun_mounts");
	lua_gettable(L, -2);
	if (lua_istable(L, -1)) {
		for (unsigned int i=0; i<lua_rawlen(L,-1); i++) {
			lua_pushinteger(L, i+1);
			lua_gettable(L, -2);
			if (lua_istable(L, -1) && lua_rawlen(L,-1) == 4)	{
				lua_pushinteger(L, 1);
				lua_gettable(L, -2);
				s.gunMount[i].pos = LuaVector::CheckFromLuaF(L, -1);
				lua_pop(L, 1);
				lua_pushinteger(L, 2);
				lua_gettable(L, -2);
				s.gunMount[i].dir = LuaVector::CheckFromLuaF(L, -1);
				lua_pop(L, 1);
				lua_pushinteger(L, 3);
				lua_gettable(L, -2);
				s.gunMount[i].sep = lua_tonumber(L,-1);
				lua_pop(L, 1);
				lua_pushinteger(L, 4);
				lua_gettable(L, -2);
				s.gunMount[i].orient = static_cast<ShipType::DualLaserOrientation>(
						LuaConstants::GetConstantFromArg(L, "DualLaserOrientation", -1));
				lua_pop(L, 1);
			}
			lua_pop(L, 1);
		}
	}
	lua_pop(L, 1);
	LUA_DEBUG_END(L, 0);

	//sanity check
	if (s.name.empty())
		return luaL_error(L, "Ship has no name");

	if (s.lmrModelName.empty())
		return luaL_error(L, "Missing model name in ship");

	//this shouldn't necessarily be a fatal problem, could just warn+mark ship unusable
	//or replace with proxy geometry
	try {
		LmrLookupModelByName(s.lmrModelName.c_str());
	} catch (LmrModelNotFoundException &) {
		return luaL_error(L, "Model %s is not defined", s.lmrModelName.c_str());
	}

	const std::string& id = s_currentShipFile;
	typedef std::map<ShipType::Type, ShipType>::iterator iter;
	std::pair<iter, bool> result = ShipType::types.insert(std::make_pair(id, s));
	if (result.second)
		list->push_back(s_currentShipFile);
	else
		return luaL_error(L, "Ship '%s' was already defined by a different file", id.c_str());
	s_currentShipFile.clear();

	return 0;
}
Exemplo n.º 13
0
void ShipType::Init()
{
	static bool isInitted = false;
	if (isInitted) return;
	isInitted = true;

	lua_State *l = luaL_newstate();

	LUA_DEBUG_START(l);

	luaL_requiref(l, "_G", &luaopen_base, 1);
	luaL_requiref(l, LUA_DBLIBNAME, &luaopen_debug, 1);
	luaL_requiref(l, LUA_MATHLIBNAME, &luaopen_math, 1);
	lua_pop(l, 3);

	LuaConstants::Register(l);
	LuaVector::Register(l);
	LUA_DEBUG_CHECK(l, 0);

	// provide shortcut vector constructor: v = vector.new
	lua_getglobal(l, LuaVector::LibName);
	lua_getfield(l, -1, "new");
	assert(lua_iscfunction(l, -1));
	lua_setglobal(l, "v");
	lua_pop(l, 1); // pop the vector library table

	LUA_DEBUG_CHECK(l, 0);

	// register ship definition functions
	lua_register(l, "define_ship", define_ship);
	lua_register(l, "define_static_ship", define_static_ship);
	lua_register(l, "define_missile", define_missile);

	LUA_DEBUG_CHECK(l, 0);

	// load all ship definitions
	namespace fs = FileSystem;
	for (fs::FileEnumerator files(fs::gameDataFiles, "ships", fs::FileEnumerator::Recurse);
			!files.Finished(); files.Next()) {
		const fs::FileInfo &info = files.Current();
		if (ends_with(info.GetPath(), ".lua")) {
			const std::string name = info.GetName();
			s_currentShipFile = name.substr(0, name.size()-4);
			pi_lua_dofile(l, info.GetPath());
			s_currentShipFile.clear();
		}
	}

	LUA_DEBUG_END(l, 0);

	lua_close(l);

	if (ShipType::player_ships.empty())
		Error("No playable ships have been defined! The game cannot run.");

	//collect ships that can fit atmospheric shields
	for (std::vector<ShipType::Type>::const_iterator it = ShipType::player_ships.begin();
		it != ShipType::player_ships.end(); ++it) {
		const ShipType &ship = ShipType::types[*it];
		if (ship.equipSlotCapacity[Equip::SLOT_ATMOSHIELD] != 0)
			ShipType::playable_atmospheric_ships.push_back(*it);
	}

	if (ShipType::playable_atmospheric_ships.empty())
		Error("No ships can fit atmospheric shields! The game cannot run.");
}
Exemplo n.º 14
0
/**
   set_color builtin
*/
static int builtin_set_color(parser_t &parser, wchar_t **argv)
{
    /** Variables used for parsing the argument list */
    const struct woption long_options[] =
    {
        { L"background", required_argument, 0, 'b'},
        { L"help", no_argument, 0, 'h' },
        { L"bold", no_argument, 0, 'o' },
        { L"underline", no_argument, 0, 'u' },
        { L"version", no_argument, 0, 'v' },
        { L"print-colors", no_argument, 0, 'c' },
        { 0, 0, 0, 0 }
    };

    const wchar_t *short_options = L"b:hvocu";

    int argc = builtin_count_args(argv);

    const wchar_t *bgcolor = NULL;
    bool bold = false, underline=false;
    int errret;

    /* Parse options to obtain the requested operation and the modifiers */
    woptind = 0;
    while (1)
    {
        int c = wgetopt_long(argc, argv, short_options, long_options, 0);

        if (c == -1)
        {
            break;
        }

        switch (c)
        {
            case 0:
                break;

            case 'b':
                bgcolor = woptarg;
                break;

            case 'h':
                builtin_print_help(parser, argv[0], stdout_buffer);
                return STATUS_BUILTIN_OK;

            case 'o':
                bold = true;
                break;

            case 'u':
                underline = true;
                break;

            case 'c':
                print_colors();
                return STATUS_BUILTIN_OK;

            case '?':
                return STATUS_BUILTIN_ERROR;
        }
    }

    /* Remaining argument is foreground color */
    const wchar_t *fgcolor = NULL;
    if (woptind < argc)
    {
        if (woptind + 1 == argc)
        {
            fgcolor = argv[woptind];
        }
        else
        {
            append_format(stderr_buffer,
                          _(L"%ls: Too many arguments\n"),
                          argv[0]);
            return STATUS_BUILTIN_ERROR;
        }
    }

    if (fgcolor == NULL && bgcolor == NULL && !bold && !underline)
    {
        append_format(stderr_buffer,
                      _(L"%ls: Expected an argument\n"),
                      argv[0]);
        return STATUS_BUILTIN_ERROR;
    }

    const rgb_color_t fg = rgb_color_t(fgcolor ? fgcolor : L"");
    if (fgcolor && (fg.is_none() || fg.is_ignore()))
    {
        append_format(stderr_buffer, _(L"%ls: Unknown color '%ls'\n"), argv[0], fgcolor);
        return STATUS_BUILTIN_ERROR;
    }

    const rgb_color_t bg = rgb_color_t(bgcolor ? bgcolor : L"");
    if (bgcolor && (bg.is_none() || bg.is_ignore()))
    {
        append_format(stderr_buffer, _(L"%ls: Unknown color '%ls'\n"), argv[0], bgcolor);
        return STATUS_BUILTIN_ERROR;
    }

    /* Make sure that the term exists */
    if (cur_term == NULL && setupterm(0, STDOUT_FILENO, &errret) == ERR)
    {
        append_format(stderr_buffer, _(L"%ls: Could not set up terminal\n"), argv[0]);
        return STATUS_BUILTIN_ERROR;
    }

    /*
       Test if we have at least basic support for setting fonts, colors
       and related bits - otherwise just give up...
    */
    if (! exit_attribute_mode)
    {
        return STATUS_BUILTIN_ERROR;
    }


    /* Save old output function so we can restore it */
    int (* const saved_writer_func)(char) = output_get_writer();

    /* Set our output function, which writes to a std::string */
    builtin_set_color_output.clear();
    output_set_writer(set_color_builtin_outputter);

    if (bold)
    {
        if (enter_bold_mode)
            writembs(tparm(enter_bold_mode));
    }

    if (underline)
    {
        if (enter_underline_mode)
            writembs(enter_underline_mode);
    }

    if (bgcolor != NULL)
    {
        if (bg.is_normal())
        {
            write_background_color(0);
            writembs(tparm(exit_attribute_mode));
        }
    }

    if (fgcolor != NULL)
    {
        if (fg.is_normal() || fg.is_reset())
        {
            write_foreground_color(0);
            writembs(tparm(exit_attribute_mode));
        }
        else
        {
            write_foreground_color(index_for_color(fg));
        }
    }

    if (bgcolor != NULL)
    {
        if (! bg.is_normal() && ! bg.is_reset())
        {
            write_background_color(index_for_color(bg));
        }
    }

    /* Restore saved writer function */
    output_set_writer(saved_writer_func);

    /* Output the collected string */
    std::string local_output;
    std::swap(builtin_set_color_output, local_output);
    stdout_buffer.append(str2wcstring(local_output));

    return STATUS_BUILTIN_OK;
}
Exemplo n.º 15
0
void CleanupDecoder()
{
	s_formatInfos.clear();
	s_supportedFormatsFilter.clear();
}
Exemplo n.º 16
0
 void clear()
 {
   cat_.clear();
   antecedents_.clear();
   removed_ = false;
 }
Exemplo n.º 17
0
		StrBlock(){
			str.clear();
			size=0;
			pos.Set(0);
			hasStr=false;
		}
Exemplo n.º 18
0
	void clear()
	{
		headers.clear();
		content.clear();
	}
Exemplo n.º 19
0
static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) {
    for (int i=0;i<3;i++)
        avatar_pos[i] = avatar_front[i] = avatar_top[i] = camera_pos[i] = camera_front[i] = camera_top[i] = 0.0f;

    char ccontext[128];
    char state;
    BYTE squad_state;
    BYTE is_squadleader;
    BYTE team_state;
    bool ok;

    ok = peekProc(state_ptr, &state, 1); // State value
    if (! ok)
        return false;

    if (state != STATE_IN_GAME && state != STATE_IN_MENU) {
        ptr_chain_valid = false;
        context.clear();
        identity.clear();
        return true;
    } else if (!ptr_chain_valid) {
        if (!resolve_ptrs())
            return false;
        ptr_chain_valid = true;
    }

    ok = peekProc(avatar_pos_ptr, avatar_pos, 12) &&
        peekProc(avatar_front_ptr, avatar_front, 12) &&
        peekProc(avatar_top_ptr, avatar_top, 12) &&
        peekProc(squad_state_ptr,&squad_state,1) &&
        peekProc(squad_lead_state_ptr, &is_squadleader,1) &&
        peekProc(team_state_ptr,&team_state,1) &&
        peekProc(ipport_ptr,ccontext,128);

    if (! ok)
        return false;

    ccontext[sizeof(ccontext) - 1] = 0;
    if (ccontext[0] != '0') {
        std::ostringstream ocontext;
        ocontext << "{ \"ipport\": \"" << ccontext << "\" }";

        context = ocontext.str();

        /*
            Get identity string.
        */
        std::wostringstream oidentity;
        oidentity << "{"
        << "\"squad\":" << static_cast<unsigned int>(squad_state) << ","
        << "\"squad_leader\":" << (is_squadleader ? "true" : "false") << ",";
        if (team_state == 0)
            oidentity << "\"team\": \"SPEC\"";
        else if (team_state == 1)
            oidentity << "\"team\": \"US\"";
        else if (team_state == 2)
            oidentity << "\"team\": \"RU\"";
        oidentity << "}";
        identity = oidentity.str();
    }

    // Flip our front vector
    for (int i=0;i<3;i++) {
        avatar_front[i] = -avatar_front[i];
    }

    // Convert from right to left handed
    avatar_pos[0] = -avatar_pos[0];
    avatar_front[0] = -avatar_front[0];
    avatar_top[0] = -avatar_top[0];

    for (int i=0;i<3;i++) {
        camera_pos[i] = avatar_pos[i];
        camera_front[i] = avatar_front[i];
        camera_top[i] = avatar_top[i];
    }

    return ok;
}
Exemplo n.º 20
0
void COOKIE_SQL::clear() {
    host.clear();
    name.clear();
    value.clear();
}
Exemplo n.º 21
0
void JsonValue::to_json(std::string &result) const
{
	result.clear();
	write(result);
}
Exemplo n.º 22
0
void MOZILLA_PROFILE::clear() {
    name.clear();
    path.clear();
    is_relative = false;
    is_default = false;
}
Exemplo n.º 23
0
    bool http_client::parse_url(
        const std::string& url,
        std::string& scheme,
        std::string& user,
        std::string& pass,
        std::string& host,
        short& port,
        std::string& path
    ) const
    {
        scheme.clear();
        user.clear();
        pass.clear();
        host.clear();
        path.clear();
        port = 0;

        // Find scheme
        std::string::size_type pos_scheme = url.find("://");
        if ( pos_scheme == std::string::npos )
        {
            pos_scheme = 0;
        }
        else
        {
            scheme = strtolower(url.substr(0, pos_scheme));
            pos_scheme += 3;
        }

        std::string::size_type pos_path = url.find('/', pos_scheme);
        if ( pos_path == std::string::npos )
        {
            host = url.substr(pos_scheme);
        }
        else
        {
            host = url.substr(pos_scheme, pos_path - pos_scheme);
            path = url.substr(pos_path);
        }

        std::string::size_type pos_at = host.find('@');
        if ( pos_at != std::string::npos )
        {
            std::string::size_type pos_dp = host.find(':');
            if ( pos_dp != std::string::npos && pos_dp < pos_at )
            {
                user = host.substr(0, pos_dp);
                pass = host.substr(pos_dp+1, pos_at-pos_dp-1);
            }
            else
            {
                user = host.substr(0, pos_at);
            }
            host = host.substr(pos_at+1);
        }

        std::string::size_type pos_dp = host.find(':');
        if ( pos_dp != std::string::npos )
        {
            port = dlib::string_cast<short>(host.substr(pos_dp+1));
            host = host.substr(0, pos_dp);
        }

        host = strtolower(host);

        if ( port == 0 )
        {
            if ( scheme == "http" )
                port = 80;
            else if ( scheme == "ftp" )
                port = 21;
            else if ( scheme == "https" )
                port = 443;
        }

        return !host.empty();
    }
Exemplo n.º 24
0
	void SetNick(const std::string& Nick)
	{
		nick.clear();
		// We may show this string to other users so do not leak the casing
		std::transform(Nick.begin(), Nick.end(), std::back_inserter(nick), ::tolower);
	}
Exemplo n.º 25
0
bool
OiioTool::print_info (Oiiotool &ot,
                      const std::string &filename, 
                      const print_info_options &opt,
                      long long &totalsize,
                      std::string &error)
{
    error.clear();
    ImageInput *input = ImageInput::open (filename.c_str());
    if (! input) {
        error = geterror();
        if (error.empty())
            error = Strutil::format ("Could not open \"%s\"", filename.c_str());
        return false;
    }
    ImageSpec spec = input->spec();

    boost::regex field_re;
    boost::regex field_exclude_re;
    if (! opt.metamatch.empty()) {
        try {
            field_re.assign (opt.metamatch,
                         boost::regex::extended | boost::regex_constants::icase);
        } catch (const std::exception &e) {
            error = Strutil::format ("Regex error '%s' on metamatch regex \"%s\"",
                                     e.what(), opt.metamatch);
            return false;
        }
    }
    if (! opt.nometamatch.empty()) {
        try {
            field_exclude_re.assign (opt.nometamatch,
                         boost::regex::extended | boost::regex_constants::icase);
        } catch (const std::exception &e) {
            error = Strutil::format ("Regex error '%s' on metamatch regex \"%s\"",
                                     e.what(), opt.nometamatch);
            return false;
        }
    }

    int padlen = std::max (0, (int)opt.namefieldlength - (int)filename.length());
    std::string padding (padlen, ' ');

    // checking how many subimages and mipmap levels are stored in the file
    int num_of_subimages = 1;
    bool any_mipmapping = false;
    std::vector<int> num_of_miplevels;
    {
        int nmip = 1;
        while (input->seek_subimage (input->current_subimage(), nmip, spec)) {
            ++nmip;
            any_mipmapping = true;
        }
        num_of_miplevels.push_back (nmip);
    }
    while (input->seek_subimage (num_of_subimages, 0, spec)) {
        // maybe we should do this more gently?
        ++num_of_subimages;
        int nmip = 1;
        while (input->seek_subimage (input->current_subimage(), nmip, spec)) {
            ++nmip;
            any_mipmapping = true;
        }
        num_of_miplevels.push_back (nmip);
    }
    input->seek_subimage (0, 0, spec);  // re-seek to the first

    if (opt.metamatch.empty() ||
        boost::regex_search ("resolution, width, height, depth, channels", field_re)) {
        printf ("%s%s : %4d x %4d", filename.c_str(), padding.c_str(),
                spec.width, spec.height);
        if (spec.depth > 1)
            printf (" x %4d", spec.depth);
        printf (", %d channel, %s%s", spec.nchannels,
                spec.deep ? "deep " : "",
                spec.depth > 1 ? "volume " : "");
        if (spec.channelformats.size()) {
            for (size_t c = 0;  c < spec.channelformats.size();  ++c)
                printf ("%s%s", c ? "/" : "",
                        spec.channelformats[c].c_str());
        } else {
            int bits = spec.get_int_attribute ("oiio:BitsPerSample", 0);
            printf ("%s", extended_format_name(spec.format, bits));
        }
        printf (" %s", input->format_name());
        if (opt.sum) {
            imagesize_t imagebytes = spec.image_bytes (true);
            totalsize += imagebytes;
            printf (" (%.2f MB)", (float)imagebytes / (1024.0*1024.0));
        }
        // we print info about how many subimages are stored in file
        // only when we have more then one subimage
        if ( ! opt.verbose && num_of_subimages != 1)
            printf (" (%d subimages%s)", num_of_subimages,
                    any_mipmapping ? " +mipmap)" : "");
        if (! opt.verbose && num_of_subimages == 1 && any_mipmapping)
            printf (" (+mipmap)");
        printf ("\n");
    }

    int movie = spec.get_int_attribute ("oiio:Movie");
    if (opt.verbose && num_of_subimages != 1) {
        // info about num of subimages and their resolutions
        printf ("    %d subimages: ", num_of_subimages);
        for (int i = 0; i < num_of_subimages; ++i) {
            input->seek_subimage (i, 0, spec);
            if (spec.depth > 1)
                printf ("%dx%dx%d ", spec.width, spec.height, spec.depth);
            else
                printf ("%dx%d ", spec.width, spec.height);
            if (movie)
                break;
        }
        printf ("\n");
    }

    // if the '-a' flag is not set we print info
    // about first subimage only
    if ( ! opt.subimages)
        num_of_subimages = 1;
    for (int i = 0; i < num_of_subimages; ++i) {
        print_info_subimage (ot, i, num_of_subimages, spec, input,
                             filename, opt, field_re, field_exclude_re);
    }

    input->close ();
    delete input;
    return true;
}
Exemplo n.º 26
0
bool GenerateOccupancyChart(const OccupancyUtils::OccupancyParams& params, const string& strFileName, std::string& strError)
{
    if (strFileName.empty())
    {
        strError = "No output file specified";
        return false;
    }

    ofstream fout;
    fout.open(strFileName.c_str());

    if (fout.fail())
    {
        strError = "Unable to open output file: " + strFileName;
        return false;
    }

    string outputPath;

    if (!FileUtils::GetWorkingDirectory(strFileName, outputPath))
    {
        strError = "Unable to determine ouput directory";
        return false;
    }

    if (!jqPlotChart::CopyScripts(outputPath))
    {
        strError = "Unable to copy required files to output directory";
        return false;
    }

    size_t nMaxNumWavefronts = params.m_nMaxWavesPerCU;


    CLCUInfoBase* cuDevice = NULL;

    if (params.m_gen >= GDT_HW_GENERATION_VOLCANICISLAND && params.m_gen < GDT_HW_GENERATION_LAST)
    {
        cuDevice = new CLCUInfoVI();
    }
    else if (params.m_gen == GDT_HW_GENERATION_SOUTHERNISLAND || params.m_gen == GDT_HW_GENERATION_SEAISLAND)
    {
        cuDevice = new CLCUInfoSI();
    }
    else
    {
        return false;
    }

    cuDevice->SetCUParam(CU_PARAMS_KERNEL_NAME,        params.m_strKernelName);
    cuDevice->SetCUParam(CU_PARAMS_DEVICE_NAME,        params.m_strDeviceName);
    cuDevice->SetCUParam(CU_PARAMS_VECTOR_GPRS_MAX,    params.m_nMaxVGPRS);
    cuDevice->SetCUParam(CU_PARAMS_SCALAR_GPRS_MAX,    params.m_nMaxSGPRS);
    cuDevice->SetCUParam(CU_PARAMS_LDS_MAX,            params.m_nMaxLDS);
    cuDevice->SetCUParam(CU_PARAMS_VECTOR_GPRS_USED,   params.m_nUsedVGPRS);
    cuDevice->SetCUParam(CU_PARAMS_SCALAR_GPRS_USED,   params.m_nUsedSGPRS);
    cuDevice->SetCUParam(CU_PARAMS_LDS_USED,           params.m_nUsedLDS);
    cuDevice->SetCUParam(CU_PARAMS_WG_SIZE_MAX,        params.m_nMaxWGSize);
    cuDevice->SetCUParam(CU_PARAMS_GLOBAL_SIZE_MAX,    params.m_nMaxGlobalWorkSize);

    size_t nActiveWaves;
    cuDevice->ComputeNumActiveWaves(params.m_nWorkgroupSize, nActiveWaves);

    jqPlotChart chart1;
    jqPlotChart chart2;
    jqPlotChart chart3;

    chart1.m_strChartID = "chartVGPR";
    chart1.m_strChartName = "Number of waves limited by VGPRs";
    chart1.m_strXAxisName = "Number of VGPRs";
    chart1.m_strYAxisName = "Number of active wavefronts";
    chart1.m_strTooltipFormatString = "VGPR = %s<br/>Wave = %s";

    vector<float> ticksVGPR;
    ticksVGPR.push_back(0);
    ticksVGPR.push_back(64);
    ticksVGPR.push_back(128);
    ticksVGPR.push_back(192);
    ticksVGPR.push_back(256);
    chart1.SetXAxisTicks(ticksVGPR);

    float fPad = 1.2f;

    chart1.m_uiMaxXAxis = (unsigned int)((float)params.m_nMaxVGPRS * fPad);
    chart1.m_uiMinXAxis = 0;
    chart1.m_uiMaxYAxis = (unsigned int)(fPad * (float)params.m_nMaxWavesPerCU);
    chart1.m_uiMinYAxis = 0;
    chart1.AddData(jqPlotChartData((float)params.m_nUsedVGPRS, (float)nActiveWaves, true));

    jqPlotChart chartSGPR;

    if (params.m_gen >= GDT_HW_GENERATION_SOUTHERNISLAND && params.m_gen < GDT_HW_GENERATION_LAST)
    {
        chartSGPR.m_strChartID = "chartSGPR";
        chartSGPR.m_strChartName = "Number of waves limited by SGPRs";
        chartSGPR.m_strXAxisName = "Number of SGPRs";
        chartSGPR.m_strYAxisName = "Number of active wavefronts";
        chartSGPR.m_strTooltipFormatString = "SGPR = %s<br/>Wave = %s";

        vector<float> ticksSGPR;
        ticksSGPR.push_back(0);
        ticksSGPR.push_back(26);
        ticksSGPR.push_back(52);
        ticksSGPR.push_back(78);
        ticksSGPR.push_back(102);
        chartSGPR.SetXAxisTicks(ticksSGPR);

        chartSGPR.m_uiMaxXAxis = (unsigned int)((float)params.m_nMaxSGPRS * fPad);
        chartSGPR.m_uiMinXAxis = 0;
        chartSGPR.m_uiMaxYAxis = (unsigned int)(fPad * (float)params.m_nMaxWavesPerCU);
        chartSGPR.m_uiMinYAxis = 0;
        chartSGPR.AddData(jqPlotChartData((float)params.m_nUsedSGPRS, (float)nActiveWaves, true));
    }

    // Chart for LDS
    chart2.m_strChartID = "chartLDS";
    chart2.m_strChartName = "Number of waves limited by LDS";
    chart2.m_strXAxisName = "LDS Size ";
    chart2.m_strYAxisName = "Number of active wavefronts";
    chart2.m_strTooltipFormatString = "LDS = %s <br/>Wave = %s";
    chart2.m_uiMaxXAxis = (unsigned int)(fPad * params.m_nMaxLDS / BYTE_2_KBYTE_CONVERSION);
    chart2.m_uiMinXAxis = 0;
    chart2.m_uiMaxYAxis = (unsigned int)(fPad * (float)nMaxNumWavefronts);
    chart2.m_uiMinYAxis = 0;
    chart2.AddData(jqPlotChartData(((float)params.m_nUsedLDS / BYTE_2_KBYTE_CONVERSION), (float)nActiveWaves, true));

    vector<float> ticksLDS;
    ticksLDS.push_back(0.0f);
    ticksLDS.push_back(8.0f);
    ticksLDS.push_back(16.0f);
    ticksLDS.push_back(24.0f);
    ticksLDS.push_back(32.0f);
    chart2.m_strTickXFormatString = "%4.1fk";
    chart2.SetXAxisTicks(ticksLDS);

    // Chart for Workgroup size
    chart3.m_strChartID = "chartWGS";
    chart3.m_strChartName = "Number of waves limited by Work-group size";
    chart3.m_strXAxisName = "Work-group size";
    chart3.m_strYAxisName = "Number of active wavefronts";
    chart3.m_strTooltipFormatString = "Work-group size = %s<br/>Wave = %s";
    chart3.m_uiMaxXAxis = (unsigned int)(fPad * params.m_nMaxWGSize);
    chart3.m_uiMinXAxis = 0;
    chart3.m_uiMaxYAxis = (unsigned int)(fPad * (float)nMaxNumWavefronts);
    chart3.m_uiMinYAxis = 0;
    chart3.AddData(jqPlotChartData((float)params.m_nWorkgroupSize, (float)nActiveWaves, true));

    vector<float> ticksWG;
    ticksWG.push_back(0);
    ticksWG.push_back(64);
    ticksWG.push_back(128);
    ticksWG.push_back(192);
    ticksWG.push_back(256);
    chart3.SetXAxisTicks(ticksWG);

    string strLimitingFactor;
    strLimitingFactor.clear();

    if (params.m_fOccupancy < 100.0f)
    {
        size_t numLimitingVal = min(min(params.m_nLDSLimitedWaveCount, params.m_nVGPRLimitedWaveCount), params.m_nWGLimitedWaveCount);

        if (params.m_gen >= GDT_HW_GENERATION_SOUTHERNISLAND && params.m_gen < GDT_HW_GENERATION_LAST)
        {
            numLimitingVal = min((size_t)params.m_nSGPRLimitedWaveCount, numLimitingVal);

            if (params.m_nUsedSGPRS != 0 && params.m_nSGPRLimitedWaveCount == numLimitingVal)
            {
                strLimitingFactor += "SGPR";
                chartSGPR.m_strTitleColor = "#FF0000";
            }
        }

        if (params.m_nUsedVGPRS != 0 && params.m_nVGPRLimitedWaveCount == numLimitingVal)
        {
            if (!strLimitingFactor.empty())
            {
                strLimitingFactor += ", ";
            }

            strLimitingFactor += "VGPR";
            chart1.m_strTitleColor = "#FF0000";
        }

        if (params.m_nUsedLDS != 0 && params.m_nLDSLimitedWaveCount == numLimitingVal)
        {
            if (!strLimitingFactor.empty())
            {
                strLimitingFactor += ", ";
            }

            strLimitingFactor += "LDS";
            chart2.m_strTitleColor = "#FF0000";
        }

        if (params.m_nWGLimitedWaveCount == numLimitingVal)
        {
            if (!strLimitingFactor.empty())
            {
                strLimitingFactor += ", ";
            }

            strLimitingFactor += "Work-group size";
            chart3.m_strTitleColor = "#FF0000";
        }
    }
    else
    {
        strLimitingFactor = "None";
    }

    GenerateVGPRLimitedWFTables(cuDevice, chart1, params);
    GenerateLDSLimitedWFTable(cuDevice, chart2, params);
    GenerateWGLimitedWFTable(cuDevice, chart3, params);

    if (params.m_gen >= GDT_HW_GENERATION_SOUTHERNISLAND && params.m_gen < GDT_HW_GENERATION_LAST)
    {
        GenerateSGPRLimitedWFTables(cuDevice, chartSGPR, params);
    }

    // IE9 requires this tag to support convas
    fout << "<!DOCTYPE html>" << endl;
    fout << "<!-- saved from url=(0014)about:internet -->" << endl;
    fout << "<!--[if lt IE 9]><script language=\"javascript\" type=\"text/javascript\" src=\"excanvas.min.js\"></script><![endif]-->" << endl;
    fout << "<html lang=\"en\">" << endl;
    fout << "<head>" << endl;
    fout << "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">" << endl;
    fout << "<title>Kernel Occupancy</title>" << endl;

    // insert style

    fout << "<style type=\"text/css\">" << endl;
    fout << "th {" << endl;
    fout << "   font-size:1em;" << endl;
    fout << "   text-align:left;" << endl;
    fout << "   padding-top:5px;" << endl;
    fout << "   padding-bottom:4px;" << endl;
    fout << "   background-color:#969696;" << endl;
    fout << "   color:#fff;" << endl;
    fout << "}" << endl;
    fout << "td, th {" << endl;
    fout << "   font-size:0.85em;" << endl;
    fout << "   border:1px solid #969696;" << endl;
    fout << "   padding:3px 7px 2px 7px;" << endl;
    fout << "}" << endl;
    fout << "table {" << endl;
    fout << "   font-family:\"Trebuchet MS\", Arial, Helvetica, sans-serif;" << endl;
    fout << "   width:" TABLE_WIDTH ";" << endl;
    fout << "   border-collapse:collapse;" << endl;
    fout << "   margin-left: auto;" << endl;
    fout << "   margin-right: auto;" << endl;
    fout << "}" << endl;

    fout << ".title_row" << endl;
    fout << "{" << endl;
    fout << "   background-color:#C8BBBE;" << endl;
    fout << "   color:#fff;" << endl;
    fout << "}" << endl;

    fout << ".hightlight_row" << endl;
    fout << "{" << endl;
    fout << "   color:#FF0000;" << endl;
    fout << "   font-weight:bold;" << endl;
    fout << "}" << endl;
    fout << "</style>" << endl;

    jqPlotChart::WriteScriptDesc(fout);

    fout << "<script class=\"code\" language=\"javascript\" type=\"text/javascript\">" << endl;
    fout << "$(document).ready(function(){" << endl;

    // insert table here
    // Chart for GPR
    chart1.WriteToStream(fout);

    if (params.m_gen >= GDT_HW_GENERATION_SOUTHERNISLAND && params.m_gen < GDT_HW_GENERATION_LAST)
    {
        chartSGPR.WriteToStream(fout);
    }

    chart2.WriteToStream(fout);
    chart3.WriteToStream(fout);


    fout << "});" << endl;

    fout << "</script>" << endl;

    fout << "</head>" << endl;


    // document body
    fout << "<body";
    AddDisableSelectionCode(fout);
    fout << ">" << endl;

    // create table
    fout << "<table>" << endl;

    int nCells = (params.m_gen >= GDT_HW_GENERATION_SOUTHERNISLAND  && params.m_gen < GDT_HW_GENERATION_LAST) ? 4 : 3;
    fout << "<tr>" << endl;

    // row 0, cell 0
    fout << "<td>" << endl;
    fout << "<div id=\"chartWGS\" style=\"width:" CHART_WIDTH ";height:" TABLE_HEIGHT ";\"></div>" << endl;
    fout << "</td>" << endl;

    // row 0, cell 1
    fout << "<td>" << endl;
    fout << "<div id=\"chartVGPR\" style=\"width:" CHART_WIDTH ";height:" TABLE_HEIGHT ";\"></div>" << endl;
    fout << "</td>" << endl;

    if (params.m_gen >= GDT_HW_GENERATION_SOUTHERNISLAND && params.m_gen < GDT_HW_GENERATION_LAST)
    {
        fout << "<td>" << endl;
        fout << "<div id=\"chartSGPR\" style=\"width:" CHART_WIDTH ";height:" TABLE_HEIGHT ";\"></div>" << endl;
        fout << "</td>" << endl;
    }

    // row 0, cell 2
    fout << "<td>" << endl;
    fout << "<div id=\"chartLDS\" style=\"width:" CHART_WIDTH ";height:" TABLE_HEIGHT ";\"></div>" << endl;
    fout << "</td>" << endl;

    fout << "</tr>" << endl;

    // row 1, cell 1
    fout << "<tr>" << endl;
    fout << "<td colspan=\"" << nCells << "\">" << endl;
    CreateInfoTable(params, fout, strLimitingFactor);
    fout << "</td>" << endl;

    fout << "</tr>" << endl;

    fout << "</table>" << endl;

    fout << "</body>" << endl;
    fout << "</html>" << endl;

    fout.close();

    strError.clear();

    SAFE_DELETE(cuDevice);

    return true;
}
Exemplo n.º 27
0
bool CPVRGUIInfo::TranslateCharInfo(DWORD dwInfo, std::string &strValue) const
{
  bool bReturn(true);
  CSingleLock lock(m_critSection);

  switch(dwInfo)
  {
  case PVR_NOW_RECORDING_TITLE:
    CharInfoActiveTimerTitle(strValue);
    break;
  case PVR_NOW_RECORDING_CHANNEL:
    CharInfoActiveTimerChannelName(strValue);
    break;
  case PVR_NOW_RECORDING_CHAN_ICO:
    CharInfoActiveTimerChannelIcon(strValue);
    break;
  case PVR_NOW_RECORDING_DATETIME:
    CharInfoActiveTimerDateTime(strValue);
    break;
  case PVR_NEXT_RECORDING_TITLE:
    CharInfoNextTimerTitle(strValue);
    break;
  case PVR_NEXT_RECORDING_CHANNEL:
    CharInfoNextTimerChannelName(strValue);
    break;
  case PVR_NEXT_RECORDING_CHAN_ICO:
    CharInfoNextTimerChannelIcon(strValue);
    break;
  case PVR_NEXT_RECORDING_DATETIME:
    CharInfoNextTimerDateTime(strValue);
    break;
  case PVR_PLAYING_DURATION:
    CharInfoPlayingDuration(strValue);
    break;
  case PVR_PLAYING_TIME:
    CharInfoPlayingTime(strValue);
    break;
  case PVR_NEXT_TIMER:
    CharInfoNextTimer(strValue);
    break;
  case PVR_ACTUAL_STREAM_VIDEO_BR:
    CharInfoVideoBR(strValue);
    break;
  case PVR_ACTUAL_STREAM_AUDIO_BR:
    CharInfoAudioBR(strValue);
    break;
  case PVR_ACTUAL_STREAM_DOLBY_BR:
    CharInfoDolbyBR(strValue);
    break;
  case PVR_ACTUAL_STREAM_SIG:
    CharInfoSignal(strValue);
    break;
  case PVR_ACTUAL_STREAM_SNR:
    CharInfoSNR(strValue);
    break;
  case PVR_ACTUAL_STREAM_BER:
    CharInfoBER(strValue);
    break;
  case PVR_ACTUAL_STREAM_UNC:
    CharInfoUNC(strValue);
    break;
  case PVR_ACTUAL_STREAM_CLIENT:
    CharInfoPlayingClientName(strValue);
    break;
  case PVR_ACTUAL_STREAM_DEVICE:
    CharInfoFrontendName(strValue);
    break;
  case PVR_ACTUAL_STREAM_STATUS:
    CharInfoFrontendStatus(strValue);
    break;
  case PVR_ACTUAL_STREAM_CRYPTION:
    CharInfoEncryption(strValue);
    break;
  case PVR_ACTUAL_STREAM_SERVICE:
    CharInfoService(strValue);
    break;
  case PVR_ACTUAL_STREAM_MUX:
    CharInfoMux(strValue);
    break;
  case PVR_ACTUAL_STREAM_PROVIDER:
    CharInfoProvider(strValue);
    break;
  case PVR_BACKEND_NAME:
    CharInfoBackendName(strValue);
    break;
  case PVR_BACKEND_VERSION:
    CharInfoBackendVersion(strValue);
    break;
  case PVR_BACKEND_HOST:
    CharInfoBackendHost(strValue);
    break;
  case PVR_BACKEND_DISKSPACE:
    CharInfoBackendDiskspace(strValue);
    break;
  case PVR_BACKEND_CHANNELS:
    CharInfoBackendChannels(strValue);
    break;
  case PVR_BACKEND_TIMERS:
    CharInfoBackendTimers(strValue);
    break;
  case PVR_BACKEND_RECORDINGS:
    CharInfoBackendRecordings(strValue);
    break;
  case PVR_BACKEND_DELETED_RECORDINGS:
    CharInfoBackendDeletedRecordings(strValue);
    break;
  case PVR_BACKEND_NUMBER:
    CharInfoBackendNumber(strValue);
    break;
  case PVR_TOTAL_DISKSPACE:
    CharInfoTotalDiskSpace(strValue);
    break;
  case PVR_TIMESHIFT_START_TIME:
    CharInfoTimeshiftStartTime(strValue);
    break;
  case PVR_TIMESHIFT_END_TIME:
    CharInfoTimeshiftEndTime(strValue);
    break;
  case PVR_TIMESHIFT_PLAY_TIME:
    CharInfoTimeshiftPlayTime(strValue);
    break;
  default:
    strValue.clear();
    bReturn = false;
    break;
  }

  return bReturn;
}
Exemplo n.º 28
0
void
get_ref_seq(const char* ref_seq_file,
            std::string& ref_seq,
            const pos_range ref_segment)
{
    static const unsigned buff_size(50000);
    char buff[buff_size];

    std::ifstream ref_is(ref_seq_file);

    if ( ! ref_is )
    {
        log_os << "ERROR: Can't open reference sequence file: " << ref_seq_file << "\n";
        exit(EXIT_FAILURE);
    }

    unsigned line_no(1);
#ifdef SEQ_UTIL_VERBOSE
    log_os << "Reading from reference sequence file " << ref_seq_file << "\n";
#endif
    ref_is.getline(buff,buff_size);
#ifdef SEQ_UTIL_VERBOSE
    log_os << "First line: " << buff << "\n";
#endif

    if (buff[0] != '>')
    {
        log_os << "ERROR: Unexpected format in reference sequence file: " << ref_seq_file << " line_no: " << line_no << "\n"
               << "\tline: '" << buff << "'\n";
        exit(EXIT_FAILURE);
    }

    const pos_t begin_pos(ref_segment.is_begin_pos ? ref_segment.begin_pos : 0);
    pos_t ref_pos(0);

    ref_seq.clear();
    while (true)
    {
        ref_is.getline(buff,buff_size);
        if (! ref_is)
        {
            if     (ref_is.eof()) break;
            else if (ref_is.fail())
            {
                if (ref_is.bad())
                {
                    log_os << "ERROR: unexpected failure while attempting to read sequence file: " << ref_seq_file << "\n";
                    exit(EXIT_FAILURE);
                }
                ref_is.clear();
            }
        }
        line_no++;
        if (buff[0] == '>')
        {
            log_os << "ERROR: Unexpected format in reference sequence file: " << ref_seq_file << " line_no: " << line_no << "\n"
                   << "\tline: '" << buff << "'\n";
            exit(EXIT_FAILURE);
        }

        // correct for '\r' if present:
        pos_t rc(ref_is.gcount()-1);
        if (rc && (buff[rc-1]=='\r'))
        {
            buff[--rc]='\0';
        }
        if (ref_segment.is_end_pos)
        {
            if (ref_pos>=ref_segment.end_pos) break;
            if ((ref_pos+rc)>ref_segment.end_pos)
            {
                rc=(ref_segment.end_pos-ref_pos);
                buff[rc]='\0';
            }
        }
        if (ref_pos<begin_pos)
        {
            if ((ref_pos+rc) > begin_pos)
            {
                ref_seq += (buff+(begin_pos-ref_pos));
            }
        }
        else
        {
            ref_seq += buff;
        }
        ref_pos += rc;
    }

#ifdef SEQ_UTIL_VERBOSE
    log_os << "Finished reading from reference sequence file " << ref_seq_file << "\n";
    log_os << "Reference sequence size: " << ref_seq.size() << "\n";
#endif
}
Exemplo n.º 29
0
json_object* OGRGeoJSONSeqLayer::GetNextObject()
{
    m_osFeatureBuffer.clear();
    while( true )
    {
        // If we read all the buffer, then reload it from file
        if( m_nPosInBuffer >= m_nBufferValidSize )
        {
            if( m_nBufferValidSize < m_osBuffer.size() )
            {
                return nullptr;
            }
            m_nBufferValidSize = VSIFReadL(&m_osBuffer[0], 1,
                                           m_osBuffer.size(), m_fp);
            m_nPosInBuffer = 0;
            if( VSIFTellL(m_fp) == m_nBufferValidSize && m_nBufferValidSize > 0 )
            {
                m_bIsRSSeparated = (m_osBuffer[0] == RS);
                if( m_bIsRSSeparated )
                {
                    m_nPosInBuffer ++;
                }
            }
            m_nIter ++;

            if( m_nFileSize > 0 &&
                (m_nBufferValidSize < m_osBuffer.size() ||
                 (m_nIter % 100) == 0) )
            {
                CPLDebug("GeoJSONSeq", "First pass: %.2f %%",
                        100.0 * VSIFTellL(m_fp) / m_nFileSize);
            }
            if( m_nPosInBuffer >= m_nBufferValidSize )
            {
                return nullptr;
            }
        }

        // Find next feature separator in buffer
        const size_t nNextSepPos = m_osBuffer.find(
            m_bIsRSSeparated ? RS : '\n', m_nPosInBuffer);
        if( nNextSepPos != std::string::npos )
        {
            m_osFeatureBuffer.append(m_osBuffer.data() + m_nPosInBuffer,
                                     nNextSepPos - m_nPosInBuffer);
            m_nPosInBuffer = nNextSepPos + 1;
        }
        else
        {
            // No separator ? then accummulate
            m_osFeatureBuffer.append(m_osBuffer.data() + m_nPosInBuffer,
                                     m_nBufferValidSize - m_nPosInBuffer);
            if( m_osFeatureBuffer.size() > 100 * 1024 * 1024 )
            {
                CPLError(CE_Failure, CPLE_NotSupported,
                            "Too large feature");
                return nullptr;
            }
            m_nPosInBuffer = m_nBufferValidSize;
            if( m_nBufferValidSize == m_osBuffer.size() )
            {
                continue;
            }
        }

        if( !m_osFeatureBuffer.empty() )
        {
            json_object* poObject = nullptr;
            OGRJSonParse(m_osFeatureBuffer.c_str(), &poObject);
            if( json_object_get_type(poObject) == json_type_object )
            {
                return poObject;
            }
            json_object_put(poObject);
        }
    }
}
Exemplo n.º 30
0
void HelpFormatter::clearWord(std::ostream& ostr, int& pos, std::string& word, int indent) const
{
    formatWord(ostr, pos, word, indent);
    word.clear();
}