//-----------------------------------------------------------------------------
// Purpose: 
// Input  : pEntity - 
//			pList - 
// Output : 
//-----------------------------------------------------------------------------
static BOOL CheckTarget(CMapEntity *pEntity, CListBox *pList)
{
	LPCTSTR pszValue = pEntity->GetKeyValue("target");
	if (pszValue == NULL)	// no target
	{
		return(TRUE);
	}

	if (pEntity->IsClass("trigger_changelevel") || pEntity->IsClass("info_landmark"))
	{
		return(TRUE);
	}

	MDkeyvalue kv("targetname", pszValue);

	CMapWorld *pWorld = (CMapWorld*) pEntity->GetWorldObject(pEntity);

	if (pWorld->EnumChildren(ENUMMAPCHILDRENPROC(FindKeyValue), DWORD(&kv), MAPCLASS_TYPE(CMapEntity)))
	{
		// also check paths in world
		POSITION p = pWorld->m_Paths.GetHeadPosition();
		while(p)
		{
			CMapPath *pPath = pWorld->m_Paths.GetNext(p);
			if(!strcmpi(pPath->GetName(), pszValue))
				return TRUE;	// found it
		}

		// returned true - was not aborted prematurely - therefore there is
		// no matching targetname.
		AddError(pList, ErrorUnmatchedTarget, (DWORD)pszValue, pEntity);
	}

	return TRUE;
}
    void PropertyRestrictions<Key, KeyValue, Container>::ConfigureFromJsonAndKey( const Configuration * inputJson, const std::string& key )
    {
        // Make this optional.
        if( inputJson->Exist( key ) == false )
        {
            return;
        }

        // We have a list of json objects. The format/logic is as follows. For input:
        // [
        //  { "Character": "Good", "Income": "High" },
        //  { "Character": "Bad", "Income": "Low" }
        // ]
        // We give the intervention if the individuals has
        // Good Character AND High Income OR Bad Character AND Low Income.
        // So we AND together the elements of each json object and OR together these 
        // calculated truth values of the elements of the json array.
        json::QuickInterpreter s2sarray = (*inputJson)[key].As<json::Array>();
        for( int idx=0; idx < (*inputJson)[key].As<json::Array>().Size(); idx++ )
        {
            Container container;

            auto json_map = s2sarray[idx].As<json::Object>();
            for( auto data = json_map.Begin();
                      data != json_map.End();
                      ++data )
            {
                std::string key = data->name;
                std::string value = (std::string)s2sarray[idx][key].As< json::String >();
                KeyValue kv( key, value );
                container.Add( kv );
            }
            _restrictions.push_back( container );
        }
    }
Esempio n. 3
0
File: lang.cpp Progetto: Try/game
void Lang::load(const char *f, const wchar_t* iso3Code ) {
  lang.clear();
  leters.clear();

  ifstream fin( f );
  std::unordered_set<wchar_t, std::hash<size_t> > let;

  uint16_t ver, col;
  size_t c = 0;

  fin.read( (char*)&ver, sizeof(ver) );
  fin.read( (char*)&col, sizeof(col) );
  ++col;

  int lcode = 2;
  std::vector<int16_t> tmpBuf;
  std::wstring langName;
  for( int i=1; i<col; ++i ){
    size_t sz;
    fin.read( (char*)&sz, sizeof(sz) );
    langName.resize( sz );
    tmpBuf.resize( std::max(sz, tmpBuf.size()) );

    fin.read( (char*)&tmpBuf[0],   sz*sizeof(int16_t) );
    langName.assign( tmpBuf.begin(), tmpBuf.begin()+sz );

    if( langName==iso3Code )
      lcode = i;
    }

  fin.read( (char*)&c, sizeof(c) );

  std::vector<std::wstring> kv(col);

  for( size_t i=0; i<c; ++i ){
    for( int r=0; r<col; ++r ){
      std::wstring& str = kv[r];
      size_t sz = str.size();

      fin.read( (char*)&sz, sizeof(sz) );
      str.resize( sz );
      tmpBuf.resize( std::max(sz, tmpBuf.size()) );

      fin.read( (char*)&tmpBuf[0], sz*sizeof(int16_t) );

      str.assign( tmpBuf.begin(), tmpBuf.begin()+sz );

      for( size_t q=0; q<sz; ++q )
        let.insert(str[q]);
      }

    lang[kv[0]] = kv[lcode];
    }

  leters.assign( let.begin(), let.end() );
}
 void PropertyRestrictions<Key, KeyValue, Container>::Add( std::map< std::string, std::string >& rMap )
 {
     Container container;
     for( auto& entry : rMap )
     {
         KeyValue kv( entry.first, entry.second );
         container.Add( kv );
     }
     _restrictions.push_back( container );
 }
