Пример #1
0
void hexdump(direction d, int fd, unsigned char *p, int n)
{
    register int l=0;
    char buf[78];
    unsigned char c;
#define hpos(x) (3*(x)+(((x)>7)?2:1))
#define apos(x) ((x)+60) /* (x+((x>7)?60:59)) */
#define hdigit(x) (((x)>9)?((x)-10+'a'):((x)+'0'))

    memset(buf, ' ', 77);
    buf[77]='\0';
    printf("%s %d:\n", (d==d_from) ? "From" : "To", fd);
    while (n-->0) {
	c=(unsigned char)*p++;
	buf[hpos(l)]   = hdigit(c>>4);
	buf[hpos(l)+1] = hdigit(c&15);
	buf[apos(l)] = (c<32||c>126) ? '.' : c;
	if (++l>15) {
	    puts(buf);
	    memset(buf, ' ', 77);
	    l=0;
	}
    }
    puts(buf);

#undef hpos
#undef apos
#undef hdigit
}
Пример #2
0
AusleihPos AusleihPos::parse(string a) {
	string kunde, cd, tag;
	Tokenizer tok(a, ';');

	cd = tok.getSubstr();
	kunde = tok.getSubstr();
	tag = tok.getSubstr();


	AusleihPos apos(CD::parse(cd), Kunde::parse(kunde), *DateFormatDE::parse(tag));

	return apos;
}
Пример #3
0
void DoSensePlayer( Mob* actor, Player* player )
{
	cml::vector3f playerpos = player->transform.position;
	cml::vector3f mob2player = actor->transform.position - playerpos;
	float angle_to_player = 0;
	actor->player_distance = cml::length( mob2player );
	bool player_visible = false;
	if( actor->player_distance < actor->vision.distance )
	{
		cml::vector2f mob_forward = GetForward( actor );
		angle_to_player = cml::deg(cml::signed_angle_2D( mob_forward, cml::vector2f(mob2player[0],mob2player[2]) ));

			if( abs(angle_to_player) < actor->vision.angle)
			{
				// comprobamos que no haya algun elemento del mapa interrumpiendo la visión
				b2Body* b = actor->GetPhysicBody();
				cml::vector3f actorpos = actor->transform.position;
				cml::vector3f playerpos = player->transform.position;
				if( actorpos != playerpos )
				{
					MyRayCB tehcb;
					tehcb.SetOrigin();
					b2Vec2 apos(-actorpos[0],-actorpos[2]);
					b2Vec2 ppos(-playerpos[0],-playerpos[2]);

					b->GetWorld()->RayCast( &tehcb, apos, ppos );

					// si el rayo NO ha colisionado con algun elemento del mapa, tenemos al player en el cono!
					player_visible = !tehcb.didcollide;
				}
			}
	}
	//if( !player_visible ) actor->angle_to_player = NO_PLAYER;
	actor->angle_to_player = angle_to_player;
	actor->player_visible = player_visible;
}
Пример #4
0
bool importXML::importOne(const QString &pFileName)
{

  QDomDocument doc(pFileName);
  if (!openDomDocument(pFileName, doc))
    return false;

  QString tmpfileName; // only set if we translate the file with XSLT
  if (DEBUG)
      qDebug("importXML::importOne(%s) doctype = %s",
             qPrintable(pFileName), qPrintable(doc.doctype().name()));
  if (doc.doctype().name() != "xtupleimport")
  {
    QString xsltfile;
    q.prepare("SELECT * FROM xsltmap "
              "WHERE ((xsltmap_doctype=:doctype OR xsltmap_doctype='')"
              "   AND (xsltmap_system=:system   OR xsltmap_system=''));");
    q.bindValue(":doctype", doc.doctype().name());
    q.bindValue(":system", doc.doctype().systemId());
    q.exec();
    if (q.first())
    {
      xsltfile = q.value("xsltmap_import").toString();
      //TODO: what if more than one row is found?
    }
    else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return false;
    }
    else
    {
      systemError(this,
                  tr("<p>Could not find a map for doctype '%1' and "
                     "system id '%2'. "
                     "Write an XSLT stylesheet to convert this to valid xtuple"
                     "import XML and add it to the Map of XSLT Import Filters.")
                      .arg(doc.doctype().name()).arg(doc.doctype().systemId()));
      return false;
    }

    // TODO: switch to use ExportHelper::XSLTConvert()?
    QTemporaryFile tmpfile(_defaultXMLDir + QDir::separator() +
                           doc.doctype().name() + "TOxtupleimport");
    tmpfile.setAutoRemove(false);
    if (! tmpfile.open())
    {
      systemError(this, tr("<p>Could not create a temporary file."));
      return false;
    }
    tmpfileName = tmpfile.fileName();
    tmpfile.close();

    if (_metrics->boolean("XSLTLibrary"))
    {
      systemError(this, "XSLT via internal library not yet supported");
      return false;
    }
    else
    {
      QStringList args = _externalCmd.split(" ", QString::SkipEmptyParts);
      QString command = args[0];
      args.removeFirst();
      args.replaceInStrings("%f", pFileName);
      if (QFile::exists(xsltfile))
        args.replaceInStrings("%x", xsltfile);
      else if (QFile::exists(_defaultXSLTDir + QDir::separator() + xsltfile))
        args.replaceInStrings("%x", _defaultXSLTDir + QDir::separator() + xsltfile);
      else
      {
        systemError(this, tr("Cannot find the XSLT file as either %1 or %2")
                          .arg(xsltfile)
                          .arg(_defaultXSLTDir + QDir::separator() + xsltfile));
        return false;
      }

      QProcess xslt(this);
      xslt.setStandardOutputFile(tmpfileName);
      xslt.start(command, args);
      QString commandline = command + " " + args.join(" ");
      QString errOutput;
      /* TODO: make the entire file-processing asynchronous
         this will keep the UI snappy and handle spurious errors
         like the occasional waitForFinished failure if the processing
         runs faster than expected.
       */
      if (! xslt.waitForStarted())
        errOutput = tr("Error starting XSLT Processing: %1\n%2")
                          .arg(commandline)
                          .arg(QString(xslt.readAllStandardError()));
      if (! xslt.waitForFinished())
        errOutput = tr("The XSLT Processor encountered an error: %1\n%2")
                          .arg(commandline)
                          .arg(QString(xslt.readAllStandardError()));
      if (xslt.exitStatus() !=  QProcess::NormalExit)
        errOutput = tr("The XSLT Processor did not exit normally: %1\n%2")
                          .arg(commandline)
                          .arg(QString(xslt.readAllStandardError()));
      if (xslt.exitCode() != 0)
        errOutput = tr("The XSLT Processor returned an error code: %1\nreturned %2\n%3")
                          .arg(commandline)
                          .arg(xslt.exitCode())
                          .arg(QString(xslt.readAllStandardError()));

      if (! errOutput.isEmpty())
      {
        systemError(this, errOutput);
        return false;
      }

      if (! openDomDocument(tmpfileName, doc))
        return false;
    }
  }

  /* xtupleimport format is very straightforward:
      top level element is xtupleimport
        second level elements are all table/view names (default to api schema)
          third level elements are all column names
     and there are no text nodes until third level

     wrap the import of an entire file in a single transaction so
     we can reimport files which have failures. however, if a
     view-level element has the ignore attribute set to true then
     rollback just that view-level element if it generates an error.
  */

  // the silent attribute provides the user the option to turn off 
  // the interactive message for the view-level element


  q.exec("BEGIN;");
  if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return false;
  }

  XSqlQuery rollback;
  rollback.prepare("ROLLBACK;");

  for (QDomElement viewElem = doc.documentElement().firstChildElement();
       ! viewElem.isNull();
       viewElem = viewElem.nextSiblingElement())
  {
    QStringList columnNameList;
    QStringList columnValueList;

    bool ignoreErr = (viewElem.attribute("ignore", "false").isEmpty() ||
                      viewElem.attribute("ignore", "false") == "true");

    bool silent = (viewElem.attribute("silent", "false").isEmpty() ||
                   viewElem.attribute("silent", "false") == "true");

    QString mode = viewElem.attribute("mode", "insert");
    QStringList keyList;
    if (! viewElem.attribute("key").isEmpty())
      keyList = viewElem.attribute("key").split(QRegExp(",\\s*"));

    QString viewName = viewElem.tagName();
    if (viewName.indexOf(".") > 0)
      ; // viewName contains . so accept that it's schema-qualified
    else if (! viewElem.attribute("schema").isEmpty())
      viewName = viewElem.attribute("schema") + "." + viewName;
    else // backwards compatibility - must be in the api schema
      viewName = "api." + viewName;

    // TODO: fix QtXML classes so they read default attribute values from the DTD
    // then remove this code
    if (mode.isEmpty())
      mode = "insert";
    else if (mode == "update" && keyList.isEmpty())
    {
      if (! viewElem.namedItem(viewName + "_number").isNull())
        keyList.append(viewName + "_number");
      else if (! viewElem.namedItem("order_number").isNull())
        keyList.append("order_number");
      else if (! ignoreErr)
      {
        rollback.exec();
        systemError(this, tr("Cannot process %1 element without a key attribute"));
        return false;
      }
      if (! viewElem.namedItem("line_number").isNull())
        keyList.append("line_number");
    }
    // end of code to remove

    QString savepointName = viewName;
    savepointName.remove(".");
    if (ignoreErr)
      q.exec("SAVEPOINT " + savepointName + ";");

    QRegExp apos("\\\\*'");

    for (QDomElement columnElem = viewElem.firstChildElement();
         ! columnElem.isNull();
         columnElem = columnElem.nextSiblingElement())
    {
      QString value = columnElem.attribute("value").isEmpty() ?
                              columnElem.text() : columnElem.attribute("value");

      columnNameList.append(columnElem.tagName());

      if (value.trimmed() == "[NULL]")
        columnValueList.append("NULL");
      else if (value.trimmed().startsWith("SELECT"))
        columnValueList.append("(" + value.trimmed() + ")");
      else if (columnElem.attribute("quote") == "false")
        columnValueList.append(value);
      else
        columnValueList.append("'" + value.replace(apos, "''") + "'");
    }

    QString sql;
    if (mode == "update")
    {
      QStringList whereList;
      for (int i = 0; i < keyList.size(); i++)
        whereList.append("(" + keyList[i] + "=" +
                         columnValueList[columnNameList.indexOf(keyList[i])] + ")");

      for (int i = 0; i < columnNameList.size(); i++)
        columnNameList[i].append("=" + columnValueList[i]);

      sql = "UPDATE " + viewName + " SET " +
            columnNameList.join(", ") +
            " WHERE (" + whereList.join(" AND ") + ");";
    }
    else if (mode == "insert")
      sql = "INSERT INTO " + viewName + " (" +
            columnNameList.join(", ") +
            " ) SELECT " +
            columnValueList.join(", ") + ";" ;
    else
    {
      if (ignoreErr)
        q.exec("ROLLBACK TO SAVEPOINT " + savepointName + ";");
      else
      {
        rollback.exec();
        systemError(this, tr("Could not process %1: invalid mode %2")
                            .arg(viewElem.tagName()).arg(mode));
        return false;
      }
    }

    if (DEBUG) qDebug("About to run this: %s", qPrintable(sql));
    q.exec(sql);
    if (q.lastError().type() != QSqlError::NoError)
    {
      if (ignoreErr)
      {
        QString warning = q.lastError().databaseText();
        q.exec("ROLLBACK TO SAVEPOINT " + savepointName + ";");
        if (! silent)
        {
          QMessageBox::warning(this, tr("Ignoring Error"),
                             tr("Ignoring database error while importing %1:\n\n%2")
                              .arg(viewElem.tagName())
                              .arg(warning));
        }                  
      }
      else
      {
        rollback.exec();
        systemError(this, tr("Error importing %1 %2\n\n").arg(pFileName).arg(tmpfileName) + q.lastError().databaseText(), __FILE__, __LINE__);
        return false;
      }
    }
    else if (ignoreErr)
      q.exec("RELEASE SAVEPOINT " + savepointName + ";");
  }

  q.exec("COMMIT;");
  if (q.lastError().type() != QSqlError::NoError)
  {
    rollback.exec();
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return false;
  }

  QFile file(pFileName);
  if (_metrics->value("XMLSuccessTreatment") == "Delete")
  {
    if (! file.remove())
    {
      systemError(this, tr("Could not remove %1 after successful processing (%2).")
                        .arg(pFileName).arg(file.error()));
      return false;
    }
  }
  else if (_metrics->value("XMLSuccessTreatment") == "Rename")
  {
    QString suffix = _metrics->value("XMLSuccessSuffix");
    if (suffix.isEmpty())
      suffix = ".done";

    QString newname = pFileName + suffix;
    for (int i = 0; QFile::exists(newname) ; i++)
      newname = pFileName + suffix + "." + QString::number(i);

    if (! file.rename(newname))
    {
      systemError(this, tr("Could not rename %1 to %2 after successful processing (%3).")
                        .arg(pFileName).arg(file.error()));
      return false;
    }
  }
  else if (_metrics->value("XMLSuccessTreatment") == "Move")
  {
    QString donedirName = _metrics->value("XMLSuccessDir");
    if (donedirName.isEmpty())
      donedirName = "done";
    if (QDir::isRelativePath(donedirName))
      donedirName = _defaultXMLDir + QDir::separator() + donedirName;

    QDir donedir(donedirName);
    if (! donedir.exists())
      donedir.mkpath(donedirName);

    QString newname = donedirName + QDir::separator() + QFileInfo(file).fileName(); 
    if (QFile::exists(newname))
      newname = newname + QDate::currentDate().toString(".yyyy.MM.dd");
    if (QFile::exists(newname))
      newname = newname + QDateTime::currentDateTime().toString(".hh.mm");
    if (QFile::exists(newname))
      newname = newname + QDateTime::currentDateTime().toString(".ss");

    if (! file.rename(newname))
    {
      systemError(this, tr("<p>Could not move %1 to %2 after successful processing (%3).")
                        .arg(pFileName).arg(newname).arg(file.error()));
      return false;
    }
  }

  // else if (_metrics->value("XMLSuccessTreatment") == "None") {}

  return true;
}