Ejemplo n.º 1
0
Archivo: Row.cpp Proyecto: lnsp/csvpp
/**
Parses the specified row to a valid CSV line.
@return CSV string containing row data
*/
std::string csv::Row::to_csv_string(Row& _row)
{
	string csv_string;
	for (unsigned i = 0; i < _row.length(); i++)
	{
		csv_string += _row.get_cell(i) + ";";
	}
	return csv_string;
}
Ejemplo n.º 2
0
Status YARAEventSubscriber::Callback(const FileEventContextRef& ec,
                                     const void* user_data) {
  if (user_data == nullptr) {
    return Status(1, "No YARA category string provided");
  }

  if (ec->action != "UPDATED" && ec->action != "CREATED") {
    return Status(1, "Invalid action");
  }

  Row r;
  r["action"] = ec->action;
  r["target_path"] = ec->path;
  r["category"] = *(std::string*)user_data;

  // Only FSEvents transactions updates (inotify is a no-op).
  r["transaction_id"] = INTEGER(ec->transaction_id);

  // These are default values, to be updated in YARACallback.
  r["count"] = INTEGER(0);
  r["matches"] = std::string("");
  r["strings"] = std::string("");
  r["tags"] = std::string("");

  ConfigDataInstance config;
  const auto& parser = config.getParser("yara");
  if (parser == nullptr)
    return Status(1, "ConfigParser unknown.");
  const auto& yaraParser = std::static_pointer_cast<YARAConfigParserPlugin>(parser);
  auto rules = yaraParser->rules();

  // Use the category as a lookup into the yara file_paths. The value will be
  // a list of signature groups to scan with.
  auto category = r.at("category");
  const auto& yara_config = config.getParsedData("yara");
  const auto& yara_paths = yara_config.get_child("file_paths");
  const auto& sig_groups = yara_paths.find(category);
  for (const auto& rule : sig_groups->second) {
    const std::string group = rule.second.data();
    int result = yr_rules_scan_file(rules[group],
                                    ec->path.c_str(),
                                    SCAN_FLAGS_FAST_MODE,
                                    YARACallback,
                                    (void*)&r,
                                    0);

    if (result != ERROR_SUCCESS) {
      return Status(1, "YARA error: " + std::to_string(result));
    }
  }

  if (ec->action != "" && r.at("matches").size() > 0) {
    add(r, ec->time);
  }

  return Status(0, "OK");
}
Ejemplo n.º 3
0
bool Compatible::equal(const Row& r1, const Row& r2) {
	if (disjoint != "")
		return false;

	for (Fields cols = allcols; !nil(cols); ++cols)
		if (r1.getraw(hdr1, *cols) != r2.getraw(hdr2, *cols))
			return false;
	return true;
}
Ejemplo n.º 4
0
void TablePrivate::deleteRow(int id)
{
    Q_Q(Table);
    int index = rows.indexOf(rowsById.value(id));
    q->removeRow(index);
    Row *row = rows.takeAt(index);
    rowsById.remove(id);
    row->deleteLater();
}
Ejemplo n.º 5
0
int DeleteDMLPackage::buildFromBuffer(std::string& buffer, int columns, int rows)
{
#ifdef DML_PACKAGE_DEBUG
    //cout << "The data buffer received: " << buffer << endl;
#endif

    int retval = 1;

    initializeTable();

    std::vector<std::string> dataList;
    typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
    boost::char_separator<char> sep(":");
    tokenizer tokens(buffer, sep);
    for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter)
    {
        dataList.push_back(StripLeadingWhitespace(*tok_iter));

    }

    int n = 0;
    for (int i=0; i < rows; i++)
    {
        //get a new row
        Row aRow;
        //Row *aRowPtr = new Row();
        //std::string colName;
        //std::string colValue;
        //get row ID from the buffer
        std::string rowid  = dataList[n++];
        aRow.set_RowID(atoll(rowid.c_str()));
        //aRowPtr->set_RowID(atol(rowid.c_str()));
#ifdef DML_PACKAGE_DEBUG

        //cout << "The row ID is " << rowid << endl;
#endif
        /*
                for (int j = 0; j < columns; j++)
                {
                    //Build a column list
                    colName = dataList[n++];
                    colValue = dataList[n++];
        #ifdef DML_PACKAGE_DEBUG
                    cout << "The column data: " << colName << " " << colValue << endl;
        #endif
                    DMLColumn* aColumn = new DMLColumn(colName, colValue);
                    (aRowPtr->get_ColumnList()).push_back(aColumn);
        }
        //build a row list for a table
        fTable->get_RowList().push_back(aRowPtr);
        */
    }

    return retval;

}
Ejemplo n.º 6
0
Row DSSelect  :: Get() {
	Row r = SourceAt(0)->Get();
	for ( unsigned int i = 1; i < SourceCount(); i++ ) {
		DSCase * cs = dynamic_cast <DSCase *>( SourceAt(i) );
		if ( cs->Match( r ) ) {
			return Order( r.AppendRow( cs->Get() ) );
		}
	}
	throw Exception( "No default case" );
}
Ejemplo n.º 7
0
// / Calculates the variance for a row in a matrix.
double variance(Row < double >&row)
{
    double sum = 0.;

    double average = mean(row);

    for (int r = 0; r < row.size(); r++)
        sum += (row[r] - average) * (row[r] - average);
    return sum / double (row.size() - 1);
}
Ejemplo n.º 8
0
void SMTPData::AddressFinder::execute()
{
    Row * r = q->nextRow();
    while ( r ) {
        a->append( new Address( "",
                                r->getEString( "localpart" ),
                                r->getEString( "domain" ) ) );
        r = q->nextRow();
    }
}
int BookingDatabase::Passengers::add(std::string pName)
{
    Passenger passenger;
    passenger.mName = pName;
    passenger.mPID = getNewID();
    Row<Passenger>* row = new Row<Passenger>(this, passenger);
    addRow(row);
    //if (mDataConsoleOutput) std::cout << "Passenger " << row->getData().mPID << " " << pName << std::endl;
    return row->getData().mPID;
}
Ejemplo n.º 10
0
YBORM_DECL ElementTree::ElementPtr
xmlize_row(const Row &row, const String &entry_name)
{
    ElementTree::ElementPtr entry = ElementTree::new_element(entry_name);
    Row::const_iterator it = row.begin(), end = row.end();
    for (; it != end; ++it)
        entry->sub_element(mk_xml_name(it->first, _T("")),
                it->second.nvl(Value(String(_T("")))).as_string());
    return entry;
}
Ejemplo n.º 11
0
/**
 * Execute a SQL query.
 */