// Add a new element to the StringMap, or modify an existent one
bool StringMap::put(const char *key, const char *val) {
    int index = findElement(key);
    if(index != -1) {
        ((KeyValuePair*)c[index])->setValue(val);
        return false;
    }
    else {
        KeyValuePair kv(key, val);
        c.add(kv);
        return true;
    }
}
Esempio n. 6
0
	/**
	 * @return String-serialized dictionary
	 */
	inline std::string toString() const
	{
		std::string s;

		for(const_iterator kv(begin());kv!=end();++kv) {
			_appendEsc(kv->first.data(),(unsigned int)kv->first.length(),s);
			s.push_back('=');
			_appendEsc(kv->second.data(),(unsigned int)kv->second.length(),s);
			s.append(ZT_EOL_S);
		}

		return s;
	}
Esempio n. 7
0
ConfigMap::ConfigMap(int argc, char **argv, bool exitOnUnrecognizedArgument)
{
	// put args into std::strings so they are easier to manipulate
	std::vector<std::string> args;
	for (int i=0;i<argc;i++) {
		args.push_back(std::string(argv[i]));
	}

	if (args.size() < 2) {
		printArgumentHelpAndExit(args[0]);
	}

	std::string setupFile = args[1] + ".vrsetup";
	setupFile = DataFileUtils::findDataFile(setupFile);
	readFile(setupFile);

	// parse arguments
	if (args.size() > 2) {
		for (int i=2;i<args.size();i++) {
			if ((args[i] == "-f") || (args[i] == "--configfile")) {
				i++;
				if (i >= args.size())
					printArgumentHelpAndExit(args[0]);
				else
					readFile(decygifyPath(args[i]));
			}
			else if ((args[i] == "-c") || (args[i] == "--configval")) {
				i++;
				if (i >= args.size())
					printArgumentHelpAndExit(args[0]);
				else {
					std::string kv(args[i]);
					size_t e = kv.find("=");
					std::stringstream msg;
					msg << "Invalid key=value command line argument: \""+kv+"\"";
					MinVR::Logger::getInstance().assertMessage(e>0, msg.str().c_str());
					std::string key = kv.substr(0,e);
					std::string val = kv.substr(e+1);
					set(key, val);
				}
			}
			else if ((args[i] == "-h") || (args[i] == "--") || 
				(args[i] == "--help") || (args[i] == "-help")) {
					printArgumentHelpAndExit(args[0]);
			}
			else if (exitOnUnrecognizedArgument) {
				printArgumentHelpAndExit(args[0]);
			}
		}
	}
}
Esempio n. 8
0
void AbstractConfiguration::setRawWithEvent(const std::string& key, std::string value)
{
	KeyValue kv(key, value);
	if (_eventsEnabled)
	{
		propertyChanging(this, kv);
	}
	{
		Mutex::ScopedLock lock(_mutex);
		setRaw(key, value);
	}
	if (_eventsEnabled)
	{
		propertyChanged(this, kv);
	}
}
Esempio n. 9
0
SkKTXFile::KeyValue SkKTXFile::CreateKeyValue(const char *cstrKey, const char *cstrValue) {
    SkString key(cstrKey);
    SkString value(cstrValue);

    // Size of buffer is length of string plus the null terminators...
    size_t size = key.size() + 1 + value.size() + 1;

    SkAutoSMalloc<256> buf(size);
    uint8_t* kvBuf = reinterpret_cast<uint8_t*>(buf.get());
    memcpy(kvBuf, key.c_str(), key.size() + 1);
    memcpy(kvBuf + key.size() + 1, value.c_str(), value.size() + 1);

    KeyValue kv(size);
    SkAssertResult(kv.readKeyAndValue(kvBuf));
    return kv;
}
Esempio n. 10
0
void PluginKateTextFilter::slotEditFilter()
{
  if (!KAuthorized::authorizeKAction(QStringLiteral("shell_access"))) {
    KMessageBox::sorry(0,i18n(
        "You are not allowed to execute arbitrary external applications. If "
        "you want to be able to do this, contact your system administrator."),
        i18n("Access Restrictions"));
    return;
  }
  if (!KTextEditor::Editor::instance()->application()->activeMainWindow())
    return;

  KTextEditor::View* kv(KTextEditor::Editor::instance()->application()->activeMainWindow()->activeView());
  if (!kv) return;

  QDialog dialog(KTextEditor::Editor::instance()->application()->activeMainWindow()->window());

  Ui::TextFilterWidget ui;
  ui.setupUi(&dialog);
  ui.filterBox->setFocus();

  dialog.setWindowTitle(i18n("Text Filter"));

  KConfigGroup config(KSharedConfig::openConfig(), "PluginTextFilter");
  QStringList items = config.readEntry("Completion list", QStringList());
  copyResult = config.readEntry("Copy result", false);
  mergeOutput = config.readEntry("Merge output", true);
  ui.filterBox->setMaxCount(10);
  ui.filterBox->setHistoryItems(items, true);
  ui.copyResult->setChecked(copyResult);
  ui.mergeOutput->setChecked(mergeOutput);

  if (dialog.exec() == QDialog::Accepted) {
    copyResult = ui.copyResult->isChecked();
    mergeOutput = ui.mergeOutput->isChecked();
    const QString filter = ui.filterBox->currentText();
    if (!filter.isEmpty()) {
      ui.filterBox->addToHistory(filter);
      config.writeEntry("Completion list", ui.filterBox->historyItems());
      config.writeEntry("Copy result", copyResult);
      config.writeEntry("Merge output", mergeOutput);
      m_last_command = filter;
      runFilter(kv, filter);
    }
  }
}
Esempio n. 11
0
void PluginKateTextFilter::slotFilterProcessExited(int, QProcess::ExitStatus)
{
  KTextEditor::View* kv(KTextEditor::Editor::instance()->application()->activeMainWindow()->activeView());
  if (!kv) return;

  // Is there any error output to display?
  if (!mergeOutput && !m_stderrOutput.isEmpty())
  {
      QPointer<KTextEditor::Message> message = new KTextEditor::Message(
          xi18nc(
              "@info"
            , "<title>Result of:</title><nl /><pre><code>$ %1\n<nl />%2</code></pre>"
            , m_last_command
            , m_stderrOutput
            )
        , KTextEditor::Message::Error
        );
      message->setWordWrap(true);
      message->setAutoHide(1000);
      kv->document()->postMessage(message);
  }

  if (copyResult) {
    QApplication::clipboard()->setText(m_strFilterOutput);
    return;
  }

  // Do not even try to change the document if no result collected...
  if (m_strFilterOutput.isEmpty())
    return;

  KTextEditor::Document::EditingTransaction transaction(kv->document());

  KTextEditor::Cursor start = kv->cursorPosition();
  if (kv->selection()) {
    start = kv->selectionRange().start();
    kv->removeSelectionText();
  }

  kv->setCursorPosition(start); // for block selection

  kv->insertText(m_strFilterOutput);
}
scalar pressureSwirlInjector::averageVelocity
(
    const label i
) const
{

    const injectorType& it = sm_.injectors()[i].properties();

    scalar dt = it.teoi() - it.tsoi();

    scalar injectedMassFlow = it.mass()/(it.teoi()-it.tsoi());

    scalar injectionPressure = averagePressure(i);

    scalar Tav = it.integrateTable(it.T())/dt;
    scalar rhoFuel = sm_.fuels().rho(sm_.ambientPressure(), Tav, it.X());

    scalar kV = kv(i, injectedMassFlow, injectionPressure);

    return  kV*sqrt(2.0*(injectionPressure-sm_.ambientPressure())/rhoFuel);
}
    Request::Request(std::string data) : cookie(0)
    {
        std::stringstream ss(data);
        ss >> method >> uri >> version;

        if(uri != "/darkside")
            uri = Configuration::instance()->document_root() + uri;

        std::string line;
        getline(ss,line); // clear the newline character
        while(getline(ss,line,'\n') && !line.empty())
        {
            std::stringstream kv(line);
            std::pair<std::string,std::string> key_val;
            kv >> key_val.first >> key_val.second;
            if(key_val.first == "Cookie:")
              cookie = atoi(key_val.second.substr(key_val.second.find('=')+1).c_str());
            else
              headers.push_back(key_val);
        }

        getline(ss,line);
        body = line;
    }
