int KHistogram::read(FILE *fp, int format) {
  reset();

  if (fp == NULL) return 1;

  if (format == 0 || format == 1 || format == 2 || format == 3) {
    // get number of bands
    int b = 0;
    if (fscanf(fp, "%d", &b) != 1) return 2;
    if (b < 1 || b > _size) return 3;
    _bands = b;

    // read the contents of each band
    for (b = 0; b < _bands; b++) {
      if (band(b).read(fp, format) != 0) {
        reset();
        return 4;
      }
    }
  } else if (format == 4) {
    // aubin format

    // get number of bands
    int b = 0;
    if (fscanf(fp, "%d", &b) != 1) return 2;
    if (b < 1 || b > _size) return 3;
    _bands = b;

    // get number of bins
    int n = 0;
    if (fscanf(fp, "%d", &n) != 1) return 4;
    if (n < 1) return 5;
    for (b = 0; b < _bands; b++)
      if (n > band(b).size()) return 6;

    // set the number of bins in each band
    for (b = 0; b < _bands; b++) band(b).bins() = n;

    // read the contents of each band
    for (b = 0; b < _bands; b++) {
      if (band(b).read(fp, format) != 0) {
        reset();
        return 7;
      }
    }
  } else
    return 7;

  return 0;
}
/*
callback for sensor driver to update the value, e.g. if the sampled value changes
can be called for every sample acquisition
this will evaluate the sample against the reporting criteria and schedule a report 
if a reportable event occurs
*/
void on_update(sample s)// callback from sensor driver, e.g. on changing value 
{
    if (band(s) != last_band || s >= high_step || s <= low_step){ // test limits
        schedule_report(s);
    }
    return;
}
void KHistogram::reset() {
  // reset number of active bands
  _bands = 0;

  // reset band objects
  for (int i = 0; i < _size; i++) band(i).reset();
}
int KHistogram::accumulate(KHistogram &h) {
  if (_bands != h.bands()) {
    return 1;
  }

  for (int i = 0; i < size(); i++) band(i).accumulate(h.band(i));

  return 0;
}
int KHistogram::histogramGDAL(GDALDataset *dataset) {
  int numBands = dataset->GetRasterCount();
  if (numBands < 1 || numBands > size()) return 1;
  size() = numBands;

  for (int i = 0; i < size(); i++)
    if (band(i).histogramGDAL(dataset->GetRasterBand(i + 1)) != 0) return 2;

  return 0;
}
void QgsPalettedRasterRenderer::toSld( QDomDocument &doc, QDomElement &element, const QgsStringMap &props ) const
{
  QgsStringMap newProps = props;

  // create base structure
  QgsRasterRenderer::toSld( doc, element, props );

  // look for RasterSymbolizer tag
  QDomNodeList elements = element.elementsByTagName( QStringLiteral( "sld:RasterSymbolizer" ) );
  if ( elements.size() == 0 )
    return;

  // there SHOULD be only one
  QDomElement rasterSymbolizerElem = elements.at( 0 ).toElement();

  // add Channel Selection tags
  QDomElement channelSelectionElem = doc.createElement( QStringLiteral( "sld:ChannelSelection" ) );
  rasterSymbolizerElem.appendChild( channelSelectionElem );

  // for the mapped band
  QDomElement channelElem = doc.createElement( QStringLiteral( "sld:GrayChannel" ) );
  channelSelectionElem.appendChild( channelElem );

  // set band
  QDomElement sourceChannelNameElem = doc.createElement( QStringLiteral( "sld:SourceChannelName" ) );
  sourceChannelNameElem.appendChild( doc.createTextNode( QString::number( band() ) ) );
  channelElem.appendChild( sourceChannelNameElem );

  // add ColorMap tag
  QDomElement colorMapElem = doc.createElement( QStringLiteral( "sld:ColorMap" ) );
  colorMapElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "values" ) );
  if ( this->classes().size() >= 255 )
    colorMapElem.setAttribute( QStringLiteral( "extended" ), QStringLiteral( "true" ) );
  rasterSymbolizerElem.appendChild( colorMapElem );

  // for each color set a ColorMapEntry tag nested into "sld:ColorMap" tag
  // e.g. <ColorMapEntry color="#EEBE2F" quantity="-300" label="label" opacity="0"/>
  QList<QgsPalettedRasterRenderer::Class> classes = this->classes();
  QList<QgsPalettedRasterRenderer::Class>::const_iterator classDataIt = classes.constBegin();
  for ( ; classDataIt != classes.constEnd();  ++classDataIt )
  {
    QDomElement colorMapEntryElem = doc.createElement( QStringLiteral( "sld:ColorMapEntry" ) );
    colorMapElem.appendChild( colorMapEntryElem );

    // set colorMapEntryElem attributes
    colorMapEntryElem.setAttribute( QStringLiteral( "color" ), classDataIt->color.name() );
    colorMapEntryElem.setAttribute( QStringLiteral( "quantity" ), QString::number( classDataIt->value ) );
    colorMapEntryElem.setAttribute( QStringLiteral( "label" ), classDataIt->label );
    if ( classDataIt->color.alphaF() != 1.0 )
    {
      colorMapEntryElem.setAttribute( QStringLiteral( "opacity" ), QString::number( classDataIt->color.alphaF() ) );
    }
  }
}
Example #7
0
int main(int argc, char **argv) {
  QApplication app(argc, argv);
  QRubberBand band(QRubberBand::Rectangle);

  QPalette pal;
  pal.setBrush(QPalette::Highlight, QBrush(Qt::red));
  band.setPalette(pal);

  band.resize(30, 30);
  band.show();
  return app.exec();
}
int KHistogram::apply(GDALDataset *dataset) {
  int numBands = dataset->GetRasterCount();
  if (numBands < 1 || numBands > size())  // bands in dataset
    return 1;
  if (numBands > size())  // bands in histogram/LUT
    numBands = size();

  for (int i = 0; i < numBands; i++)
    if (band(i).apply(dataset->GetRasterBand(i + 1)) != 0) return 2;

  return 0;
}
int KHistogram::write(FILE *fp, int format) {
  if (fp == NULL) return 1;
  if (_bands == 0) return 2;

  // make sure that the bands have a valid number of bins
  int b;
  for (b = 0; b < _bands; b++)
    if (band(b).bins() < 1) return 3;

  if (format == 0 || format == 1 || format == 2 || format == 3) {
    // describe number of bands
    fprintf(fp, "%d\n", _bands);

    // write the contents of each band
    for (b = 0; b < _bands; b++) band(b).write(fp, format);
  } else if (format == 4) {
    // aubin format

    // make sure that the bands have the same number of bins
    for (b = 1; b < _bands; b++)
      if (band(b - 1).bins() != band(b).bins()) return 4;

    // describe number of bands     and uniform number of bins in each
    fprintf(fp, "%d %d\n", _bands, band(0).bins());

    // write the contents of each band
    for (b = 0; b < _bands; b++) band(b).write(fp, format);
  } else
    return 5;

  return 0;
}
Example #10
0
cholmod_sparse *CHOLMOD(band)
(
    /* ---- input ---- */
    cholmod_sparse *A,	/* matrix to extract band matrix from */
    long k1,		/* ignore entries below the k1-st diagonal */
    long k2,		/* ignore entries above the k2-nd diagonal */
    int mode,		/* >0: numerical, 0: pattern, <0: pattern (no diag) */
    /* --------------- */
    cholmod_common *Common
)
{
    return (band (A, k1, k2, mode, FALSE, Common)) ;
}
int KHistogram::histogram(GDALDataset *dataset) {
  int numBands = dataset->GetRasterCount();
  if (numBands < 1) return 1;
  if (numBands <= size()) {
    size() = numBands;
  } else {
    // leave size alone & just process those the number asked for
  }

  for (int i = 0; i < size(); i++)
    if (band(i).histogram(dataset->GetRasterBand(i + 1)) != 0) return 2;

  return 0;
}
Example #12
0
int CHOLMOD(band_inplace)
(
    /* ---- input ---- */
    long k1,		/* ignore entries below the k1-st diagonal */
    long k2,		/* ignore entries above the k2-nd diagonal */
    int mode,		/* >0: numerical, 0: pattern, <0: pattern (no diag) */
    /* ---- in/out --- */
    cholmod_sparse *A,	/* matrix from which entries not in band are removed */
    /* --------------- */
    cholmod_common *Common
)
{
    return (band (A, k1, k2, mode, TRUE, Common) != NULL) ;
}
/*
for reporting a sample that satisfies the reporting criteria and resetting the state machine
*/
int report_sample(sample s)
{
    if(send_notification(s)){  // sends current_sample if observing is on
        last_band = band(s); // limits state machine
        high_step = s + LWM2M_step; // reset floating band upper limit defined by step
        low_step = s - LWM2M_step; // reset floating band lower limit defined by step
        pmin_timer.detach();
        pmin_exceeded = false; // state machine to inhibit reporting at intervals < pmin
        pmin_timer.attach(&on_pmin, LWM2M_pmin);
        pmax_timer.detach();
        pmax_timer.attach(&on_pmax, LWM2M_pmax);
        return 1;
    }
    else return 0;
}
Example #14
0
main()
{
    int i;
    double b[8][5] = { {3.0, -4.0, 1.0, 0.0, 0.0},
        { -2.0, -5.0, 6.0, 1.0, 0.0}, {1.0, 3.0, -1.0, 2.0, -3.0},
        {2.0, 5.0, -5.0, 6.0, -1.0}, { -3.0, 1.0, -1.0, 2.0, -5.0},
        {6.0, 1.0, -3.0, 2.0, -9.0}, { -4.0, 1.0, -1.0, 2.0, 0.0},
        {5.0, 1.0, -7.0, 0.0, 0.0}
    };
    double d[8][3] = { {13.0, 29.0, -13.0},
        { -6.0, 17.0, -21.0}, { -31.0, -6.0, 4.0}, {64.0, 3.0, 16.0},
        { -20.0, 1.0, -5.0}, { -22.0, -41.0, 56.0}, { -29.0, 10.0, -21.0},
        {7.0, -24.0, 20.0}
    };

    if (band(b, d, 8, 2, 5, 3) > 0)
        for (i = 0; i <= 7; i++)
            printf("x(%d)=%13.6e,  %13.6e,  %13.6e\n",
                   i, d[i][0], d[i][1], d[i][2]);
}
Example #15
0
File: main.c Project: Zbsiz/ZQ-home
int main(int argc, char* argv[])
{
  rings();
  band();

  printf("nihao!\n");  

  int a = 1;
  int b;

  b=-a-5;
  
  printf("%d\n", b);


  /* 输出转义符, 结果还是会自动换行  */
  putchar('\n');

  /*
  char bb;
  scanf("%c", &bb);
  printf("%c\\n", bb);
  */

  /*  使用不可打印字符时,需要用转义字符标识  */
  printf("note:\n  a  s\ti\b\bk\rp\n");

  /*  输入ascii 部分码表  */
  for (int i=0; i<26; i++)
  {
    printf("%c: %d   ", 'A'+i, 'A'+i);
    if (i%7 == 6)
      printf("\n");
  }
  printf("\n");

  return 0;
}
Example #16
0
int main() {
  static_assert(add() == int(), "");
  static_assert(mul() == 1, "");
  static_assert(bor() == int(), "");
  static_assert(band() == -1, "");
  static_assert(land() == true, "");
  static_assert(lor() == false, "");
  comma(); // No value to theck

  // These are all errors, but the error is emitted at the point
  // of instantiation (line 10).
  sub();			// { dg-message "required from here" }
  div();			// { dg-message "required from here" }
  mod();			// { dg-message "required from here" }
  lsh();			// { dg-message "required from here" }
  rsh();			// { dg-message "required from here" }
  assign();			// { dg-message "required from here" }
  addi();			// { dg-message "required from here" }
  subi();			// { dg-message "required from here" }
  muli();			// { dg-message "required from here" }
  divi();			// { dg-message "required from here" }
  modi();			// { dg-message "required from here" }
  bxor();			// { dg-message "required from here" }
  bxori();			// { dg-message "required from here" }
  bori();			// { dg-message "required from here" }
  bandi();			// { dg-message "required from here" }
  lshi();			// { dg-message "required from here" }
  rshi();			// { dg-message "required from here" }
  eq();				// { dg-message "required from here" }
  ne();				// { dg-message "required from here" }
  lt();				// { dg-message "required from here" }
  gt();				// { dg-message "required from here" }
  le();				// { dg-message "required from here" }
  ge();				// { dg-message "required from here" }
  dot_star();			// { dg-message "required from here" }
  arrow_star();			// { dg-message "required from here" }
}
Example #17
0
bool YaehmopOut::readBandData(const QString& data, QVector<band>& bands,
                              QVector<kpoint>& kpoints,
                              QVector<specialKPoint>& specialKPoints)
{
  bands.clear();
  kpoints.clear();
  specialKPoints.clear();

  QStringList lines = data.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);

  while (lines.size() != 0 && !lines[0].contains("#BAND_DATA"))
    lines.removeFirst();

  if (lines.size() == 0)
    return printAndReturnFalse("Band Data not found in readBandData()!");

  // These get printed from the status file and are not needed...
  foreach(const QString& line, lines) {
    if (line.contains("Error value from Diagonalization"))
      lines.removeOne(line);
  }

  // Right here, lines.size() must be at least 8
  if (lines.size() < 8)
    return printAndReturnFalse("Band data is too few lines!");

  size_t ind = 2;
  if (!lines[ind].contains("Special points"))
    return printAndReturnFalse("Special Points missing");
  size_t numSpecialPoints = lines[ind].split(" ")[0].toInt();

  // Now we know more detail about how many lines should be here
  if (lines.size() < 7 + numSpecialPoints)
    return printAndReturnFalse("Too few lines of data in band data!");

  ++ind;
  if (!lines[ind].contains("k points"))
    return printAndReturnFalse("k points missing");
  size_t numKPoints = lines[ind].split(" ")[0].toInt();

  ++ind;
  if (!lines[ind].contains("orbitals in"))
    return printAndReturnFalse("orbitals in missing");;
  size_t numOrbitals = lines[ind].split(" ")[0].toInt();

  for (size_t i = 0; i < numSpecialPoints; ++i) {
    ++ind;
    specialKPoint kp;
    if (lines[ind].split(" ").size() < 4)
      return printAndReturnFalse("Special points line too small");

    kp.label = lines[ind].split(" ")[0];
    kp.coords = Vector3(lines[ind].split(" ")[1].toDouble(),
                        lines[ind].split(" ")[2].toDouble(),
                        lines[ind].split(" ")[3].toDouble());
    specialKPoints.append(kp);
  }

  ++ind;
  if (!lines[ind].contains("Begin band data"))
    return printAndReturnFalse("Begin band data missing");

  // This should be equal in size to the number of orbitals
  bands.reserve(numOrbitals);
  for (size_t i = 0; i < numOrbitals; ++i) {
    bands.append(band());
    // This is how many points we should have in total
    bands[i].reserve(numKPoints * (numSpecialPoints - 1) + 1);
  }
  // This is how many points we should have in total
  kpoints.reserve(numKPoints * (numSpecialPoints - 1) + 1);

  ++ind;
  while (true) {
    // Did we make it to the end without finishing the band data?
    if (ind >= lines.size())
      return printAndReturnFalse("END_BAND_DATA is missing!");

    // Did we make it to the end?
    if (lines[ind].contains("END_BAND_DATA"))
      break;

    // Read the k-point info
    if (!lines[ind].contains("K point") ||
        lines[ind].split(" ").size() < 6) {
      return printAndReturnFalse("K point missing");
    }

    kpoint kp = Vector3(lines[ind].split(" ")[3].toDouble(),
                        lines[ind].split(" ")[4].toDouble(),
                        lines[ind].split(" ")[5].toDouble());
    kpoints.append(kp);

    // Get the orbital energies
    for (size_t j = 0; j < numOrbitals; ++j) {
      ++ind;
      bands[j].append(lines[ind].trimmed().toDouble());
    }
    ++ind;
  }

  // We made it!
  return true;
}
Example #18
0
    return e1->eval(a, b, c, d) ^ e2->eval(a, b, c, d);
  }
};