const RecordSet &MySqlDataProvider::execSql(const std::string& sql,
                                            const bool refresh)
{
    if (!mIsConnected)
        throw std::runtime_error("not connected to database");

    LOG_DEBUG("MySqlDataProvider::execSql Performing SQL query: " << sql);

    // do something only if the query is different from the previous
    // or if the cache must be refreshed
    // otherwise just return the recordset from cache.
    if (refresh || (sql != mSql))
    {
        mRecordSet.clear();

        // actually execute the query.
        if (mysql_query(mDb, sql.c_str()) != 0)
            throw DbSqlQueryExecFailure(mysql_error(mDb));

        if (mysql_field_count(mDb) > 0)
        {
            MYSQL_RES* res;

            // get the result of the query.
            if (!(res = mysql_store_result(mDb)))
                throw DbSqlQueryExecFailure(mysql_error(mDb));

            // set the field names.
            unsigned nFields = mysql_num_fields(res);
            MYSQL_FIELD* fields = mysql_fetch_fields(res);
            Row fieldNames;
            for (unsigned i = 0; i < nFields; ++i)
                fieldNames.push_back(fields[i].name);

            mRecordSet.setColumnHeaders(fieldNames);

            // populate the RecordSet.
            MYSQL_ROW row;
            while ((row = mysql_fetch_row(res)))
            {
                Row r;

                for (unsigned i = 0; i < nFields; ++i)
                    r.push_back(static_cast<char *>(row[i]));

                mRecordSet.add(r);
            }

            // free memory
            mysql_free_result(res);
        }
    }

    return mRecordSet;
}
Ejemplo n.º 12
0
	bool checkCols(const Sudoku &s)
	{
		for(unsigned int c = 0; c < 9; ++c) {
			Row l;
			for(const auto &row : s)
				l.push_back(row[c]);
			if (!checkList(l, "in col"))
				return false;
		}
		return true;
	}