Esempio n. 14
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;
	}
Esempio n. 15
0
void ccforest<T>::findAllRoots(int depth) {
  if(foundAllRoots) return;
  foundAllRoots = 1;
  Rtimer rt;
  rt_start(rt);

  if(depth > 5) {
	cerr << "WARNING: excessive recursion in ccforest (ignored)" << endl;
  }

  int explicitRootCount = 0;
  assert(!superTree);
  superTree = new ccforest<T>();

  if (stats)
    DEBUG_CCFOREST *stats << "sort edgeStream (by cclabel)): ";
  keyCmpKeyvalueType<T> fo;
  sort(&edgeStream, fo); /* XXX -changed this to use a cmp obj  */

  /* time forward processing */
  EMPQueueAdaptive<cckeyvalue,T> *pq =
	new EMPQueueAdaptive<cckeyvalue,T>();	/* parent queue */

  size_t streamLength = edgeStream->stream_len();
  T prevSrc = T(-1);
  T parent = T(-1);
  ccedge prevEdge;
  for(unsigned int i=0; i<streamLength; i++) {
	ccedge *e;
	AMI_err ae = edgeStream->read_item(&e);
	assert(ae == AMI_ERROR_NO_ERROR);

#if(0)
	if (stats) {
	    DEBUG_CCFOREST *stats << "------------------------------" << endl;
	    DEBUG_CCFOREST *stats << "processing edge " << *e << endl;
	}
	DEBUG_CCFOREST pq->print();
#endif

	if(*e == prevEdge) {
	  if (stats)
	    DEBUG_CCFOREST *stats << "\tduplicate " << *e << " removed\n";
	  continue; /* already have this done */
	}
	prevEdge = *e;

	if (stats)
	  DEBUG_CCFOREST *stats << "processing edge " << *e << endl;

	/* find root (assign parent) */
	if(e->src() != prevSrc) {
	  prevSrc = e->src();
	  cckeyvalue kv;
	  /* check if we have a key we don't use. */
	  while(pq->min(kv) && (kv.getPriority() < e->src())) {
		pq->extract_min(kv);
		assert(kv.src() >= kv.dst());
		removeDuplicates(kv.src(), kv.dst(), *pq);
		ae = rootStream->write_item(kv); /* save root */
		assert(ae == AMI_ERROR_NO_ERROR);	
	  }
	  /* try to find our root */
	  if(pq->min(kv) && ((e->src() == kv.getPriority()))) {
		pq->extract_min(kv);
		parent = kv.getValue();
		removeDuplicates(e->src(), parent, *pq);
	  } else {
		parent = e->src();		/* we are root */
		explicitRootCount++;
		/* technically, we could skip this part. the lookup function
           automatically assumes that values without parents are roots */
	  }

	  /* save result */
	  cckeyvalue kroot(e->src(), parent);
	  assert(kroot.src() >= kroot.dst());
	  ae = rootStream->write_item(kroot);
	  assert(ae == AMI_ERROR_NO_ERROR);
	}
#ifndef NDEBUG
	cckeyvalue kv2;
	assert(pq->is_empty() || (pq->min(kv2) && kv2.getPriority() > e->src()));
#endif

	/* insert */
	cckeyvalue kv(e->dst(), parent);
	assert(kv.src() >= kv.dst());
	pq->insert(kv);

	/* cout << "identified: " << kroot << endl; */
  }

  /* drain the priority queue */
  if (stats)
    DEBUG_CCFOREST *stats << "draining priority queue" << endl;
  while (!pq->is_empty()) {
	cckeyvalue kv;
	pq->extract_min(kv);
	assert(kv.src() >= kv.dst());
	if (stats)
	  DEBUG_CCFOREST *stats << "processing edge " << kv << endl;

	removeDuplicates(kv.src(), kv.dst(), *pq);
	AMI_err ae = rootStream->write_item(kv);
	assert(ae == AMI_ERROR_NO_ERROR);
  }
  delete pq;

  /* note that rootStream is naturally ordered by src */

  if(superTree->size()) {
        if (stats) {
	    DEBUG_CCFOREST *stats << "resolving cycles..." << endl;
	    /* printStream(rootStream); */
	    DEBUG_CCFOREST *stats << "sort rootStream: ";
        }

	AMI_STREAM<cckeyvalue> *sortedRootStream; 
	dstCmpKeyvalueType<T> dstfo;
	sortedRootStream = sort(rootStream, dstfo); 
	/* XXX replaced this to use a cmp object -- laura
	   AMI_STREAM<cckeyvalue>*sortedRootStream=new AMI_STREAM<cckeyvalue>();
	   AMI_err ae = AMI_sort(rootStream, sortedRootStream, valueCmp); 
	   assert(ae == AMI_ERROR_NO_ERROR);
	*/
	delete rootStream;

	cckeyvalue *kv;
	T parent;
	AMI_err ae;
	
	AMI_STREAM<cckeyvalue>* relabeledRootStream
	  = new AMI_STREAM<cckeyvalue>();
	ae = sortedRootStream->seek(0);
	superTree->findAllRoots(depth+1);
	while((ae = sortedRootStream->read_item(&kv)) == AMI_ERROR_NO_ERROR) {
	  parent = superTree->findNextRoot(kv->dst());
	  ae = relabeledRootStream->write_item(cckeyvalue(kv->src(), parent));
	  assert(ae == AMI_ERROR_NO_ERROR);
	}
	delete sortedRootStream;

        if (stats)
	    DEBUG_CCFOREST *stats << "sort relabeledRootStream: ";
	rootStream = sort(relabeledRootStream, fo);
	/* laura: changed  this
	   rootStream = new AMI_STREAM<cckeyvalue>();
	   ae = AMI_sort(relabeledRootStream, rootStream);
	   assert(ae == AMI_ERROR_NO_ERROR);
	*/
	delete relabeledRootStream;

        if (stats)
	    DEBUG_CCFOREST *stats << "resolving cycles... done." << endl;
  }
  rootStream->seek(0);

  if (stats){
    DEBUG_CCFOREST *stats << "Rootstream length="
					  << rootStream->stream_len() << endl;
    DEBUG_CCFOREST printStream(*stats, rootStream);
    DEBUG_CCFOREST *stats << "Explicit root count=" << explicitRootCount << endl;
  }

  rt_stop(rt);
  if (stats)
    stats->recordTime("ccforest::findAllRoots",  (long int)rt_seconds(rt));
}
Esempio n. 16
0
bool SkKTXFile::readKTXFile(const uint8_t* data, size_t dataLen) {
    const uint8_t *buf = data;
    size_t bytesLeft = dataLen;

    // Make sure original KTX header is there... this should have been checked
    // already by a call to is_ktx()
    SkASSERT(bytesLeft > KTX_FILE_IDENTIFIER_SIZE);
    SkASSERT(0 == memcmp(KTX_FILE_IDENTIFIER, buf, KTX_FILE_IDENTIFIER_SIZE));
    buf += KTX_FILE_IDENTIFIER_SIZE;
    bytesLeft -= KTX_FILE_IDENTIFIER_SIZE;

    // Read header, but first make sure that we have the proper space: we need
    // two 32-bit ints: 1 for endianness, and another for the mandatory image
    // size after the header.
    if (bytesLeft < 8 + sizeof(Header)) {
        return false;
    }

    uint32_t endianness = this->readInt(&buf, &bytesLeft);
    fSwapBytes = kKTX_ENDIANNESS_CODE != endianness;

    // Read header values
    fHeader.fGLType                = this->readInt(&buf, &bytesLeft);
    fHeader.fGLTypeSize            = this->readInt(&buf, &bytesLeft);
    fHeader.fGLFormat              = this->readInt(&buf, &bytesLeft);
    fHeader.fGLInternalFormat      = this->readInt(&buf, &bytesLeft);
    fHeader.fGLBaseInternalFormat  = this->readInt(&buf, &bytesLeft);
    fHeader.fPixelWidth            = this->readInt(&buf, &bytesLeft);
    fHeader.fPixelHeight           = this->readInt(&buf, &bytesLeft);
    fHeader.fPixelDepth            = this->readInt(&buf, &bytesLeft);
    fHeader.fNumberOfArrayElements = this->readInt(&buf, &bytesLeft);
    fHeader.fNumberOfFaces         = this->readInt(&buf, &bytesLeft);
    fHeader.fNumberOfMipmapLevels  = this->readInt(&buf, &bytesLeft);
    fHeader.fBytesOfKeyValueData   = this->readInt(&buf, &bytesLeft);

    // Check for things that we understand...
    {
        // First, we only support compressed formats and single byte
        // representations at the moment. If the internal format is
        // compressed, the the GLType field in the header must be zero.
        // In the future, we may support additional data types (such
        // as GL_UNSIGNED_SHORT_5_6_5)
        if (fHeader.fGLType != 0 && fHeader.fGLType != GR_GL_UNSIGNED_BYTE) {
            return false;
        }

        // This means that for well-formatted KTX files, the glTypeSize
        // field must be one...
        if (fHeader.fGLTypeSize != 1) {
            return false;
        }

        // We don't support 3D textures.
        if (fHeader.fPixelDepth > 1) {
            return false;
        }

        // We don't support texture arrays
        if (fHeader.fNumberOfArrayElements > 1) {
            return false;
        }

        // We don't support cube maps
        if (fHeader.fNumberOfFaces > 1) {
            return false;
        }

        // We don't support width and/or height <= 0
        if (fHeader.fPixelWidth <= 0 || fHeader.fPixelHeight <= 0) {
            return false;
        }
    }

    // Make sure that we have enough bytes left for the key/value
    // data according to what was said in the header.
    if (bytesLeft < fHeader.fBytesOfKeyValueData) {
        return false;
    }

    // Next read the key value pairs
    size_t keyValueBytesRead = 0;
    while (keyValueBytesRead < fHeader.fBytesOfKeyValueData) {
        uint32_t keyValueBytes = this->readInt(&buf, &bytesLeft);
        keyValueBytesRead += 4;

        if (keyValueBytes > bytesLeft) {
            return false;
        }

        KeyValue kv(keyValueBytes);
        if (!kv.readKeyAndValue(buf)) {
            return false;
        }

        fKeyValuePairs.push_back(kv);

        uint32_t keyValueBytesPadded = (keyValueBytes + 3) & ~3;
        buf += keyValueBytesPadded;
        keyValueBytesRead += keyValueBytesPadded;
        bytesLeft -= keyValueBytesPadded;
    }

    // Read the pixel data...
    int mipmaps = SkMax32(fHeader.fNumberOfMipmapLevels, 1);
    SkASSERT(mipmaps == 1);

    int arrayElements = SkMax32(fHeader.fNumberOfArrayElements, 1);
    SkASSERT(arrayElements == 1);

    int faces = SkMax32(fHeader.fNumberOfFaces, 1);
    SkASSERT(faces == 1);

    int depth = SkMax32(fHeader.fPixelDepth, 1);
    SkASSERT(depth == 1);

    for (int mipmap = 0; mipmap < mipmaps; ++mipmap) {
        // Make sure that we have at least 4 more bytes for the first image size
        if (bytesLeft < 4) {
            return false;
        }

        uint32_t imgSize = this->readInt(&buf, &bytesLeft);

        // Truncated file.
        if (bytesLeft < imgSize) {
            return false;
        }

        // !FIXME! If support is ever added for cube maps then the padding
        // needs to be taken into account here.
        for (int arrayElement = 0; arrayElement < arrayElements; ++arrayElement) {
            for (int face = 0; face < faces; ++face) {
                for (int z = 0; z < depth; ++z) {
                    PixelData pd(buf, imgSize);
                    fPixelData.append(1, &pd);
                }
            }
        }
        
        uint32_t imgSizePadded = (imgSize + 3) & ~3;
        buf += imgSizePadded;
        bytesLeft -= imgSizePadded;
    }

    return bytesLeft == 0;
}
Esempio n. 17
0
    int accuracyTest(const char* test_path) {
      std::shared_ptr<easypr::Kv> kv(new easypr::Kv);
      kv->load("etc/chinese_mapping");

      map<string, vector<CPlate>> xmlMap;
      string path(test_path);
      path = path + "/GroundTruth.xml";
      getGroundTruth(xmlMap, path.c_str());

      //cout << xmlMap.size() << endl;
      //cout << xmlMap.begin()->first << endl;
      //vector<CPlate> plateVec = xmlMap.begin()->second;
      //cout << plateVec[0].getPlateStr() << endl;

      XMLNode xMainNode = XMLNode::createXMLTopNode("tagset");
#ifdef OS_WINDOWS
      XMLNode::setGlobalOptions(XMLNode::char_encoding_GBK);
#endif
      auto files = Utils::getFiles(test_path);

      std::string path_result = "result/Result.xml";

      CPlateRecognize pr;

      // 设置Debug模式

      pr.setDebug(false);

      pr.setLifemode(true);

      // 设置要处理的一张图片中最多有多少车牌

      pr.setMaxPlates(4);

      pr.setDetectType(PR_DETECT_COLOR | PR_DETECT_SOBEL);
      //pr.setDetectType(PR_DETECT_CMSER);

      int size = files.size();

      if (0 == size) {
        cout << "No File Found in general_test/native_test!" << endl;
        return 0;
      }

      cout << "Begin to test the easypr accuracy!" << endl;

      // 总的测试图片数量

      int count_all = 0;

      // 错误的图片数量

      int count_err = 0;

      // 未识别的图片数量

      int count_norecogin = 0;

      std::list<std::string> not_recognized_files;

      // 总的字符差距

      float diff_all = 0;

      // 平均字符差距

      float diff_avg = 0;

      // 完全匹配的识别次数

      float match_count = 0;

      // 完全匹配的识别次数所占识别图片中的比例

      float match_rate = 0;

      // 开始和结束时间

      time_t begin, end;
      time(&begin);

      for (int i = 0; i < size; i++) {
        string filepath = files[i].c_str();

        // EasyPR开始判断车牌

        Mat src = imread(filepath);

        // 如果是非图像文件,直接过去

        if (!src.data) continue;

        cout << "------------------" << endl;

        // 获取真实的车牌

        string plateLicense = Utils::getFileName(filepath);
        cout << kv->get("original_plate") << ":" << plateLicense << endl;

        XMLNode xNode = xMainNode.addChild("image");
        xNode.addChild("imageName").addText(plateLicense.c_str());

        map<string, vector<CPlate>>::iterator it;

        it = xmlMap.find(plateLicense);
        if (it != xmlMap.end()) {
          cout << it->first << endl;
          vector<CPlate> plateVec = it->second;
          for (auto plate : plateVec) {
            cout << plate.getPlateStr() << " (g)" << endl;
          }
        }

        XMLNode rectangleNodes = xNode.addChild("taggedRectangles");
        vector<CPlate> plateVec;

        int result = pr.plateRecognize(src, plateVec);
        //int result = pr.plateRecognizeAsText(src, plateVec);
        if (result == 0) {
          int num = plateVec.size();

          if (num == 0) {
            cout << kv->get("empty_plate") << endl;
            if (plateLicense != kv->get("empty_plate")) {
              not_recognized_files.push_back(plateLicense);
              count_norecogin++;
            }
          }
          else if (num > 1) {

            // 多车牌使用diff最小的那个记录

            int mindiff = 10000;
            for (int j = 0; j < num; j++) {
              cout << plateVec[j].getPlateStr() << " (" << j + 1 << ")" << endl;

              XMLNode rectangleNode = rectangleNodes.addChild("taggedRectangle");
              RotatedRect rr = plateVec[j].getPlatePos();
              LocateType locateType = plateVec[j].getPlateLocateType();

              rectangleNode.addAttribute("x", to_string((int)rr.center.x).c_str());
              rectangleNode.addAttribute("y", to_string((int)rr.center.y).c_str());
              rectangleNode.addAttribute("width", to_string((int)rr.size.width).c_str());
              rectangleNode.addAttribute("height", to_string((int)rr.size.height).c_str());

              rectangleNode.addAttribute("rotation", to_string((int)rr.angle).c_str());
              rectangleNode.addAttribute("locateType", to_string(locateType).c_str());
              rectangleNode.addText(plateVec[j].getPlateStr().c_str());

              string colorplate = plateVec[j].getPlateStr();

              // 计算"蓝牌:苏E7KU22"中冒号后面的车牌大小"

              vector<string> spilt_plate = Utils::splitString(colorplate, ':');

              int size = spilt_plate.size();
              if (size == 2 && spilt_plate[1] != "") {
                int diff = utils::levenshtein_distance(plateLicense,
                  spilt_plate[size - 1]);
                if (diff < mindiff) mindiff = diff;
              }
            }

            cout << kv->get("diff") << ":" << mindiff << kv->get("char") << endl;
            if (mindiff == 0) {

              // 完全匹配

              match_count++;
            }
            diff_all = diff_all + mindiff;
          }
          else {

            // 单车牌只计算一次diff

            for (int j = 0; j < num; j++) {
              cout << plateVec[j].getPlateStr() << endl;

              XMLNode rectangleNode = rectangleNodes.addChild("taggedRectangle");
              RotatedRect rr = plateVec[j].getPlatePos();
              LocateType locateType = plateVec[j].getPlateLocateType();

              rectangleNode.addAttribute("x", to_string((int)rr.center.x).c_str());
              rectangleNode.addAttribute("y", to_string((int)rr.center.y).c_str());
              rectangleNode.addAttribute("width", to_string((int)rr.size.width).c_str());
              rectangleNode.addAttribute("height", to_string((int)rr.size.height).c_str());

              rectangleNode.addAttribute("rotation", to_string((int)rr.angle).c_str());
              rectangleNode.addAttribute("locateType", to_string(locateType).c_str());
              rectangleNode.addText(plateVec[j].getPlateStr().c_str());

              string colorplate = plateVec[j].getPlateStr();

              // 计算"蓝牌:苏E7KU22"中冒号后面的车牌大小"

              vector<string> spilt_plate = Utils::splitString(colorplate, ':');

              int size = spilt_plate.size();
              if (size == 2 && spilt_plate[1] != "") {
                int diff = utils::levenshtein_distance(plateLicense,
                  spilt_plate[size - 1]);
                cout << kv->get("diff") << ":" << diff << kv->get("char") << endl;

                if (diff == 0) {

                  // 完全匹配

                  match_count++;
                }
                diff_all = diff_all + diff;
              }
            }
          }
        }
        else {
          cout << kv->get("error_code") << ":" << result << endl;
          count_err++;
        }
        count_all++;
      }
      time(&end);

      cout << "------------------" << endl;
      cout << "Easypr accuracy test end!" << endl;
      cout << "------------------" << endl;
      cout << endl;
      cout << kv->get("summaries") << ":" << endl;
      cout << kv->get("sum_pictures") << ":" << count_all << ",  ";
      cout << kv->get("unrecognized") << ":" << count_norecogin << ",  ";

      xMainNode.writeToFile(path_result.c_str());

      float count_recogin = float(count_all - (count_err + count_norecogin));
      float count_rate = count_recogin / count_all;
      cout << kv->get("locate_rate") << ":" << count_rate * 100 << "%  " << endl;

      if (count_recogin > 0) {
        diff_avg = diff_all / count_recogin;
      }

      if (count_recogin > 0) {
        match_rate = match_count / count_recogin * 100;
      }

      cout << kv->get("diff_average") << ":" << diff_avg << ",  ";
      cout << kv->get("full_match") << ":" << match_count << ",  ";
      cout << kv->get("full_rate") << ":" << match_rate << "%  " << endl;

      double seconds = difftime(end, begin);
      double avgsec = seconds / double(count_all);

      cout << kv->get("seconds") << ":" << seconds << kv->get("sec") << ",  ";
      cout << kv->get("seconds_average") << ":" << avgsec << kv->get("sec") << endl;

      cout << kv->get("unrecognized") << ":" << endl;

      for (auto it = not_recognized_files.begin(); it != not_recognized_files.end();
        ++it) {
        cout << *it << endl;
      }

      cout << endl;

      cout << "------------------" << endl;

      ofstream myfile("accuracy.txt", ios::app);
      if (myfile.is_open()) {
        time_t t = time(0);  // get time now
        struct tm* now = localtime(&t);
        char buf[80];

        strftime(buf, sizeof(buf), "%Y-%m-%d %X", now);
        myfile << string(buf) << endl;

        myfile << kv->get("sum_pictures") << ":" << count_all << ",  ";
        myfile << kv->get("unrecognized") << ":" << count_norecogin << ",  ";
        myfile << kv->get("locate_rate") << ":" << count_rate * 100 << "%  "
          << endl;
        myfile << kv->get("diff_average") << ":" << diff_avg << ",  ";
        myfile << kv->get("full_match") << ":" << match_count << ",  ";
        myfile << kv->get("full_rate") << ":" << match_rate << "%  " << endl;
        myfile << kv->get("seconds") << ":" << seconds << kv->get("sec") << ",  ";
        myfile << kv->get("seconds_average") << ":" << avgsec << kv->get("sec")
          << endl;
        myfile.close();
      }
      else {
        cout << "Unable to open file";
      }
      return 0;
    }