Expr* const ba() { return new A(); }
Expr* const bb() { return new B(); }
Expr* const bc() { return new C(); }
Expr* const bd() { return new D(); }
Expr* bnot(Expr* const e) { return new Not(e); }
Expr* band(Expr* const e1, Expr* const e2) { return new And(e1, e2); }
Expr* bor(Expr* const e1, Expr* const e2) { return new Or(e1, e2); }
Expr* bxor(Expr* const e1, Expr* const e2) { return new Xor(e1, e2); }

Expr* const knownXor4 =
  band(
      bor(bxor(ba(), bb()), bxor(bc(), bd())),
      bxor(bor(ba(), bb()), bor(bc(), bd())));

bool isXor4(Expr* const e) {
  return !e->eval(true, true, true, true)
      && !e->eval(false, true, true, true)
      && !e->eval(true, false, true, true)
      && !e->eval(false, false, true, true)
      && !e->eval(true, true, false, true)
      && !e->eval(false, true, false, true)
      && !e->eval(true, false, false, true)
      && e->eval(false, false, false, true)
      && !e->eval(true, true, true, false)
      && !e->eval(false, true, true, false)
      && !e->eval(true, false, true, false)
      && e->eval(false, false, true, false)
void KHistogram::statistics() {
  for (int i = 0; i < bands(); i++) band(i).statistics();
}
Example #20
0
void NitfWriter::done(PointTableRef table)
{
    LasWriter::done(table);

    try
    {
        ::nitf::Record record(NITF_VER_21);
        ::nitf::FileHeader header = record.getHeader();
        header.getFileHeader().set("NITF");
        header.getComplianceLevel().set(m_cLevel);
        header.getSystemType().set(m_sType);
        header.getOriginStationID().set(m_oStationId);
        header.getFileTitle().set(m_fileTitle);
        header.getClassification().set(m_fileClass);
        header.getMessageCopyNum().set("00000");
        header.getMessageNumCopies().set("00000");
        header.getEncrypted().set("0");
        header.getBackgroundColor().setRawData(const_cast<char*>("000"), 3);
        header.getOriginatorName().set(m_origName);
        header.getOriginatorPhone().set(m_origPhone);
        header.getSecurityGroup().getClassificationSystem().set(m_securityClassificationSystem);
        header.getSecurityGroup().getControlAndHandling().set(m_securityControlAndHandling);
        header.getSecurityGroup().getClassificationText().set(m_sic);

        ::nitf::DESegment des = record.newDataExtensionSegment();

        des.getSubheader().getFilePartType().set("DE");
        des.getSubheader().getTypeID().set("LIDARA DES");
        des.getSubheader().getVersion().set("01");
        des.getSubheader().getSecurityClass().set(m_securityClass);
        ::nitf::FileSecurity security = record.getHeader().getSecurityGroup();
        des.getSubheader().setSecurityGroup(security.clone());

        ::nitf::TRE usrHdr("LIDARA DES", "raw_data");
        usrHdr.setField("raw_data", "not");
        ::nitf::Field fld = usrHdr.getField("raw_data");
        fld.setType(::nitf::Field::BINARY);

        flush();
        m_oss.flush();
        std::streambuf *buf = m_oss.rdbuf();
        long size = buf->pubseekoff(0, m_oss.end);
        buf->pubseekoff(0, m_oss.beg);

        std::vector<char> bytes(size);
        buf->sgetn(bytes.data(), size);

        des.getSubheader().setSubheaderFields(usrHdr);

        ::nitf::ImageSegment image = record.newImageSegment();
        ::nitf::ImageSubheader subheader = image.getSubheader();


        BOX3D bounds =  reprojectBoxToDD(table.spatialRef(), m_bounds);

        //NITF decimal degree values for corner coordinates only has a
        // precision of 3 after the decimal. This may cause an invalid
        // polygon due to rounding errors with a small tile. Therefore
        // instead of rounding min values will use the floor value and
        // max values will use the ceiling values.
        bounds.minx = (floor(bounds.minx * 1000)) / 1000.0;
        bounds.miny = (floor(bounds.miny * 1000)) / 1000.0;
        bounds.maxx = (ceil(bounds.maxx * 1000)) / 1000.0;
        bounds.maxy = (ceil(bounds.maxy * 1000)) / 1000.0;

        double corners[4][2];
        corners[0][0] = bounds.maxy;
        corners[0][1] = bounds.minx;
        corners[1][0] = bounds.maxy;
        corners[1][1] = bounds.maxx;
        corners[2][0] = bounds.miny;
        corners[2][1] = bounds.maxx;
        corners[3][0] = bounds.miny;
        corners[3][1] = bounds.minx;
        subheader.setCornersFromLatLons(NRT_CORNERS_DECIMAL, corners);

        subheader.getImageSecurityClass().set(m_imgSecurityClass);
        subheader.setSecurityGroup(security.clone());
        if (m_imgDate.size())
            subheader.getImageDateAndTime().set(m_imgDate);

        ::nitf::BandInfo info;
        ::nitf::LookupTable lt(0,0);
        info.init("G",    /* The band representation, Nth band */
                  " ",      /* The band subcategory */
                  "N",      /* The band filter condition */
                  "   ",    /* The band standard image filter code */
                  0,        /* The number of look-up tables */
                  0,        /* The number of entries/LUT */
                  lt);     /* The look-up tables */

        std::vector< ::nitf::BandInfo> bands;
        bands.push_back(info);
        subheader.setPixelInformation(
            "INT",      /* Pixel value type */
            8,         /* Number of bits/pixel */
            8,         /* Actual number of bits/pixel */
            "R",       /* Pixel justification */
            "NODISPLY",     /* Image representation */
            "VIS",     /* Image category */
            1,         /* Number of bands */
            bands);

        subheader.setBlocking(
            8,   /*!< The number of rows */
            8,  /*!< The number of columns */
            8, /*!< The number of rows/block */
            8,  /*!< The number of columns/block */
            "P");                /*!< Image mode */

        //Image Header fields to set
        subheader.getImageId().set("None");
        subheader.getImageTitle().set(m_imgIdentifier2);

        // 64 char string
        std::string zeros(64, '0');

        std::unique_ptr< ::nitf::BandSource> band(new ::nitf::MemorySource(
            const_cast<char*>(zeros.c_str()),
            zeros.size() /* memory size */,
            0 /* starting offset */,
            1 /* bytes per pixel */,
            0 /*skip*/));
        ::nitf::ImageSource iSource;
        iSource.addBand(*band);

        //AIMIDB
        if (!m_aimidb.empty())
        {
            boost::optional<const Options&> options = m_aimidb.getOptions();
            if (options)
            {
                ::nitf::TRE tre("AIMIDB");
                std::vector<Option> opts = options->getOptions();
                for (auto i = opts.begin(); i != opts.end(); ++i)
                {
                    tre.setField(i->getName(), i->getValue<std::string>());
                }
                subheader.getExtendedSection().appendTRE(tre);
            }
        }

        //ACFTB
        if (!m_acftb.empty())
        {
            boost::optional<const Options&> options = m_acftb.getOptions();
            if (options)
            {
                ::nitf::TRE tre("ACFTB");
                std::vector<Option> opts = options->getOptions();
                for (auto i = opts.begin(); i != opts.end(); ++i)
                {
                    tre.setField(i->getName(), i->getValue<std::string>());
                }
                subheader.getExtendedSection().appendTRE(tre);
            }
        }

        ::nitf::Writer writer;
        ::nitf::IOHandle output_io(m_filename.c_str(), NITF_ACCESS_WRITEONLY,
            NITF_CREATE);
        writer.prepare(output_io, record);

        ::nitf::SegmentWriter sWriter = writer.newDEWriter(0);

        ::nitf::SegmentMemorySource sSource(bytes.data(), size, 0, 0, false);
        sWriter.attachSource(sSource);

        ::nitf::ImageWriter iWriter = writer.newImageWriter(0);
        iWriter.attachSource(iSource);

        writer.write();
        output_io.close();
    }
    catch (except::Throwable & t)
    {
        std::ostringstream oss;
        // std::cout << t.getTrace();
        throw pdal_error(t.getMessage());
    }
}
Example #21
0
qint32 cMediaInfo::writeFilename()
{
	QSqlQuery	query;

	query.prepare("SELECT id FROM file WHERE fileName=:fileName AND fileSize=:fileSize AND fileDate=:fileDate;");
	query.bindValue(":fileName", fileName());
	query.bindValue(":fileSize", fileSize());
	query.bindValue(":fileDate", fileDate());

	if(!query.exec())
	{
		myDebug << query.lastError().text();
		return(-1);
	}

	if(query.next())
		query.prepare("UPDATE file SET fileType=:fileType, length=:length, bitrate=:bitrate, sampleRate=:sampleRate, channels=:channels, bitsPerSample=:bitsPerSample, layer=:layer, version=:version, sampleWidth=:sampleWidth, sampleFrames=:sampleFrames, isEncrypted=:isEncrypted, trackGain=:trackGain, albumGain=:albumGain, trackPeak=:trackPeak, albumPeak=:albumPeak, protectionEnabled=:protectionEnabled, channelMode=:channelMode, isCopyrighted=:isCopyrighted, isOriginal=:isOriginal, album=:album, title=:title, copyright=:copyright, trackNumber=:trackNumber, contentGroupDescription=:contentGroupDescription, subTitle=:subTitle, originalAlbum=:originalAlbum, partOfSet=:partOfSet, subTitleOfSet=:subTitleOfSet, internationalStandardRecordingCode=:internationalStandardRecordingCode, leadArtist=:leadArtist, band=:band, conductor=:conductor, interpret=:interpret, originalArtist=:originalArtist, textWriter=:textWriter, originalTextWriter=:originalTextWriter, composer=:composer, encodedBy=:encodedBy, beatsPerMinute=:beatsPerMinute, language=:language, contentType=:contentType, mediaType=:mediaType, mood=:mood, producedNotice=:producedNotice, publisher=:publisher, fileOwner=:fileOwner, internetRadioStationName=:internetRadioStationName, internetRadioStationOwner=:internetRadioStationOwner, originalFilename=:originalFilename, playlistDelay=:playlistDelay, encodingTime=:encodingTime, originalReleaseTime=:originalReleaseTime, recordingTime=:recordingTime, releaseTime=:releaseTime, taggingTime=:taggingTime, swhwSettings=:swhwSettings, albumSortOrder=:albumSortOrder, performerSortOrder=:performerSortOrder, titleSortOrder=:titleSortOrder, synchronizedLyrics=:synchronizedLyrics, unsynchronizedLyrics=:unsynchronizedLyrics WHERE filename=:filename AND filesize=:filesize AND filedate=:filedate;");
	else
		query.prepare("INSERT INTO file (fileName, fileSize, fileDate, fileType, length, bitrate, sampleRate, channels, bitsPerSample, layer, version, sampleWidth, sampleFrames, isEncrypted, trackGain, albumGain, trackPeak, albumPeak, protectionEnabled, channelMode, isCopyrighted, isOriginal, album, title, copyright, trackNumber, contentGroupDescription, subTitle, originalAlbum, partOfSet, subTitleOfSet, internationalStandardRecordingCode, leadArtist, band, conductor, interpret, originalArtist, textWriter, originalTextWriter, composer, encodedBy, beatsPerMinute, language, contentType, mediaType, mood, producedNotice, publisher, fileOwner, internetRadioStationName, internetRadioStationOwner, originalFilename, playlistDelay, encodingTime, originalReleaseTime, recordingTime, releaseTime, taggingTime, swhwSettings, albumSortOrder, performerSortOrder, titleSortOrder, synchronizedLyrics, unsynchronizedLyrics) VALUES (:fileName, :fileSize, :fileDate, :fileType, :length, :bitrate, :sampleRate, :channels, :bitsPerSample, :layer, :version, :sampleWidth, :sampleFrames, :isEncrypted, :trackGain, :albumGain, :trackPeak, :albumPeak, :protectionEnabled, :channelMode, :isCopyrighted, :isOriginal, :album, :title, :copyright, :trackNumber, :contentGroupDescription, :subTitle, :originalAlbum, :partOfSet, :subTitleOfSet, :internationalStandardRecordingCode, :leadArtist, :band, :conductor, :interpret, :originalArtist, :textWriter, :originalTextWriter, :composer, :encodedBy, :beatsPerMinute, :language, :contentType, :mediaType, :mood, :producedNotice, :publisher, :fileOwner, :internetRadioStationName, :internetRadioStationOwner, :originalFilename, :playlistDelay, :encodingTime, :originalReleaseTime, :recordingTime, :releaseTime, :taggingTime, :swhwSettings, :albumSortOrder, :performerSortOrder, :titleSortOrder, :synchronizedLyrics, :unsynchronizedLyrics);");

	query.bindValue(":fileName", fileName());
	query.bindValue(":fileSize", fileSize());
	query.bindValue(":fileDate", fileDate());
	query.bindValue(":fileType", fileType());
	query.bindValue(":length", length());
	query.bindValue(":bitrate", bitrate());
	query.bindValue(":sampleRate", sampleRate());
	query.bindValue(":channels", channels());
	query.bindValue(":bitsPerSample", bitsPerSample());
	query.bindValue(":layer", layer());
	query.bindValue(":version", version());
	query.bindValue(":sampleWidth", sampleWidth());
	query.bindValue(":sampleFrames", sampleFrames());
	query.bindValue(":isEncrypted", isEncrypted());
	query.bindValue(":trackGain", trackGain());
	query.bindValue(":albumGain", albumGain());
	query.bindValue(":trackPeak", trackPeak());
	query.bindValue(":albumPeak", albumPeak());
	query.bindValue(":protectionEnabled", protectionEnabled());
	query.bindValue(":channelMode", channelMode());
	query.bindValue(":isCopyrighted", isCopyrighted());
	query.bindValue(":isOriginal", isOriginal());
	query.bindValue(":album", album());
	query.bindValue(":title", title());
	query.bindValue(":copyright", copyright());
	query.bindValue(":trackNumber", trackNumber());
	query.bindValue(":contentGroupDescription", contentGroupDescription());
	query.bindValue(":subTitle", subTitle());
	query.bindValue(":originalAlbum", originalAlbum());
	query.bindValue(":partOfSet", partOfSet());
	query.bindValue(":subTitleOfSet", subTitleOfSet());
	query.bindValue(":internationalStandardRecordingCode", internationalStandardRecordingCode());
	query.bindValue(":leadArtist", leadArtist());
	query.bindValue(":band", band());
	query.bindValue(":conductor", conductor());
	query.bindValue(":interpret", interpret().join(", "));
	query.bindValue(":originalArtist", originalArtist());
	query.bindValue(":textWriter", textWriter());
	query.bindValue(":originalTextWriter", originalTextWriter());
	query.bindValue(":composer", composer());
	query.bindValue(":encodedBy", encodedBy());
	query.bindValue(":beatsPerMinute", beatsPerMinute());
	query.bindValue(":language", language().join(", "));
	query.bindValue(":contentType", contentType().join(", "));
	query.bindValue(":mediaType", mediaType().join(", "));
	query.bindValue(":mood", mood());
	query.bindValue(":producedNotice", producedNotice());
	query.bindValue(":publisher", publisher());
	query.bindValue(":fileOwner", fileOwner());
	query.bindValue(":internetRadioStationName", internetRadioStationName());
	query.bindValue(":internetRadioStationOwner", internetRadioStationOwner());
	query.bindValue(":originalFilename", originalFilename());
	query.bindValue(":playlistDelay", playlistDelay());
	query.bindValue(":encodingTime", encodingTime());
	query.bindValue(":originalReleaseTime", originalReleaseTime());
	query.bindValue(":recordingTime", recordingTime());
	query.bindValue(":releaseTime", releaseTime());
	query.bindValue(":taggingTime", taggingTime());
	query.bindValue(":swhwSettings", swhwSettings().join(", "));
	query.bindValue(":albumSortOrder", albumSortOrder());
	query.bindValue(":performerSortOrder", performerSortOrder());
	query.bindValue(":titleSortOrder", titleSortOrder());
	query.bindValue(":synchronizedLyrics", synchronizedLyrics().join());
	query.bindValue(":unsynchronizedLyrics", unsynchronizedLyrics().join("||"));

	if(!query.exec())
	{
		myDebug << query.lastError().text();
		return(-1);
	}

	query.prepare("SELECT id FROM file WHERE fileName=:fileName AND fileSize=:fileSize AND fileDate=:fileDate;");
	query.bindValue(":fileName", fileName());
	query.bindValue(":fileSize", fileSize());
	query.bindValue(":fileDate", fileDate());

	if(!query.exec())
	{
		myDebug << query.lastError().text();
		return(-1);
	}

	if(query.next())
		return(query.value("id").toInt());

	return(-1);
}
Example #22
0
void VisGlyph::drawSingleBand(RGBt & color, std::vector<double> &data, std::vector<double> &max, std::vector<double> &min, int datano) {



	double temp1, temp2, temp3;
	int i;

	std::vector<Vec2> polymean(m_dim_size + 1);
	std::vector<Vec2> polymax(m_dim_size + 1);
	std::vector<Vec2> polymin(m_dim_size + 1);

	double basex,basey;
	basex = (*m_basex)[datano];
	basey = (*m_basey)[datano];

	double alpha = 2.0*M_PI/m_dim_size;
	double *isin = new double[m_dim_size];
	double *icos = new double[m_dim_size];

	double temp;
	for (i = 0; i < m_dim_size; i++) {
		temp = (m_blocksize / 2.0) / (m_dim_max[i]
				- m_dim_min[i]);
		icos[i] = temp * cos(i * alpha);
		isin[i] = temp * sin(i * alpha);
	}

	for ( i = 0; i < m_dim_size; i++ )
	{
        temp1 = (data[i] - m_dim_min[i]);
        temp2 = (max[i] - m_dim_min[i]);
        temp3 = (min[i] - m_dim_min[i]);
		if ( fabs(1 - m_hier_info->extent_scaling_fac ) > 1e-4 )
		{
			temp2 = temp1 + m_hier_info->extent_scaling_fac*(temp2-temp1);
			temp3 = temp1 + m_hier_info->extent_scaling_fac*(temp3-temp1);
        }
		polymax[i].X = basex + temp2 * icos[i];
        polymax[i].Y = basey - temp2 * isin[i];;
		polymin[i].X = basex + temp3 * icos[i];
        polymin[i].Y = basey - temp3 * isin[i];;
	}
	polymax[m_dim_size] = polymax[0];
	polymin[m_dim_size] = polymin[0];

	for (i = 0; i < m_dim_size; i++) {
		double temp = (data[i] - m_dim_min[i]);
		polymean[i].X = basex + temp * icos[i];
		polymean[i].Y = basey - temp * isin[i];
	}
	polymean[m_dim_size] = polymean[0];

	std::vector<Vec2> band(4);

	m_canvas->setForeground(color, m_opacity);

    // Draw the lower band
    int d;
    for (d=0; d<m_dim_size+1; d++)
    {
		Vec2 lo, hi;

        lo = polymin[d];
		hi = polymean[d];

        if (d==0) {
            band[0] = lo;
            band[3] = hi;

        } else {

            band[1] = lo;
            band[2] = hi;
            m_canvas->drawTransparentBand(band, 0.0, m_hier_info->density, m_canvas->fg_color, m_canvas->fg_color);

            band[0] = band[1];
            band[3] = band[2];
        }
    }

    // Draw the upper band
    for (d=0; d<m_dim_size+1; d++)
    {
        Vec2 lo, hi;

		lo = polymean[d];
		hi = polymax[d];

        if (d==0) {
            band[0] = lo;
            band[3] = hi;
        } else {
            band[1] = lo;
            band[2] = hi;

            m_canvas->drawTransparentBand(band, m_hier_info->density, 0.0, m_canvas->fg_color, m_canvas->fg_color);

            band[0] = band[1];
            band[3] = band[2];
        }
    }
}
Example #23
0
void NitfWriter::doneFile()
{
    finishOutput();

    try
    {
        ::nitf::Record record(NITF_VER_21);
        ::nitf::FileHeader header = record.getHeader();
        header.getFileHeader().set("NITF");
        header.getComplianceLevel().set(m_cLevel);
        header.getSystemType().set(m_sType);
        header.getOriginStationID().set(m_oStationId);
        if (m_fileTitle.empty())
        	m_fileTitle = FileUtils::getFilename(m_nitfFilename);
        header.getFileTitle().set(m_fileTitle);
        header.getClassification().set(m_fileClass);
        header.getMessageCopyNum().set("00000");
        header.getMessageNumCopies().set("00000");
        header.getEncrypted().set("0");
        header.getBackgroundColor().setRawData(const_cast<char*>("000"), 3);
        header.getOriginatorName().set(m_origName);
        header.getOriginatorPhone().set(m_origPhone);
        header.getSecurityGroup().getClassificationSystem().set(
            m_securityClassificationSystem);
        header.getSecurityGroup().getControlAndHandling().set(
            m_securityControlAndHandling);
        header.getSecurityGroup().getClassificationText().set(m_sic);

        ::nitf::DESegment des = record.newDataExtensionSegment();

        des.getSubheader().getFilePartType().set("DE");
        des.getSubheader().getTypeID().set("LIDARA DES");
        des.getSubheader().getVersion().set("01");
        des.getSubheader().getSecurityClass().set(m_securityClass);
        ::nitf::FileSecurity security = record.getHeader().getSecurityGroup();
        des.getSubheader().setSecurityGroup(security.clone());

        ::nitf::TRE usrHdr("LIDARA DES", "raw_data");
        usrHdr.setField("raw_data", "not");
        ::nitf::Field fld = usrHdr.getField("raw_data");
        fld.setType(::nitf::Field::BINARY);

        std::streambuf *buf = m_oss.rdbuf();
        long size = buf->pubseekoff(0, m_oss.end);
        buf->pubseekoff(0, m_oss.beg);

        std::vector<char> bytes(size);
        buf->sgetn(bytes.data(), size);
        m_oss.clear();

        des.getSubheader().setSubheaderFields(usrHdr);

        ::nitf::ImageSegment image = record.newImageSegment();
        ::nitf::ImageSubheader subheader = image.getSubheader();

        BOX3D bounds =  reprojectBoxToDD(m_srs, m_bounds);

        //NITF decimal degree values for corner coordinates only has a
        // precision of 3 after the decimal. This may cause an invalid
        // polygon due to rounding errors with a small tile. Therefore
        // instead of rounding min values will use the floor value and
        // max values will use the ceiling values.
        bounds.minx = (floor(bounds.minx * 1000)) / 1000.0;
        bounds.miny = (floor(bounds.miny * 1000)) / 1000.0;
        bounds.maxx = (ceil(bounds.maxx * 1000)) / 1000.0;
        bounds.maxy = (ceil(bounds.maxy * 1000)) / 1000.0;

        double corners[4][2];
        corners[0][0] = bounds.maxy;
        corners[0][1] = bounds.minx;
        corners[1][0] = bounds.maxy;
        corners[1][1] = bounds.maxx;
        corners[2][0] = bounds.miny;
        corners[2][1] = bounds.maxx;
        corners[3][0] = bounds.miny;
        corners[3][1] = bounds.minx;
        subheader.setCornersFromLatLons(NRT_CORNERS_DECIMAL, corners);

        subheader.getImageSecurityClass().set(m_imgSecurityClass);
        subheader.setSecurityGroup(security.clone());
        if (m_imgDate.size())
            subheader.getImageDateAndTime().set(m_imgDate);

        ::nitf::BandInfo info;
        ::nitf::LookupTable lt(0,0);
        info.init(" ",    /* The band representation, Nth band */
                  " ",      /* The band subcategory */
                  "N",      /* The band filter condition */
                  "   ",    /* The band standard image filter code */
                  0,        /* The number of look-up tables */
                  0,        /* The number of entries/LUT */
                  lt);     /* The look-up tables */

        std::vector< ::nitf::BandInfo> bands;
        bands.push_back(info);
        subheader.setPixelInformation(
            "INT",      /* Pixel value type */
            8,         /* Number of bits/pixel */
            8,         /* Actual number of bits/pixel */
            "R",       /* Pixel justification */
            "NODISPLY",     /* Image representation */
            "VIS",     /* Image category */
            1,         /* Number of bands */
            bands);

        subheader.setBlocking(
            8,   /*!< The number of rows */
            8,  /*!< The number of columns */
            8, /*!< The number of rows/block */
            8,  /*!< The number of columns/block */
            "B");                /*!< Image mode */

        //Image Header fields to set
        subheader.getImageId().set("None");
        subheader.getImageTitle().set(m_imgIdentifier2);

        // 64 char string
        std::string zeros(64, '0');

        std::unique_ptr< ::nitf::BandSource> band(new ::nitf::MemorySource(
            const_cast<char*>(zeros.c_str()),
            zeros.size() /* memory size */,
            0 /* starting offset */,
            1 /* bytes per pixel */,
            0 /*skip*/));
        ::nitf::ImageSource iSource;
        iSource.addBand(*band);

        //AIMIDB
        ::nitf::TRE aimidbTre("AIMIDB");

        //LIDAR defaults
        if (m_imgDate.size())
        	aimidbTre.setField("ACQUISITION_DATE", m_imgDate);
        aimidbTre.setField("MISSION_NO", "UNKN");
        aimidbTre.setField("MISSION_IDENTIFICATION", "NOT AVAIL.");
        aimidbTre.setField("FLIGHT_NO", "00");
        aimidbTre.setField("CURRENT_SEGMENT", "AA");
        aimidbTre.setField("START_TILE_COLUMN", "001");
        aimidbTre.setField("START_TILE_ROW", "00001");
        aimidbTre.setField("END_SEGMENT", "00");
        aimidbTre.setField("END_TILE_COLUMN", "001");
        aimidbTre.setField("END_TILE_ROW", "00001");

        for (auto& s : m_aimidb)
        {
            StringList v = Utils::split2(s, ':');
            if (v.size() != 2)
            {
                std::ostringstream oss;
                oss << "Invalid name/value for AIMIDB '" << s <<
                    "'.  Format: <name>:<value>.";
                throw oss.str();
            }
            Utils::trim(v[0]);
            Utils::trim(v[1]);
            aimidbTre.setField(v[0], v[1]);
        }
        subheader.getExtendedSection().appendTRE(aimidbTre);

		//if IDATIM is empty set it equal to AIMIDB.ACQUISITION_DATE
        if(!m_imgDate.size())
        {
        	m_imgDate=aimidbTre.getField("ACQUISITION_DATE").toString();
			if (m_imgDate.size())
				subheader.getImageDateAndTime().set(m_imgDate);
        }

        //ACFTB
        ::nitf::TRE acftbTre("ACFTB");

        //LIDAR defaults
        acftbTre.setField("AC_MSN_ID", "NOT AVAILABLE");
        acftbTre.setField("SCENE_SOURCE", " ");
        if (m_imgDate.size()>7)
        	acftbTre.setField("PDATE", m_imgDate.substr(0,8));
        acftbTre.setField("MPLAN", "999");
        acftbTre.setField("LOC_ACCY", "000.00");
        acftbTre.setField("ROW_SPACING", "0000000");
        acftbTre.setField("ROW_SPACING_UNITS", "u");
        acftbTre.setField("COL_SPACING", "0000000");
        acftbTre.setField("COL_SPACING_UNITS", "u");
        acftbTre.setField("FOCAL_LENGTH", "999.99");

        for (auto& s : m_acftb)
        {
            StringList v = Utils::split2(s, ':');
            if (v.size() != 2)
            {
                std::ostringstream oss;
                oss << "Invalid name/value for ACFTB '" << s <<
                    "'.  Format: <name>:<value>.";
                throw oss.str();
            }
            Utils::trim(v[0]);
            Utils::trim(v[1]);
            acftbTre.setField(v[0], v[1]);
        }
        subheader.getExtendedSection().appendTRE(acftbTre);

        ::nitf::Writer writer;
        ::nitf::IOHandle output_io(m_nitfFilename.c_str(),
            NITF_ACCESS_WRITEONLY, NITF_CREATE);
        writer.prepare(output_io, record);

        ::nitf::SegmentWriter sWriter = writer.newDEWriter(0);

        ::nitf::SegmentMemorySource sSource(bytes.data(), size, 0, 0, false);
        sWriter.attachSource(sSource);

        ::nitf::ImageWriter iWriter = writer.newImageWriter(0);
        iWriter.attachSource(iSource);

        writer.write();
        output_io.close();
    }
    catch (except::Throwable & t)
    {
        std::ostringstream oss;
        // std::cout << t.getTrace();
        throw pdal_error(t.getMessage());
    }
}
Example #24
0
int main(int argc, char** argv) {
try {
  nmprk::ipmi::device d;
  d.transport = nmprk::ipmi::defaultTrans;
  d.bridge =    nmprk::ipmi::defaultBridge;
  d.cipher = nmprk::ipmi::cipherSuite_3;
  d.type = nmprk::ipmi::device_nm;

#if 0 // If you want to test in debugger without command line, set to 1
  d.address = "10.20.0.41";
  //d.address = "local";
  d.user = "******";
  d.password = "******";
  //d.transport = 0x2c;
  //d.bridge = 0x06;
  d.type = nmprk::ipmi::device_nm;
#else
  if(argc < 3) {
USAGE:  
    std::cout << "Invalid arguments\n";
    std::cout << "Usage:\n";
    std::cout << argv[0] << " [ -dcmi -dnm -nm ] [ -local | -remote host username pw ]\n";
    return -1;
  }else{
 
  std::string mode(argv[1]);
  size_t found = mode.find("-dcmi");
  if(found != std::string::npos)
   d.type = nmprk::ipmi::device_dcmi;
  else if((found = mode.find("-dnm")) != std::string::npos)
   d.type = nmprk::ipmi::device_dnm;
  else if((found = mode.find("-nm")) != std::string::npos)
   d.type = nmprk::ipmi::device_nm;
  else
   goto USAGE;
  
  std::string band(argv[2]);
  found = band.find("-local");
  if(found != std::string::npos)
   d.address = nmprk::ipmi::defaultLocal;
  else{ 
   d.address = argv[3];
   d.user = argv[4];
   d.password = argv[5];
   std::cout << "Doing remote test on " << d.address << " using " << d.user << " / " << d.password << std::endl;
  }
  }
#endif 

  nmprk::ipmi::commandReq_t req;
  req.data.push_back("06");
  req.data.push_back("01");  
  
  nmprk::ipmi::commandRsp_t rsp;
  bool result;
  int  i = 0;

  std::cout << "Testing ipmi engine functions:\n";

  //std::cout << "Initing system for local..... ";
  //result = nmprk::ipmi::initSystemForLocal();
  //std::cout << TEST_CHECK_BOOL(result) << std::endl;
  //if(result == false) {
  // std::cout << "initSystemForLocal test failed, skipping rest of tests!!!\n";
  // return -1;
  //}


  std::cout << "Attempting to connect to device..... ";
  try{
   result = nmprk::ipmi::connectDevice(&d);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception Running Command: Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  std::cout << TEST_CHECK_BOOL(result) << std::endl;
  if(result == false) {
   std::cout << "Connection test failed, skipping rest of tests!!!\n";
   return -1;
  } 

  std::cout << "Attempting to run basic test command.... ";
  try{ 
   result = nmprk::ipmi::runIpmiCommand(&d,&req,&rsp);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception Running Command: Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  } 
  std::cout << TEST_CHECK_BOOL(result) << std::endl;
  std::cout << "Sent " << req.data.size() << " Bytes.  Expecting back 15 bytes got back " << rsp.data.size() << "..... ";
  result = rsp.data.size() == 15;
  std::cout <<  TEST_CHECK_BOOL(result) << std::endl;
  std::cout << "Resp Bytes:\n";
  std::vector<std::string>::iterator it = rsp.data.begin();
  for(;it != rsp.data.end() ; it++ ) {
    std::cout << *it << " ";
  }
  std::cout << "\n";
  req.data.clear();

  std::cout << "testing nmprk::ipmi::sel function:\n";
  
  std::cout << "Attempting to get SEL Info..... ";
  nmprk::ipmi::repoInfo_t* r;
  try {
    r = nmprk::ipmi::sel::getSelInfo(&d);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception Running getSelInfo(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  std::cout << TEST_CHECK_VOID(r) << std::endl;
  if(r != NULL) {
  	  std::cout << "Repo Entries: " << r->repoEntries << std::endl;
  	  std::cout << "Repo Free Space: " << r->repoFreeSpace << " Bytes\n";
  }
 
  // Now we attempt and get the first record of the SEL
  nmprk::ipmi::address_t recordId;
  recordId.lsb = 0x00;
  recordId.msb = 0x0;
  nmprk::ipmi::record_t* record;
  std::cout << "Attempting to get first Sel Record..... "; 
  try {
   record = nmprk::ipmi::sel::getSelRecord(&d,&recordId);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception getSelRecord(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  std::cout.flush();
  std::cout << TEST_CHECK_VOID(record) << std::endl;
  if(record != NULL) {
   std::cout << "Address of Next Record LSB[" << record->nextRecord.lsb << "] MSB[" << record->nextRecord.msb << "]\n";
   std::cout.flush();   
  }
  std::cout << "\n";

 /*
  * The following section of code is considered "destructive"
  * in that it alters data entries on the system.  This could
  * leave your system in a unsteady state if for example 
  * you were to clear out the SDR or FRU or 
  * other pieces of data which are needed by a wide
  * of things (no sdr means you can't determine
  * bridge and transport to use for NM for example!)
  * To enable this code and these tests 
  * use the make-destructive
  */
#ifdef DESTRUCTIVE_CODE

  // no we write that SEL entry we just got back
  // to the same spot
  bool b;
  std::cout << "Attempting to write record back to SEL.....";
  std::cout.flush();
  try {
   b = nmprk::ipmi::sel::addSelRecord(&d,&recordId,record);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception addSelRecord(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  std::cout << TEST_CHECK_BOOL(b) << std::endl;

  std::cout << "Attempting to delete the record from the SEL.....";
  std::cout.flush();
  try {
    b = nmprk::ipmi::sel::delSelRecord(&d,&recordId);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception delSelRecord(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  std::cout << TEST_CHECK_BOOL(b) << std::endl;
  
  std::cout << "Attempting to clear out the SEL.....";
  std::cout.flush();
  try {
    b = nmprk::ipmi::sel::clearSel(&d);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception clearSel(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  std::cout << TEST_CHECK_BOOL(b) << std::endl;

#endif

  std::cout << "testing nmprk::ipmi::sdr function:\n";

  std::cout << "Attempting to get SDR Info..... ";
  try {
   r = nmprk::ipmi::sdr::getSdrInfo(&d);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception clearSel(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  std::cout << TEST_CHECK_VOID(r) << std::endl;
  if(r != NULL) {
  	  std::cout << "Repo Entries: " << r->repoEntries << std::endl;
  	  std::cout << "Repo Free Space: " << r->repoFreeSpace << " Bytes\n";
  }

  recordId.lsb = 0x00;
  recordId.msb = 0x0;
  record = NULL;
  std::cout << "Attempting to get first SDR Record..... ";
  try {
   record = nmprk::ipmi::sdr::getSdrRecord(&d,&recordId);
   std::cout.flush();
  std::cout << TEST_CHECK_VOID(record) << std::endl;
  if(record != NULL) {
   std::cout << "Address of Next Record LSB[" << record->nextRecord.lsb << "] MSB[" << record->nextRecord.msb << "]\n";
   std::cout.flush();
  }
  std::cout << "\n";
  }catch(nmprk::nmprkException* e) {
	  if(e->errorCode == NMPRK_CMD_RETURNED_NON_ZERO_CODE)
	  {
		  std::cout << e->errorMsg << ": ********** FAILED **********\n";
	  }
	  else
	  {
		std::cout << "Caught Exception getSdrRecord(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
		return -1;
	  }
  }

#ifdef DESTRUCTIVE_CODE

  // no we write that SEL entry we just got back
  // to the same spot
  std::cout << "Attempting to write record back to SDR.....";
  std::cout.flush();
  try {
   b = nmprk::ipmi::sdr::addSdrRecord(&d,&recordId,record);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception addSdrRecord(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  std::cout << TEST_CHECK_BOOL(b) << std::endl;

  std::cout << "Attempting to delete the record from the SDR.....";
  std::cout.flush();
  try {
    b = nmprk::ipmi::sdr::delSdrRecord(&d,&recordId);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception delSdrRecord(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  std::cout << TEST_CHECK_BOOL(b) << std::endl;

  std::cout << "Attempting to clear out the SDR.....";
  std::cout.flush();
  try {
    b = nmprk::ipmi::sdr::clearSdr(&d);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception clearSdr(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  std::cout << TEST_CHECK_BOOL(b) << std::endl;

#endif

  std::cout << "testing nmprk::ipmi::fru function:\n";

  std::cout << "Attempting to access FRU..... ";
  nmprk::ipmi::fruInfo_t* f;
  try {
   f = nmprk::ipmi::fru::getFruInfo(&d);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception clearSdr(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  std::cout << TEST_CHECK_VOID(f) << std::endl;
  if(f != NULL) {
   if(f->accessByWord == true) 
    std::cout << "Fru is accessed with word size\n";
   else
    std::cout << "Fru is access by byte\n";
  }
  
  std::cout << "Attempting to read first entry from FRU.....";
  try {
   record = nmprk::ipmi::fru::getFruData(&d,&recordId);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception getFruData(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  std::cout << TEST_CHECK_VOID(record) << std::endl;
  if(record != NULL) {
   std::cout << "Address of Next Record LSB[" << record->nextRecord.lsb << "] MSB[" << record->nextRecord.msb << "]\n";
   std::cout.flush();
  }
  std::cout << "\n";

 
  std::cout << "testing nmprk::ipmi::global function:\n";

  std::cout << "Attempting to get Device Id.....";
  nmprk::ipmi::getDeviceIdRsp* dID;
  try {
   dID = nmprk::ipmi::global::getDeviceId(&d);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception getDeviceId(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  std::cout << TEST_CHECK_VOID(dID) << std::endl;
  if(dID != NULL) {
   std::cout << "Device Id: 0x" << nmprk::helper::int2HexStr(dID->deviceId) << std::endl;
   std::cout << "Device Revision: 0x" << nmprk::helper::int2HexStr(dID->deviceRev) << std::endl;
   std::cout << "Firmware Revision: 0x" << nmprk::helper::int2HexStr(dID->firmwareRev) << std::endl;
   std::cout << "Firmware Revision2: 0x" << nmprk::helper::int2HexStr(dID->firmwareRev2) << std::endl;
  }

  std::cout << "Determining ACPI Power State: ";
  std::cout.flush();  
  nmprk::ipmi::acpiPwrState_t p;
  try {
   p = nmprk::ipmi::global::getAcpiPwrState(&d);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Caught Exception getAcpiPwrState(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  } 
  std::cout << "Passed\n" << std::endl;  

  std::cout << "System Power State is: ";
  switch(p.systemState) {
  case nmprk::ipmi::stateSysS0G0:
  	  std::cout << "S0/G0 (Working)";
  	  break;
  case nmprk::ipmi::stateSysS1:
  	  std::cout << "S1 (Hardware Context Maintained)";
  	  break;
  case nmprk::ipmi::stateSysS2:
  	  std::cout << "S2 (Stopped Clocks w/ Processor/Cache Context lost)";
  	  break;
  case nmprk::ipmi::stateSysS3:
  	  std::cout << "S3 (Suspend-to-Ram)";
  	  break;
  case nmprk::ipmi::stateSysS4:
  	  std::cout << "S4 (Suspend-to-Disc)";
  	  break;
  case nmprk::ipmi::stateSysS5G2:
  	  std::cout << "S5/G2 (Soft Off)";
  	  break;
  case nmprk::ipmi::stateSysS4S5:
  	  std::cout << "S4/S5 (Soft Off, Can not tell between S4 and S5)";
  	  break;
  case nmprk::ipmi::stateSysG3:
  	  std::cout << "G3 (Mechanical Off)";
  	  break;
  case nmprk::ipmi::stateSysSleeping:
	  std::cout << "Sleeping";
	  break;
  case nmprk::ipmi::stateSysG1Sleep:
	  std::cout << "G1 Sleeping";
	  break;
  case nmprk::ipmi::stateSysOverRide:
	  std::cout << "OverRide (S5 entered by override)";
	  break;
  case nmprk::ipmi::stateSysLegacyOn:
	  std::cout << "Legacy On";
	  break;
  case nmprk::ipmi::stateSysLegacyOff:
	  std::cout << "Legacy Off";
	  break;
  case nmprk::ipmi::stateSysUnknown:
	  std::cout << "Unknown (Device lost track of power state)";
	  break;
  }

  std::cout << "\nDevice Power State is: ";
  switch(p.deviceState) {
  case nmprk::ipmi::stateDevD0:
 	  std::cout << "D0";
	  break;
  case nmprk::ipmi::stateDevD1:
	  std::cout << "D1";
	  break;
  case nmprk::ipmi::stateDevD2:
	  std::cout << "D2";
	  break;
  case nmprk::ipmi::stateDevD3:
	  std::cout << "D3";
	  break;
  case nmprk::ipmi::stateDevUnknown:
	  std::cout << "Unknown";
	  break;
  }
  std::cout << "\n";
  std::cout.flush();
#ifdef DESTRUCTIVE_CODE

  std::cout << "Attempting to set ACPI Power State.....";
  try{ 
   b = nmprk::ipmi::global::setAcpiPwrState(&d,p);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Failed!\nCaught Exception setAcpiPwrState(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }
  // if we get this far we passed cause other wise
  // a exception would have been caught
  std::cout << "Passed!\n";

#endif

  std::cout << "Attempting to disconnect the device..... ";
  try {
   result = nmprk::ipmi::disconnectDevice(&d);
  }catch(nmprk::nmprkException* e) {
   std::cout << "Failed!\nCaught Exception disconnectDevice(): Code[" << e->errorCode << "] MSG[" << e->errorMsg << "]\n";
   return -1;
  }

  std::cout << TEST_CHECK_BOOL(result) << std::endl;
}catch(nmprk::nmprkException* e) {
	std::cout << "Caught Exception :" << e->errorCode << " " << e->errorMsg << std::endl;
} 
  puts("\nPress the Enter key to exit");
  getchar();
  return 0;
}