Ejemplo n.º 13
0
bool PuzzleMaker::checkRow(int num, int row, int xpos)
{
	Row* toCheck = a->getRow(row);
	for(int i = 0; i < 9; i++)
	{
		int check = toCheck->getTile(i)->getNum();
		if( num == check && i != xpos)
			return false;
	}
	return true;
}
Ejemplo n.º 14
0
size_t IRCBot::readMemberID( string memberName) {
	size_t memberID = 0;
	
	Row Smoking = _db->memberRead(memberName);
	if(Smoking.empty())
		return 0;

	memberID = ((size_t) Smoking["memberID"]);

	return memberID;
}
Ejemplo n.º 15
0
Archivo: mailbox.cpp Proyecto: aox/aox
void MailboxReader::execute() {
    while ( q->hasResults() ) {
        Row * r = q->nextRow();

        UString n = r->getUString( "name" );
        uint id = r->getInt( "id" );
        Mailbox * m = ::mailboxes->find( id );
        if ( !m || m->name() != n ) {
            m = Mailbox::obtain( n );
            if ( n != m->d->name )
                m->d->name = n;
            m->setId( id );
            ::mailboxes->insert( id, m );
        }

        if ( r->getBoolean( "deleted" ) )
            m->setType( Mailbox::Deleted );
        else
            m->setType( Mailbox::Ordinary );

        uint uidvalidity = r->getInt( "uidvalidity" );
        if ( m->d->uidvalidity != uidvalidity ) {
            m->d->uidvalidity = uidvalidity;
            m->abortSessions();
        }
        if ( !r->isNull( "owner" ) )
            m->setOwner( r->getInt( "owner" ) );

        m->setUidnextAndNextModSeq( r->getInt( "uidnext" ),
                                    r->getBigint( "nextmodseq" ),
                                    q->transaction() );

        m->setFlag( r->getEString( "flag" ) );
    }

    if ( !q->done() || done )
        return;

    done = true;
    if ( q->transaction() )
        q->transaction()->commit();
    ::readers->remove( this );
    ::wiped = false;
    if ( q->failed() && !EventLoop::global()->inShutdown() ) {
        List<Mailbox> * c = Mailbox::root()->children();
        if ( c && !c->isEmpty() )
            log( "Couldn't update mailbox tree: " + q->error() );
        else
            log( "Couldn't create mailbox tree: " + q->error(),
                 Log::Disaster );
    }
    if ( owner )
        owner->execute();
};
Ejemplo n.º 16
0
string dbResult::getItem(size_t row, size_t column)
{
	Row rBuff = this->getRow(row);
        if ( column < rBuff.size() ) 
	{
		return rBuff[column];	
	}
	else
	{
		return "";
	}
}
const BookingDatabase::Passengers::Passenger* BookingDatabase::Passengers::getRandom()
{
    if (mChilds.size() == 0)
        return nullptr;

    int random = RandomInt((int)mChilds.size());
    StorageUnit* passenger = mChilds[random];
    Row<Passenger>* passengerRow = static_cast<Row<Passenger>*>(passenger);
    if (passengerRow != nullptr)
        return passengerRow->getDataPtr();
    else return nullptr;
}
Ejemplo n.º 18
0
bool Table::UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, int byteLength, char *data)
{
	assert(columns[columnIndex].columnType==BINARY);

	Row *row = GetRowByIndex(rowIndex,0);
	if (row)
	{
		row->UpdateCell(columnIndex, byteLength, data);
		return true;
	}
	return false;
}
Ejemplo n.º 19
0
QString LevelFile::toQString() {
    QString output;

    for(int i = 0; i < map.size(); i++) {
        Row row = map[i];
        for(int j = 0; j < row.size(); j++) {
            output.append(QString::number(row[j])).append(" ");
        }
        output.append("\n");
    }
    return output;
}
Ejemplo n.º 20
0
bool Table::UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, int value)
{
	assert(columns[columnIndex].columnType==NUMERIC);

	Row *row = GetRowByIndex(rowIndex,0);
	if (row)
	{
		row->UpdateCell(columnIndex, value);
		return true;
	}
	return false;
}
Ejemplo n.º 21
0
bool Table::UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, char *str)
{
	assert(columns[columnIndex].columnType==STRING);

	Row *row = GetRowByIndex(rowIndex,0);
	if (row)
	{
		row->UpdateCell(columnIndex, str);
		return true;
	}
	return false;
}
Ejemplo n.º 22
0
void
nsTreeContentView::OpenContainer(int32_t aIndex)
{
  Row* row = mRows[aIndex].get();
  row->SetOpen(true);

  int32_t count = EnsureSubtree(aIndex);
  if (mBoxObject) {
    mBoxObject->InvalidateRow(aIndex);
    mBoxObject->RowCountChanged(aIndex + 1, count);
  }
}
Ejemplo n.º 23
0
void
nsTreeContentView::CloseContainer(int32_t aIndex)
{
  Row* row = mRows[aIndex].get();
  row->SetOpen(false);

  int32_t count = RemoveSubtree(aIndex);
  if (mBoxObject) {
    mBoxObject->InvalidateRow(aIndex);
    mBoxObject->RowCountChanged(aIndex + 1, -count);
  }
}
Ejemplo n.º 24
0
	bool SelectionOperator::next() {
		assert(isOpen);

		while (in.next()) {
			Row input = in.getOutput();
			
			if (*(input.at(index)) == constant)
				return true;
		}

		return false;
	}
Ejemplo n.º 25
0
void 
ratReader::raster_engine(int y, int x, int xr, ChannelMask channels, Row& row) 
{ 
    //lock.lock();
    int Y = height() - y - 1;
    row.range(0, width());        
 
    if (rat && loaded)
    {
        const IMG_Stat &stat = rat->getStat();
        #if defined(DEBUG)
        iop->warning("Raster engine active.");
        #endif
        foreach(z, channels)
        {
            if (rat_chan_index.count(z) == 0)
            {
                #if defined(DEBUG)
                iop->error("%s can't be found in rat_chan_index", getName(z));
                #endif
                continue;
            }
            int rindex  = rat_chan_index[z].first;
            int color   = rat_chan_index[z].second;
            int ncolors = IMGvectorSize((stat.getPlane(rindex))->getColorModel());
            PXL_Raster *raster  = images(rindex);

            if (!raster)
            {   
                iop->error("Can't allocate the raster? %i", rindex);
                continue;
            }
                
            #if defined(DEBUG)
            iop->warning("%s.%s writes to: %s. Interleaved: %i, colors: %i", (stat.getPlane(rindex))->getName(), \
                        (stat.getPlane(rindex))->getComponentName(color), getName(z), raster->isInterleaved(), ncolors);
            #endif
            
            if (iop->aborted()) 
            {
                lock.unlock();
                return;            
            }
            float       *dest   = row.writable(z);
            const float *pixels = (const float*)raster->getPixels();
            for (int j = 0; j < width(); j++)
            {
                dest[j] = pixels[j*ncolors+(Y*width()*ncolors)+color];
            }
        }
    } 
    else
    {
Ejemplo n.º 26
0
void genQuicklookRow(sqlite3_stmt* stmt, Row& r) {
  for (int i = 0; i < sqlite3_column_count(stmt); i++) {
    auto column_name = std::string(sqlite3_column_name(stmt, i));
    auto column_type = sqlite3_column_type(stmt, i);
    if (column_type == SQLITE_TEXT) {
      auto value = sqlite3_column_text(stmt, i);
      if (value != nullptr) {
        r[column_name] = std::string((const char*)value);
      }
    } else if (column_type == SQLITE_INTEGER) {
      // Handle INTEGER columns explicitly to handle the date-value offset.
      auto value = sqlite3_column_int(stmt, i);
      if (column_name == "last_hit_date") {
        value += kReferenceDateOffset;
      }
      r[column_name] = INTEGER(value);
    } else if (column_type == SQLITE_BLOB) {
      // Handle BLOB values explicitly to avoid the default char* termination
      // for binary-plist data.
      auto getField = [](const pt::ptree& tree, const std::string& field) {
        if (field == "mtime" && tree.count(field) > 0) {
          // Apply a special case for embedded date-value fields.
          return INTEGER(tree.get<size_t>(field) + kReferenceDateOffset);
        }
        return (tree.count(field) > 0) ? tree.get<std::string>(field) : "";
      };

      if (column_name == "version") {
        pt::ptree tree;
        auto version = std::string((const char*)sqlite3_column_blob(stmt, i),
                                   sqlite3_column_bytes(stmt, i));
        if (parsePlistContent(version, tree)) {
          r["mtime"] = getField(tree, "date");
          r["size"] = getField(tree, "size");
          r["label"] = getField(tree, "gen");
        }
      }
    }
  }

  // Transform the folder/file_name into an aggregate path.
  r["path"] = std::move(r["folder"]) + "/" + std::move(r["file_name"]);
  r.erase("folder");
  r.erase("file_name");

  // Transform the encoded fs_id.
  auto details = osquery::split(r["fs_id"], "=.");
  if (details.size() == 4) {
    r["volume_id"] = details[2];
    r["inode"] = details[3];
  }
}
Ejemplo n.º 27
0
void
RecordView::AddSheetRecord (Sheet * sheet) {
	ASSERT (sheet != NULL);
	GtkSheet * gtksheet = GTK_SHEET (sheet->gtk_sheet);
	GtkSheetRange range = {gtksheet->range.row0, 0, gtksheet->range.rowi, 0};
	Row * tuple = row_new (gtksheet->maxcol + 1);
	gint sheet_rows = 1;
	
	// More than one row is selected; we must transpose them all into the RV sheet.
	if (range.row0 != range.rowi) {
		sheet_rows = range.rowi - range.row0 + 1;
	}
			
	Sheet * record_sheet = this->wb->add_new_sheet (this->wb,sheet->name,gtksheet->maxcol + 1,sheet_rows);
	int column = 0, row = 0;

	do {
		sheet->get_row (sheet, range.row0, tuple->cells, tuple->size);

		// Change the titles of the columns to the row titles. This is only going to work if the
		// row titles have been explicitly set somewhere inside of the plugin.
		record_sheet->set_column_title (record_sheet,
												  row,
												  sheet->row_titles->cells[range.row0]->value->str);
		
		for (int ii = 0; ii < tuple->size; ii++) {
			// We only need to change the row titles once. This can happen on our last iteration.
			if (range.row0 == range.rowi) {
				record_sheet->set_row_title (record_sheet,
													  ii,
													  sheet->column_titles->cells[ii]->value->str);

			}
			
			record_sheet->set_cell (record_sheet,
											ii,
											column,
											tuple->cells[ii]->value->str);

			if (sheet->cells[range.row0][ii]->attributes.highlighted == TRUE) {
				record_sheet->set_cell_background (record_sheet, ii, column, "#ffffcc");
			}
			else if (((ii + 1) % 2) == 0) {
				record_sheet->set_cell_background (record_sheet, ii, column, "#f9f7f9");
			}
		}
		
		range.row0++; column++; row++;
	} while (range.row0 <= range.rowi);

	tuple->destroy (tuple);
}
Ejemplo n.º 28
0
bool Database::add(std::string tablename, string keyValue, Row &object)
{
	Table* table = getTable(tablename);

	if (table == NULL || get(tablename, keyValue) != NULL) return false;

	Row* row = new Row(object.begin(), object.end());

	row->insert(make_pair("key", keyValue));
	table->insert(row);

	return true;
}
Ejemplo n.º 29
0
size_t Results::index_of(Row const& row)
{
    validate_read();
    if (!row) {
        throw DetatchedAccessorException{};
    }
    if (m_table && row.get_table() != m_table) {
        throw IncorrectTableException{
            ObjectStore::object_type_for_table_name(m_table->get_name()),
            ObjectStore::object_type_for_table_name(row.get_table()->get_name())};
    }
    return index_of(row.get_index());
}
Ejemplo n.º 30
0
void
nsTreeContentView::SerializeSeparator(nsIContent* aContent,
                                      int32_t aParentIndex, int32_t* aIndex,
                                      nsTArray<nsAutoPtr<Row> >& aRows)
{
  if (aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::hidden,
                            nsGkAtoms::_true, eCaseMatters))
    return;

  Row* row = new Row(aContent, aParentIndex);
  row->SetSeparator(true);
  aRows.AppendElement(row);
}