Esempio n. 1
0
bool Equation_Array::Add_Equation (int type, char *parameters)
{
	static char *eq_text [] = {"BPR", "BPR_PLUS", "EXPONENTIAL", "CONICAL", "AKCELIK", "BPR+", "EXP", "CON", NULL};
	static Equation_Type eq_map [] = { BPR, BPR_PLUS, EXP, CONICAL, AKCELIK, BPR_PLUS, EXP, CONICAL };

	Equation *eq_ptr = (Equation *) Record (type);

	if (eq_ptr == NULL) return (false);

	if (parameters != NULL) {
		int i;
		char buffer [FIELD_BUFFER];

		parameters = Get_Token (parameters, buffer);

		for (i=0; eq_text [i] != NULL; i++) {
			if (str_cmp (buffer, eq_text [i]) == 0) {
				eq_ptr->type = eq_map [i];
				break;
			}
		}
		if (eq_text [i] == NULL) {
			if (Send_Messages ()) {
				exe->Error ("Unrecognized Equation Type = %s", buffer);
			}
			return (false);
		}
		parameters = Get_Double (parameters, &(eq_ptr->a));
		parameters = Get_Double (parameters, &(eq_ptr->b));
		parameters = Get_Double (parameters, &(eq_ptr->c));
		parameters = Get_Double (parameters, &(eq_ptr->d));

		if (eq_ptr->type == BPR || eq_ptr->type == BPR_PLUS) {
			if (eq_ptr->a < 0.01 || eq_ptr->b < 1.0 || eq_ptr->c < 0.4) {
				if (Send_Messages ()) {
					exe->Error ("BPR Equation Parameters %.2lf, %.2lf, %.2lf are Out of Range", eq_ptr->a, eq_ptr->b, eq_ptr->c);
				}
				return (false);
			}
			if (eq_ptr->type == BPR_PLUS) {
				if (eq_ptr->d <= 0.0) eq_ptr->d = 1.0;
				if (eq_ptr->d > 7.0) {
					if (Send_Messages ()) {
						exe->Error ("BPR Plus Equation Minimum Speed %.2lf is Out of Range", eq_ptr->d);
					}
					return (false);
				}
			}
		} else if (eq_ptr->type == EXP) {
			if (eq_ptr->a < 0.07 || eq_ptr->a > 7.5 || eq_ptr->b < 1.0 || eq_ptr->b > 20.0 ||
				eq_ptr->c < 30.0 || eq_ptr->c > 750.0) {
				if (Send_Messages ()) {
					exe->Error ("Exponential Equation Parameters %.2lf, %.2lf, %.1lf are Out of Range", eq_ptr->a, eq_ptr->b, eq_ptr->c);
				}
			}
		} else if (eq_ptr->type == CONICAL) {
			if (eq_ptr->a <= 1.0 || eq_ptr->a > 20.0) {
				if (Send_Messages ()) {
					exe->Error ("Conical Equation Parameter %.2lf is Out of Range (1..20)", eq_ptr->a);
				}
				return (false);
			}
			eq_ptr->b = (2 * eq_ptr->a - 1) / (2 * eq_ptr->a - 2);
		} else if (eq_ptr->type == AKCELIK) {
			if (eq_ptr->a <= 0.05 || eq_ptr->a > 2.5) {
				if (Send_Messages ()) {
					exe->Error ("AKCELIK Equation Parameter *.2lf is Out of Range (0.05..2.5)", eq_ptr->a);
				}
				return (false);
			}
		}
	} else if (type == 1) {

		eq_ptr->type = BPR;
		eq_ptr->a = 0.15;
		eq_ptr->b = 4.0;
		eq_ptr->c = 0.75;
		eq_ptr->d = 0.0;

	} else {

		Equation *prev_ptr = (Equation *) Record (type-1);

		if (prev_ptr == NULL) return (false);

		*eq_ptr = *prev_ptr;
		return (true);
	}

	if (Send_Messages ()) {
		exe->Print (1, "Equation Parameters %d = %s, A=%0.2lf",
			type, eq_text [eq_ptr->type], eq_ptr->a);

		if (eq_ptr->type != CONICAL && eq_ptr->type != AKCELIK) {
			exe->Print (0, ", B=%0.2lf, C=%.2lf", eq_ptr->b, eq_ptr->c);
		}
		if (eq_ptr->type == BPR_PLUS) {
			exe->Print (0, ", D=%.2lf", eq_ptr->d);
		}
	}
	return (true);
}
Esempio n. 2
0
void computePerformance(double threshold = 0.8)
{
	QVector<Record> records;

    QString datasetPath = "C:/Users/XXX/Dropbox/DDTT-dataset/evaluation/userstudy/group matching";

    QString endText = ".gmatch";
    QString extension = "*.gmatch";

	QDir datasetDir(datasetPath);
	QStringList subdirs = datasetDir.entryList(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);

	QStringList users;

	for (QString subdir : subdirs)
	{
		QDir d(datasetPath + "/" + subdir);

        auto matchFiles = d.entryList(QStringList() << extension, QDir::Files);
		if (matchFiles.isEmpty()) continue;

		users << subdir;

		for (QString matchFile : matchFiles)
		{
			// Get matches from file
			QFile ff(d.absolutePath() + "/" + matchFile);
			ff.open(QFile::ReadOnly | QFile::Text);
			QTextStream in(&ff);
			auto matches = in.readAll().split("\n", QString::SkipEmptyParts);

			// Shape names
            QStringList shapes = matchFile.replace(endText, "").split("-", QString::SkipEmptyParts);
            if(shapes.back() == "g") shapes.removeLast();

			bool isSwap = shapes.front() > shapes.back();

			// Add to vector
			QVector< QPair<QString, QString> > pairMatches;
			for (QString matchLine : matches)
			{
				QStringList match = matchLine.split(" ", QString::SkipEmptyParts);

				QString p = match.front();
				QString q = match.back();

				if (isSwap) std::swap(p, q);

				pairMatches << qMakePair(p, q);
			}

			//qDebug() << pairMatches;

			// Add record
			if (isSwap) std::reverse(shapes.begin(), shapes.end());
			for (auto a : pairMatches) records << Record(shapes.front(), shapes.back(), a.first, a.second, subdir);
		}
	}

	// Debug records:
	qSort(records);
	for (Record & record : records)
	{
		//qDebug() << record.p << " " << record.q << " " << record.shapeA << " " << record.shapeB << " " << record.user;
	}

	//qDebug() << "Num records =" << records.size();

	// ShapePairs/part_p/part_q/users
	QMap<QString, QMap<QString, QMap<QString, QStringList> > > part_matches;

	// Extract set of good pair-wise part correspondences
	for (Record r : records)
	{
		part_matches[r.shapeA + "|" + r.shapeB][r.p][r.q] << r.user;
	}

	// Passed threshold
	int num_users = users.size();
	
    QVector<Record> C, badC;

	for (QString shapePair : part_matches.keys())
	{
		auto cur_shape_pairs = shapePair.split("|");

		for (auto p : part_matches[shapePair].keys())
		{
			auto part_matching = part_matches[shapePair][p];

			for (auto q : part_matching.keys())
			{
				auto match = part_matching[q];

				int num_assigned = match.size();

				double v = double(num_assigned) / num_users;

				if (v >= threshold)
				{
					C << Record(cur_shape_pairs.front(), cur_shape_pairs.back(), p, q, "from_users");
				}
                else
                {
                    badC << Record(cur_shape_pairs.front(), cur_shape_pairs.back(), p, q, "from_users");
                }
			}
		}
	}

	int totalNumPairTypes = C.size() + badC.size();

	//qDebug() << "Num records passed =" << C.size();

	// Ground truth
	// ShapePair/part_p/part_q
	QMap <QString, QMap<QString, QStringList> > ground_truth;
	for (Record r : C)
	{
		QStringList tstr = ground_truth[r.shapeA + "|" + r.shapeB][r.p];
		tstr.push_back(r.q);
		ground_truth[r.shapeA + "|" + r.shapeB][r.p] = tstr;
	}

	// Test set:
	QString testPath = "C:/Users/XXX/Dropbox/DDTT-dataset/evaluation/userstudy/geotopo";
	QDir testDir(testPath);

	int wins = 0;
	int loss = 0;
	int testPairs = 0;

// 	endText = ".match";
// 	extension = "*.match";
	auto matchFiles = testDir.entryList(QStringList() << extension, QDir::Files);
	for (auto matches_filename : matchFiles)
	{
		// Get matches from file
		QFile ff(testDir.absolutePath() + "/" + matches_filename);
		ff.open(QFile::ReadOnly | QFile::Text);
		QTextStream in(&ff);
		auto matches = in.readAll().split("\n", QString::SkipEmptyParts);

        QStringList shapes = matches_filename.replace(endText, "").split("-", QString::SkipEmptyParts);
        if(shapes.back() == "g") shapes.removeLast();

		bool isSwap = shapes.front() > shapes.back();

		// Shape names sorted
		if (isSwap) std::reverse(shapes.begin(), shapes.end());
		QString shapeA = shapes.front();
		QString shapeB = shapes.back();

		// Get pair matches
		for (QString matchLine : matches)
		{
			QStringList match = matchLine.split(" ", QString::SkipEmptyParts);

			QString p = match.front();
			QString q = match.back();

			if (isSwap) std::swap(p, q);

			if (ground_truth[shapeA + "|" + shapeB].contains(p))
			{
				QStringList truth = ground_truth[shapeA + "|" + shapeB][p];

				if (truth.contains(q))
					wins++;
				else
					loss++;
			}
			testPairs++;
		}
	}

	double performance = (double(wins) / (wins + loss));

	QString result = QString("Performance = %1, agreement %6%, selected = %4, wins = %2, loss = %3, all pairs = %5, test = %7")
		.arg(performance).arg(wins).arg(loss).arg(C.size()).arg(records.size()).arg(threshold * 100).arg(testPairs);

	QMessageBox::information(0, "Performance", result);

	qDebug() << result;
}
Esempio n. 3
0
 static inline void Info(Event event, Args&& ...args) {
     Record(EventSeverity::Info, event, ::std::forward<Args>(args)...);
 }
Esempio n. 4
0
bool Db_Record::Set_Field_Number (int number, char *string)
{
	char *rec = Record ();

	if (rec == NULL) return (Status (RECORD_SIZE));

	int len, size, shift;
	char *ptr, *field, buffer [FIELD_BUFFER];

	//---- remove trailing blanks ----

	len = (int) strlen (string);
	ptr = string + len - 1;
	
	while (ptr > string) {
		if (*ptr != ' ') break;
		len--;
		*ptr-- = '\0';
	}

	//---- set the record pointer ----

	size = 0;
	field = ptr = rec;

	//---- locate the field number ----

	for (int i=0; i < number; i++) {
		ptr = Parse_String (ptr, buffer, sizeof (buffer));

		//---- if the field was not found add a dummy field ----

		if (ptr == NULL) {
			size = (int) strlen (rec);
			if (size + 3 >= max_size) return (Status (RECORD_SIZE));

			ptr = rec + size;

			if (*delimiters == ' ') {
				*ptr++ = '\"';
				*ptr++ = '\"';
			}
			*ptr++ = *delimiters;
			*ptr = '\0';
		}

		//---- set the field pointer ----

		if (i == number - 2) {
			field = ptr;
		}
	}

	//---- check the size of the string after the field ----

	shift = (int) strlen (ptr);
	size = (int) (field - rec);
	if (size + 2 >= max_size) return (Status (RECORD_SIZE));

	if (size + len + shift + 3 >= max_size) {
		shift -= (max_size - size - len - 3);
		if (shift < 0) shift = 0;
	}

	if (strstr (string, delimiters)) {
		if (shift) {
			memmove (field + len + 3, ptr, shift+1);
		}
		*field++ = '"';
		memcpy (field, string, len);
		*(field + len) = '"';
		*(field + len + 1) = (shift) ? *delimiters : '\0';
	} else {
		if (shift) {
			memmove (field + len + 1, ptr, shift+1);
		}
		memcpy (field, string, len);
		*(field + len) = (shift) ? *delimiters : '\0';
	}
	rec [max_size + 1] = '\0';
	return (true);
}
Esempio n. 5
0
	Trip_Data * operator[] (int index)       { return (Record (index)); }
Esempio n. 6
0
App::App(int &argc, char **argv)
: QApplication(argc, argv), d(new Data(this)) {
#ifdef Q_OS_LINUX
	setlocale(LC_NUMERIC,"C");
#endif
	setOrganizationName("xylosper");
	setOrganizationDomain("xylosper.net");
	setApplicationName(Info::name());
	setApplicationVersion(Info::version());
	setLocale(Record(APP_GROUP).value("locale", QLocale::system()).toLocale());

	d->addOption(LineCmd::Open, "open", tr("Open given %1 for file path or URL."), "mrl");
	d->addOption(LineCmd::Wake, QStringList() << "wake", tr("Bring the application window in front."));
	d->addOption(LineCmd::Action, "action", tr("Exectute %1 action or open %1 menu."), "id");
	d->addOption(LineCmd::LogLevel, "log-level", tr("Maximum verbosity for log. %1 should be one of nexts:")
				 % "\n    " % Log::options().join(", "), "lv");
	d->addOption(LineCmd::OpenGLDebug, "opengl-debug", tr("Turn on OpenGL debug logger."));
	d->addOption(LineCmd::Debug, "debug", tr("Turn on options for debugging."));
	d->getCommandParser(&d->cmdParser)->process(arguments());
	d->getCommandParser(&d->msgParser);
	d->execute(&d->cmdParser);

#if defined(Q_OS_MAC) && defined(CMPLAYER_RELEASE)
	static const QByteArray path = QApplication::applicationDirPath().toLocal8Bit();
	_Debug("Set $LIBQUVI_SCRIPTSDIR=\"%%\"", QApplication::applicationDirPath());
	if (setenv("LIBQUVI_SCRIPTSDIR", path.data(), 1) < 0)
		_Error("Cannot set $LIBQUVI_SCRIPTSDIR. Some streaming functions won't work.");
#endif

	setQuitOnLastWindowClosed(false);
#ifndef Q_OS_MAC
	setWindowIcon(defaultIcon());
#endif
	auto makeStyleNameList = [this] () {
		auto names = QStyleFactory::keys();
		const auto defaultName = style()->objectName();
		for (auto it = ++names.begin(); it != names.end(); ++it) {
			if (defaultName.compare(*it, Qt::CaseInsensitive) == 0) {
				const auto name = *it;
				names.erase(it);
				names.prepend(name);
				break;
			}
		}
		return names;
	};
	auto makeStyle = [this]() {
		Record r(APP_GROUP);
		auto name = r.value("style", styleName()).toString();
		if (style()->objectName().compare(name, Qt::CaseInsensitive) == 0)
			return;
		if (!d->styleNames.contains(name, Qt::CaseInsensitive))
			return;
		setStyle(QStyleFactory::create(name));
	};
	d->styleNames = makeStyleNameList();
	makeStyle();
	connect(&d->connection, &LocalConnection::messageReceived, [this] (const QString &message) {
		d->msgParser.parse(message.split("[:sep:]")); d->execute(&d->msgParser);
	});
}
Esempio n. 7
0
DB2FileLoaderRegularImpl::Record DB2FileLoaderRegularImpl::getRecord(size_t id)
{
    assert(data);
    return Record(*this, data + id * _header->RecordSize);
}
Esempio n. 8
0
 SystemMethodTimer::~SystemMethodTimer()
 {
   Record();
   Report();
 }
Esempio n. 9
0
	Group_Link * operator[] (int index)     { return (Record (index)); }
Esempio n. 10
0
void calc_algric_tree(algbric_node *root) {
    if (root->flag == true) 
        return;
    string table_name;
    int blockNum, offset;
    auto new_col_list = new vector<table_column *>, old_col_list = new_col_list, old_col_list2 = new_col_list;
    // auto old_col_list = catm.exist_relation((root->left->table))->cols;

    switch ( root->op ) {
        case algbric_node::DIRECT :
            root->flag = true;
            return;
        case algbric_node::PROJECTION : 
        {
            if (!root->left->flag) calc_algric_tree(root->left);
            old_col_list = catm.exist_relation((root->left->table))->cols;

            for( auto x : *(root->projection_list) ) {
                auto att = catm.exist_relation(x->relation_name)->get_column(x->attribute_name);
                new_col_list->push_back(new table_column((root->left->op == algbric_node::DIRECT ? x->attribute_name.c_str() : x->full_name.c_str()), att->data_type, att->str_len, 0 ));
            }
            table_name = create_temp_table(new_col_list);
            root->table = table_name;

            auto cursor = RecordManager.getCursor(root->left->table, catm.calc_record_size(root->left->table));
            while (cursor->next()) {
                Record r = cursor->getRecord();
                vector<record_value> result;
                for(auto i = new_col_list->begin(); i != new_col_list->end(); i++) {
                    for(auto j = old_col_list->begin(); j != old_col_list->end(); j++ ) {
                        if ( (*i)->name == (*j)->name ) {
                            result.push_back(r.values[j-old_col_list->begin()]);
                        }
                    }
                }
                RecordManager.insertRecord(table_name, Record(result, new_col_list), blockNum, offset);
            }

            if (root->left->op != algbric_node::DIRECT) catm.drop_table(root->left->table);

            root->flag = true;
            return;
        }
        case algbric_node::SELECTION : 
        {
            string left_name = root->left->table;
            old_col_list = catm.exist_relation(left_name)->cols;
            for( auto x : *(old_col_list) ) {
                new_col_list->push_back( new table_column(x->name.c_str(), x->data_type, x->str_len, x->flag ));
            }

            table_name = create_temp_table(new_col_list);
            root->table = table_name;

            condition *p = NULL, *eq = NULL;
            for(auto x : (root->conditions)) {
                if ( catm.is_indexed(x->left_attr) ) {
                    p = x;
                    if (x->op == condition::EQUALTO) 
                        eq = x;
                }
            }

            if ( eq != NULL ) p = eq;

            if ( p != NULL ) {
                cout << "Index used: " << p->left_attr->full_name << endl;
                int record_size = catm.calc_record_size(root->left->table);
                auto t = p->left_attr;
                indexIterator cursor;
                int asdf = IndexManager.selectNode(cursor, t->relation_name + "/index_" + t->attribute_name + ".db", 
                        p->op, (p->v).to_str(catm.get_data_type(t)));
                if ( asdf == 0 ) {
                    int b = 0, c = 0;
                    while (cursor.next(b, c) == 0) {
                        Record a = RecordManager.getRecord(t->relation_name, b, c, record_size);
                        if (calc_conditions(&(root->conditions), a))
                            RecordManager.insertRecord(table_name, a, blockNum, offset);
                    }
                }
            } else {
                string t = root->left->table;
                int record_size = catm.calc_record_size(t);
                indexIterator cursor;
                int asdf = IndexManager.getStarter(cursor, t + "/index_" + catm.get_primary(t) + ".db");
                if ( asdf == 0 ) {
                    int b = 0, c = 0;
                    while (cursor.next(b, c) == 0) {
                        Record a = RecordManager.getRecord(t, b, c, record_size);
                        if (calc_conditions(&(root->conditions), a))
                            RecordManager.insertRecord(table_name, a, blockNum, offset);
                    }
                }
            }

            root->flag = true;
            return;
        }
        case algbric_node::JOIN :
        {
            if (!root->left->flag) calc_algric_tree(root->left);
            if (!root->right->flag) calc_algric_tree(root->right);
            if ( catm.get_size(root->right->table) < catm.get_size(root->left->table) ) {
                auto tmp = root->left;
                root->left = root->right;
                root->right = tmp;
            }

            
            old_col_list = catm.exist_relation((root->left->table))->cols;
            old_col_list2= catm.exist_relation((root->right->table))->cols;

            for( auto x : *old_col_list ) {
                new_col_list->push_back(new table_column(x->name.c_str(), x->data_type, x->str_len, 0 ));
            }

            for( auto x : *old_col_list2 ) {
                new_col_list->push_back(new table_column(x->name.c_str(), x->data_type, x->str_len, 0 ));
            }

            table_name = create_temp_table(new_col_list);
            root->table = table_name;

            auto outter_table = catm.exist_relation(root->left->table), inner_table = catm.exist_relation(root->right->table);
            int outter_size = catm.calc_record_size(root->left->table), inner_size = catm.calc_record_size(root->right->table);
            outter_table->get_size();
            condition * p = NULL;

            for ( auto x : root->conditions ) {
                if ( outter_table->get_column(x->left_attr->full_name) != NULL && inner_table->get_column(x->right_attr->full_name) != NULL) {

                } else if ( inner_table->get_column(x->left_attr->full_name) != NULL && outter_table->get_column(x->right_attr->full_name) != NULL) {
                    auto tmp = x->left_attr;
                    x->left_attr = x->right_attr;
                    x->right_attr = tmp;
                }
                assert( outter_table->get_column(x->left_attr->full_name) != NULL && inner_table->get_column(x->right_attr->full_name) != NULL);

                if ( inner_table->is_indexed(x->right_attr->full_name) ) {
                    p = x;
                }

            }

            auto cursor1 = RecordManager.getCursor(root->left->table, outter_size);

	    cout << "Index used: " << p->right_attr->full_name << endl;
            while (cursor1->next()) {
                Record r1 = cursor1->getRecord();
                if ( p ) {
                    // nested-index join
                    indexIterator a;
                    int asdf = IndexManager.getStarter(a, root->right->table + "/index_" + p->right_attr->full_name + ".db");
                    if (asdf == 0) {
                        int b = 0, c = 0;
                        while (a.next(b, c) == 0) {
                            Record r2 = RecordManager.getRecord(root->right->table, b, c, inner_size);
                            if ( calc_conditions(&(root->conditions), r1, r2) )  {
                                vector<record_value> result(r1.values);
                                result.insert(result.end(), r2.values.begin(), r2.values.end());
                                RecordManager.insertRecord(table_name, Record(result, new_col_list), blockNum, offset);
                            }
                        }
                    }
                } else {
                    // nested-loop join
                    auto cursor2 = RecordManager.getCursor(root->right->table, inner_size);
                    while (cursor2->next()) {
                        Record r2 = cursor2->getRecord();
                        if ( calc_conditions(&(root->conditions), r1, r2) )  {
                            vector<record_value> result(r1.values);
                            result.insert(result.end(), r2.values.begin(), r2.values.end());
                            RecordManager.insertRecord(table_name, Record(result, new_col_list), blockNum, offset);
                        }
                    }
                    delete cursor2;
                }
            }
            delete cursor1;

            if (root->right->op != algbric_node::DIRECT) catm.drop_table(root->right->table);
            if (root->left->op != algbric_node::DIRECT) catm.drop_table(root->left->table);

            root->flag = true;
            return;
        }
    }
}
Esempio n. 11
0
 FunctionCategoryTimer::~FunctionCategoryTimer()
 {
   Record();
   Report();
 }
Esempio n. 12
0
bool Db_Base::Write_Field (Db_Field *fld, void *data, Field_Type type)
{
	if (data == 0) return (Status (NULL_POINTER));
	if (fld == 0) return (Status (NO_FIELD, false));
	if (!Record ().OK ()) return (Status (RECORD_SIZE));

	int lvalue = 0;
	unsigned uvalue = 0;
	double dvalue = 0.0;
	Dtime tvalue;
	String svalue;
	Field_Type fld_type;

	//---- convert the input data type to generic variables ----

	fld_type = fld->Type ();

	switch (fld_type) {
		default:
			return (Status (DB_ERROR));
			
		case DB_INTEGER:
			switch (type) {
				case DB_INTEGER:
					lvalue = *((int *) data);
					break;
				case DB_DOUBLE:
					dvalue = *((double *) data);
					if (dvalue > MAX_INTEGER) {
						lvalue = MAX_INTEGER;
					} else if (dvalue < -MAX_INTEGER) {
						lvalue = -MAX_INTEGER;
					} else {
						lvalue = DTOI (dvalue);
					}
					break;
				case DB_STRING:
					lvalue = ((String *) data)->Integer ();
					break;
				case DB_TIME:
					lvalue = (int) (*((Dtime *) data));
					break;
				default:
					return (Status (DB_ERROR));
			}
			break;

		case DB_UNSIGNED:
			switch (type) {
				case DB_INTEGER:
					uvalue = *((unsigned *) data);
					break;
				case DB_DOUBLE:
					dvalue = *((double *) data);
					if (dvalue > 2.0 * MAX_INTEGER) {
						uvalue = MAX_INTEGER;
						uvalue *= 2;
					} else if (dvalue < 0.0) {
						uvalue = 0;
					} else {
						uvalue = (unsigned) (dvalue + 0.5);
					}
					break;
				case DB_STRING:
					uvalue = ((String *) data)->Integer ();
					break;
				case DB_TIME:
					uvalue = (unsigned) (*((Dtime *) data));
					break;
				default:
					return (Status (DB_ERROR));
			}
			break;

		case DB_FIXED:
		case DB_DOUBLE:
			switch (type) {
				case DB_INTEGER:
					dvalue = (double) *((int *) data);
					break;
				case DB_DOUBLE:
					dvalue = *((double *) data);
					break;
				case DB_STRING:
					dvalue = ((String *) data)->Double ();
					break;
				case DB_TIME:
					dvalue = (double) *((Dtime *) data);
					break;
				default:
					return (Status (DB_ERROR));
			}
			break;
		
		case DB_STRING:
		case DB_CHAR:
			switch (type) {
				case DB_INTEGER:
					if (fld->Units () >= FACILITY_CODE) {
						External_Units (*((int *) data), fld->Units (), svalue);
					} else {
						svalue (*((int *) data));
					}
					break;
				case DB_DOUBLE:
					svalue (*((double *) data), fld->Decimal ());
					break;
				case DB_STRING:
					svalue = *((string *) data);
					break;
				case DB_TIME:
					svalue = ((Dtime *) data)->Time_String (fld->Units ());
					break;
				default:
					return (Status (DB_ERROR));
			}
			break;

		case DB_TIME:
			switch (type) {
				case DB_INTEGER:
					tvalue = *((int *) data);
					break;
				case DB_DOUBLE:
					tvalue = *((double *) data);
					break;
				case DB_STRING:
					tvalue = *((string *) data);
					break;
				case DB_TIME:
					tvalue = *((Dtime *) data);
					break;
				default:
					return (Status (DB_ERROR));
			}
			break;
	}

	//---- convert to external units ----

	if (fld->Units () != NO_UNITS) {
		if (fld_type == DB_INTEGER) {
			lvalue = (int) External_Units (lvalue, fld->Units ());
		} else if (fld_type == DB_UNSIGNED) {
			uvalue = (unsigned) External_Units ((int) uvalue, fld->Units ());
		} else if (fld_type == DB_DOUBLE || fld_type == DB_FIXED) {
			dvalue = External_Units (dvalue, fld->Units ());
		} else if ((fld_type == DB_STRING || fld_type == DB_CHAR) && fld->Units () < FACILITY_CODE) {
			return (Status (FIELD_UNITS));
		}
	}

	//---- place the data onto the data record -----

	Nested (fld->Nested ());

	char *field = Record_String ();

	bool asc_flag = false;
	bool justify = false;
	int len, position;
	int size = fld->Width ();
	int offset = fld->Offset ();

	switch (Record_Format ()) {
		case BINARY:
			field += offset;
			asc_flag = false;
			break;
		case FIXED_COLUMN:
			field += offset;
			memset (field, ' ', size);
			asc_flag = justify = true;
			break;
		case COMMA_DELIMITED:
		case SPACE_DELIMITED:
		case TAB_DELIMITED:
		case CSV_DELIMITED:
		default:		
			asc_flag = true;
			justify = false;
			break;
	}

	switch (fld_type) {
		default:
			return (Status (DB_ERROR));
			
		case DB_INTEGER:
			if (asc_flag) {
				svalue (lvalue);

				if (justify) {
					len = (int) svalue.size ();
					position = size - len;
					if (position < 0) {
						position = 0;
						len = size;
					}
					memcpy (field + position, svalue.c_str (), len);
				}
			} else if (size == sizeof (int)) {
				*((int *) field) = lvalue;
			} else if (size == sizeof (short)) {
				if (lvalue > 32767) lvalue = 32767;
				*((short *) field) = (short) lvalue;
			} else if (size == sizeof (char)) {
				if (lvalue > 127) lvalue = 127;
				*((char *) field) = (char) lvalue;
			} else {
				return (Status (FIELD_BYTES));
			}
			break;
			
		case DB_UNSIGNED:
			if (asc_flag) {
				svalue ((size_t) uvalue);

				if (justify) {
					len = (int) svalue.size ();
					position = size - len;
					if (position < 0) {
						position = 0;
						len = size;
					}
					memcpy (field + position, svalue.c_str (), len);
				}
			} else if (size == sizeof (int)) {
				*((unsigned int *) field) = (unsigned int) uvalue;
			} else if (size == sizeof (short)) {
				if (uvalue > 65535) uvalue = 65535;
				*((unsigned short *) field) = (unsigned short) uvalue;
			} else if (size == sizeof (char)) {
				if (uvalue > 255) uvalue = 255;
				*((unsigned char *) field) = (unsigned char) uvalue;
			} else {
				return (Status (FIELD_BYTES));
			}
			break;

		case DB_DOUBLE:
			if (asc_flag) {
				svalue (dvalue, fld->Decimal ());
				if (justify) {
					len = (int) svalue.size ();
					position = size - len;
					if (position < 0) {
						position = 0;
						len = size;
					}
					memcpy (field + position, svalue.c_str (), len);
				}
			} else if (size == sizeof (double)) {
				*((double *) field) = dvalue;
			} else if (size == sizeof (float)) {
				*((float *) field) = (float) dvalue;
			} else {
				return (Status (FIELD_BYTES));
			}
			break;

		case DB_FIXED:
			if (asc_flag) {
				svalue (dvalue, fld->Decimal ());

				if (justify) {
					len = (int) svalue.size ();
					position = size - len;
					if (position < 0) {
						position = 0;
						len = size;
					}
					memcpy (field + position, svalue.c_str (), len);
				}
			} else {
				if (dvalue < 0.0) {
					lvalue = (int) (dvalue * pow (10.0, fld->Decimal ()) - 0.5);
				} else {
					lvalue = (int) (dvalue * pow (10.0, fld->Decimal ()) + 0.5);
				}

				if (size == sizeof (int)) {
					*((int *) field) = lvalue;
				} else if (size == sizeof (short)) {
					*((short *) field) = (short) lvalue;
				} else if (size == sizeof (char)) {
					*((char *) field) = (char) lvalue;
				} else {
					return (Status (FIELD_BYTES));
				}
			}
			break;

		case DB_STRING:
			if (asc_flag) {
				if (justify) {
					len = (int) svalue.size ();
					if (len > size) len = size;
					memcpy (field, svalue.c_str (), len);
				}
			} else {
				memset (field, '\0', size);
				memcpy (field, svalue.c_str (), MIN ((int) svalue.size (), size));
			}
			break;
			
		case DB_CHAR:
			if (!asc_flag || justify) {
				memset (field, '\0', size);
				field [0] = svalue [0];
			}
			break;
			
		case DB_TIME:
			if (asc_flag) {
				svalue = tvalue.Time_String (fld->Units ());
				if (justify) {
					len = (int) svalue.size ();
					if (len > size) len = size;
					memcpy (field, svalue.c_str (), len);
				}
			} else if (size == sizeof (Dtime)) {
				*((Dtime *) field) = tvalue;
			} else if (size == sizeof (short)) {
				*((short *) field) = (short) tvalue;
			} else {
				return (Status (FIELD_BYTES));
			}
			break;
	}
	if (asc_flag && !justify) {
		if (Record_Format () == UNFORMATED) {
			return (Set_Field_Number (offset, svalue));
		} else {
			fld->Buffer (svalue);
		}
	}
	return (true);
}
Esempio n. 13
0
 static inline void Error(Event event, Args&& ...args) {
     Record(EventSeverity::Error, event, ::std::forward<Args>(args)...);
 }
Esempio n. 14
0
	Route_Legs * operator[] (int index)  { return ((Route_Legs *) Record (index)); }
void Maze::search() {
    size_t row = entrance_row;
    size_t col = entrance_col;

    while (1) {
        int right = 0;
        int down = 0;
        int left = 0;
        int up = 0;

        // Ah! We have landed on a new tile
        // but haven't left our footprints!

        // First let's find out our situation:
        // Is it the exit?!
        if (row == exit_row && col == exit_col) {
            maze[row][col] = touched;
            records.push(Record(row, col, touched));
            return;
        }

        // Search for the directions we can go.
        if (col < width - 1 && maze[row][col + 1] == not_touched) {
            right = 1;
        }
        if (row < height - 1 && maze[row + 1][col] == not_touched) {
            down = 1;
        }
        if (col > 0 && maze[row][col - 1] == not_touched) {
            left = 1;
        }
        if (row > 0 && maze[row - 1][col] == not_touched) {
            up = 1;
        }

        if (right + down + left + up == 1) {
            // If we has exactly one way to go, then go!

            maze[row][col] = touched;
            records.push(Record(row, col, touched));
            if (right == 1) {
                ++col;
            } else if (down == 1) {
                ++row;
            } else if (left == 1) {
                --col;
            } else {
                --row;
            }

        } else if (right + down + left + up > 1) {
            // If we have multiple directions available,
            // then it is an intercection.

            maze[row][col] = intersection;
            records.push(Record(row, col, intersection));

            if (right == 1) {
                ++col;
            } else if (down == 1) {
                ++row;
            } else if (left == 1) {
                --col;
            } else {
                --row;
            }

        } else if (right + down + left + up == 0) {
            // Too bad! We don't have any way to go.
            // Just get back.

            while (maze[row][col] != intersection && !records.empty()) {
                maze[row][col] = wall;
                Record record = records.pop();
                row = record.row;
                col = record.col;
            }

            if (maze[row][col] != intersection && records.empty()) {
                // Oops! Dead maze!
                return;
            }

            maze[row][col] = not_touched;
            // Notice we even erase the record of the intersection.

        }

    }

}
Esempio n. 16
0
	Coordinator_Data * operator[] (int index) { return (Record (index)); }
Esempio n. 17
0
	File_Group * operator[] (int index)  { return ((File_Group *) Record (index)); }
Esempio n. 18
0
TEST_F( SegmentTest, RandomOperations )
{
	// Random interspersed operations
	std::unordered_map<TID, uint32_t> values; // TID -> testData entry
	std::vector<TID> tids;

	// Insert some baseline records
	for ( uint32_t i = 0; i < 100; ++i )
	{
		// Select string/record to insert
		uint64_t r = rand() % testData.size();
		const std::string s = testData[r];

		// Insert record
		TID tid = segment->Insert( Record( static_cast<uint32_t>(s.size()),
										   reinterpret_cast<const uint8_t*>(s.c_str()) ) );
		tids.push_back( tid );
		EXPECT_EQ( values.find( tid ), values.end() ); // TIDs should not be overwritten
		values[tid] = static_cast<uint32_t>(r);
	}

	// Random ops
	for ( uint32_t i = 0; i < 10000; ++i )
	{
		float chance = static_cast<float>(rand()) / RAND_MAX;
		if (chance < 0.70)
		{
			// Insert
			// Select string/record to insert
			uint64_t r = rand() % testData.size();
			const std::string s = testData[r];

			// Insert record
			TID tid = segment->Insert( Record( static_cast<uint32_t>(s.size()),
											   reinterpret_cast<const uint8_t*>(s.c_str()) ) );

			EXPECT_EQ( values.find( tid ), values.end() ); // TIDs should not be overwritten
			tids.push_back( tid );
			values[tid] = static_cast<uint32_t>(r);
		}
		else if (chance < 0.9)
		{
			// Update
			// Select new string / record
			TID target = tids[rand() % tids.size()];
			uint32_t r = rand() % testData.size();
			const std::string s = testData[r];

			// Replace old with new value
			bool success = segment->Update( target, Record( static_cast<uint32_t>(s.size()),
															reinterpret_cast<const uint8_t*>(s.c_str()) ) );

			EXPECT_EQ( true, success );
			values[target] = static_cast<uint32_t>(r);
		}
		else
		{
			// Remove
			uint32_t inTid = rand() % tids.size();
			TID target = tids[inTid];
			bool removeSuccess = segment->Remove( target );
			EXPECT_EQ( true, removeSuccess );
			// Remove from our tid map and tid vector as well
			values.erase( target );
			tids[inTid] = tids[tids.size() - 1];
			tids.pop_back();
		}
	}

	// Every value has to be the same as it was inserted/updated to
	for ( std::pair<TID, uint32_t> tidValue : values )
	{
		// Not removed, normal check
		const std::string& value = testData[tidValue.second];
		uint32_t len = static_cast<uint32_t>(value.size());
		Record rec = segment->Lookup( tidValue.first );
		EXPECT_EQ( len, rec.GetLen() );
		EXPECT_EQ( 0, memcmp( rec.GetData(), value.c_str(), len ) );
	}
};
Esempio n. 19
0
	Node_List * operator[] (int index)    { return (Record (index)); }
Esempio n. 20
0
void GeneticAlgorithm(){

    int maxIter = 100;
    int i,j,k;
    int group[GROUP_SIZE][COUNT_FUNC];
    int oldParameter[COUNT_FUNC];
    int maxIndex;
    double sum,max,min,tmp;
    int count_record = 0;
    char output[300];

    /*初始族群*/
    InitGroup(group);



    for ( i = 0 ; i < maxIter ; i++){
        Eliminate(group);
        Crossover(group);
        Mutation(group);

        sum = 0;
        max = -1;
        min = 20;
        maxIndex = 0;
        #pragma omp parallel for
        for ( j = 0 ; j < GROUP_SIZE ; j++){
            tmp= Evalue( group[j]);

            if ( tmp > 10){
                fout = fopen("parameter.txt", "a");
                sprintf(output,"Parameter = ");
                for ( k = 0 ; k < COUNT_FUNC ; k++){
                    sprintf(output,"%s %5d",output, group[j][k]);
                }
                sprintf(output,"%s, Score = %lf\n",output,tmp);
                fprintf(fout,"%s",output);
                fclose(fout);
            }

            sum += tmp;

            if ( tmp > max ){
                max= tmp;
                maxIndex = j;
            }
            if ( tmp < min )
                min = tmp;
        }
        if ( i % 10 == 0)
            Record(group);
        printf("Level(%d) = %.2lf, %.2lf, %.2lf\n", i,max,sum/GROUP_SIZE,min);
        if ( max >= 10.5 && PlayGame(group[maxIndex]) >= 10.9)
            break;
    }

    printf("==Result==\n");
    for ( i = 0 ; i < COUNT_FUNC ; i++){
        printf(", %d", group[maxIndex][i]);
    }
    putchar('\n');

}
Esempio n. 21
0
DBCFile::Record DBCFile::getRecord(size_t id)
{
    assert(_data);
    return Record(*this, _data + id*_recordSize);
}
Esempio n. 22
0
	Veh_Distribution * operator[] (int index) { return (Record (index)); }
Esempio n. 23
0
DBCFileLoader::Record DBCFileLoader::getRecord(size_t id)
{
    ASSERT(data);
    return Record(*this, data + id*recordSize);
}
Esempio n. 24
0
int main(int argc, const char *argv[])
{
	const char *recordFileName = NULL;

	// set up defaults
	AudioFileTypeID filetype = kAudioFileAIFFType;
	
	bool gotOutDataFormat = false;
	CAStreamBasicDescription dataFormat;
	dataFormat.mSampleRate = 44100.;	// later get this from the hardware
	dataFormat.mFormatID = kAudioFormatLinearPCM;
	dataFormat.mFormatFlags = kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
	dataFormat.mFramesPerPacket = 1;
	dataFormat.mChannelsPerFrame = 2;
	dataFormat.mBitsPerChannel = 16;
	dataFormat.mBytesPerPacket = dataFormat.mBytesPerFrame = 4;
	
	SInt32 bitrate = -1, quality = -1;
	
	// parse arguments
	for (int i = 1; i < argc; ++i) {
		const char *arg = argv[i];
		if (arg[0] != '-') {
			if (recordFileName != NULL) {
				fprintf(stderr, "may only specify one record file\n");
				usage();
			}
			recordFileName = arg;
		} else {
			arg += 1;
			if (arg[0] == 'f' || !strcmp(arg, "-file")) {
				if (++i == argc) MissingArgument();
				filetype = Parse4CharCode(argv[i], "-f | --file");
			} else if (arg[0] == 'd' || !strcmp(arg, "-data")) {
				if (++i == argc) MissingArgument();
				if (!ParseStreamDescription(argv[i], dataFormat))
					usage();
				gotOutDataFormat = true;
			} else if (arg[0] == 'b' || !strcmp(arg, "-bitrate")) {
				if (++i == argc) MissingArgument();
				bitrate = ParseInt(argv[i], "-b | --bitrate");
			} else if (arg[0] == 'q' || !strcmp(arg, "-quality")) {
				if (++i == argc) MissingArgument();
				quality = ParseInt(argv[i], "-q | --quality");
			} else {
				fprintf(stderr, "unknown argument: %s\n\n", arg - 1);
				usage();
			}
		}
	}
	
	if (recordFileName == NULL)
		usage();
	
	if (!gotOutDataFormat) {
		if (filetype == 0) {
			fprintf(stderr, "no output file or data format specified\n\n");
			usage();
		}
		if (!CAAudioFileFormats::Instance()->InferDataFormatFromFileFormat(filetype, dataFormat)) {
			fprintf(stderr, "Couldn't infer data format from file format\n\n");
			usage();
		}
	} else if (filetype == 0) {
		if (!CAAudioFileFormats::Instance()->InferFileFormatFromDataFormat(dataFormat, filetype)) {
			dataFormat.PrintFormat(stderr, "", "Couldn't infer file format from data format");
			usage();
		}
	}

	unlink(recordFileName);
	
	if (dataFormat.IsPCM())
		dataFormat.ChangeNumberChannels(2, true);
	else
		dataFormat.mChannelsPerFrame = 2;
	
	try {
		const int kNumberBuffers = 3;
		const unsigned kBufferSize = 0x8000;
		CAAudioFileRecorder recorder(kNumberBuffers, kBufferSize);
		FSRef parentDir;
		CFStringRef filename;
		XThrowIfError(PosixPathToParentFSRefAndName(recordFileName, parentDir, filename), "couldn't find output directory");
		recorder.SetFile(parentDir, filename, filetype, dataFormat, NULL);
		
		CAAudioFile &recfile = recorder.GetFile();
		if (bitrate >= 0)
			recfile.SetConverterProperty(kAudioConverterEncodeBitRate, sizeof(UInt32), &bitrate);
		if (quality >= 0)
			recfile.SetConverterProperty(kAudioConverterCodecQuality, sizeof(UInt32), &quality);

		Record(recorder);
	}
	catch (CAXException &e) {
		char buf[256];
		fprintf(stderr, "Error: %s (%s)\n", e.mOperation, CAXException::FormatError(buf, e.mError));
		return 1;
	}
	catch (...) {
		fprintf(stderr, "An unknown error occurred\n");
		return 1;
	}
	return 0;
}
Esempio n. 25
0
DB2FileLoader::Record DB2FileLoader::getRecord(size_t id)
{
    assert(data);
    return Record(*this, data + id*recordSize);
}
Esempio n. 26
0
	Period_Index * operator[] (int index)   { return (Record (index)); }
Esempio n. 27
0
bool Arg_parser::parse_long_option( const char * const opt, const char * const arg,
                                    const Option options[], int & argind )
  {
  unsigned int len;
  int index = -1;
  bool exact = false, ambig = false;

  for( len = 0; opt[len+2] && opt[len+2] != '='; ++len ) ;

  // Test all long options for either exact match or abbreviated matches.
  for( int i = 0; options[i].code != 0; ++i )
    if( options[i].name && !std::strncmp( options[i].name, &opt[2], len ) )
      {
      if( std::strlen( options[i].name ) == len )	// Exact match found
        { index = i; exact = true; break; }
      else if( index < 0 ) index = i;		// First nonexact match found
      else if( options[index].code != options[i].code ||
               options[index].has_arg != options[i].has_arg )
        ambig = true;			// Second or later nonexact match found
      }

  if( ambig && !exact )
    {
    error_ = "option `"; error_ += opt; error_ += "' is ambiguous";
    return false;
    }

  if( index < 0 )		// nothing found
    {
    error_ = "unrecognized option `"; error_ += opt; error_ += '\'';
    return false;
    }

  ++argind;
  data.push_back( Record( options[index].code ) );

  if( opt[len+2] )		// `--<long_option>=<argument>' syntax
    {
    if( options[index].has_arg == no )
      {
      error_ = "option `--"; error_ += options[index].name;
      error_ += "' doesn't allow an argument";
      return false;
      }
    if( options[index].has_arg == yes && !opt[len+3] )
      {
      error_ = "option `--"; error_ += options[index].name;
      error_ += "' requires an argument";
      return false;
      }
    data.back().argument = &opt[len+3];
    return true;
    }

  if( options[index].has_arg == yes )
    {
    if( !arg || !arg[0] )
      {
      error_ = "option `--"; error_ += options[index].name;
      error_ += "' requires an argument";
      return false;
      }
    ++argind; data.back().argument = arg;
    return true;
    }

  return true;
  }
Esempio n. 28
0
namespace db {

const char* COLUMN_NAME_EXTRA_ID = D_COLUMN_NAME_EXTRA_ID;
const char* COLUMN_NAME_TIMESTAMP = D_COLUMN_NAME_TIMESTAMP;
const char* COLUMN_NAME_DATETIME = D_COLUMN_NAME_DATETIME;
const char* COLUMN_NAME_IP_ADDRESS = D_COLUMN_NAME_IP_ADDRESS;
const char* COLUMN_NAME_PORT = D_COLUMN_NAME_PORT;

Record Record::EMPTY = Record(0, 0, "", 0);

Record::Record(ID_t extra_id, uint64_t timestamp, const std::string& ip_address, int port)
  : m_extra_id(extra_id)
  , m_timestamp(timestamp)
  , m_date_time("")
  , m_ip_address(ip_address)
  , m_port(port) {

  std::time_t end_time = static_cast<time_t>(timestamp / 1000);
  m_date_time = std::string(std::ctime(&end_time));
  int i1 = m_date_time.find_last_of('\n');
  m_date_time = m_date_time.substr(0, i1);
}

SystemTable::SystemTable()
  : Database(TABLE_NAME) {
  INF("enter SystemTable constructor.");
  this->__init__();
  INF("exit SystemTable constructor.");
}

SystemTable::SystemTable(SystemTable&& rval_obj)
  : Database(std::move(static_cast<Database&>(rval_obj))) {
}

SystemTable::~SystemTable() {
  INF("enter SystemTable destructor.");
  this->__close_database__();
  INF("exit SystemTable destructor.");
}

// ----------------------------------------------
ID_t SystemTable::addRecord(const Record& record) {
  INF("enter SystemTable::addRecord().");
  std::string insert_statement = "INSERT INTO '";
  insert_statement += this->m_table_name;
  insert_statement += "' VALUES(?1, ?2, ?3, ?4, ?5, ?6);";
  this->__prepare_statement__(insert_statement);

  bool accumulate = true;
  ID_t record_id = this->m_next_id++;
  accumulate = accumulate && (sqlite3_bind_int64(this->m_db_statement, 1, record_id) == SQLITE_OK);
  DBG("ID [%lli] has been stored in table ["%s"], SQLite database ["%s"].",
      record_id, this->m_table_name.c_str(), this->m_db_name.c_str());

  ID_t extra_id = record.getExtraId();
  accumulate = accumulate && (sqlite3_bind_int64(this->m_db_statement, 2, extra_id) == SQLITE_OK);
  DBG("Extra ID [%lli] has been stored in table ["%s"], SQLite database ["%s"].",
      extra_id, this->m_table_name.c_str(), this->m_db_name.c_str());

  uint64_t i_timestamp = record.getTimestamp();
  accumulate = accumulate && (sqlite3_bind_int64(this->m_db_statement, 3, i_timestamp) == SQLITE_OK);
  DBG("Timestamp [%lu] has been stored in table ["%s"], SQLite database ["%s"].",
      i_timestamp, this->m_table_name.c_str(), this->m_db_name.c_str());

  WrappedString i_datetime = WrappedString(record.getDateTime());
  int datetime_n_bytes = i_datetime.n_bytes();
  accumulate = accumulate && (sqlite3_bind_text(this->m_db_statement, 4, i_datetime.c_str(), datetime_n_bytes, SQLITE_TRANSIENT) == SQLITE_OK);
  DBG("Date-Time ["%s"] has been stored in table ["%s"], SQLite database ["%s"].",
      i_datetime.c_str(), this->m_table_name.c_str(), this->m_db_name.c_str());

  WrappedString i_ipaddress = WrappedString(record.getIpAddress());
  int ipaddress_n_bytes = i_ipaddress.n_bytes();
  accumulate = accumulate && (sqlite3_bind_text(this->m_db_statement, 5, i_ipaddress.c_str(), ipaddress_n_bytes, SQLITE_TRANSIENT) == SQLITE_OK);
  DBG("IP Address ["%s"] has been stored in table ["%s"], SQLite database ["%s"].",
      i_ipaddress.c_str(), this->m_table_name.c_str(), this->m_db_name.c_str());

  int i_port = record.getPort();
  accumulate = accumulate && (sqlite3_bind_int(this->m_db_statement, 6, i_port) == SQLITE_OK);
  DBG("Port [%i] has been stored in table ["%s"], SQLite database ["%s"].",
      i_port, this->m_table_name.c_str(), this->m_db_name.c_str());

  sqlite3_step(this->m_db_statement);
  if (!accumulate) {
    ERR("Error during saving data into table ["%s"], database ["%s"] by statement ["%s"]!",
        this->m_table_name.c_str(), this->m_db_name.c_str(), insert_statement.c_str());
    this->__finalize_and_throw__(insert_statement.c_str(), SQLITE_ACCUMULATED_PREPARE_ERROR);
  } else {
    DBG("All insertions have succeeded.");
  }

  this->__finalize__(insert_statement.c_str());
  this->__increment_rows__();
  INF("exit SystemTable::addRecord().");
  return record_id;
}

// ----------------------------------------------
void SystemTable::removeRecord(ID_t id) {
  INF("enter SystemTable::removeRecord().");
  std::string delete_statement = "DELETE FROM '";
  delete_statement += this->m_table_name;
  delete_statement += "' WHERE ID == '";
  delete_statement += std::to_string(id);
  delete_statement += "';";
  this->__prepare_statement__(delete_statement);
  sqlite3_step(this->m_db_statement);
  this->__finalize__(delete_statement.c_str());
  this->__decrement_rows__();
  if (id + 1 == this->m_next_id) {
    ID_t last_row_id = this->__read_last_id__(this->m_table_name);
    this->m_next_id = last_row_id + 1;
    DBG("Deleted record with largest ID. Next ID value is set to [%lli].", this->m_next_id);
  }
  if (this->__empty__()) {
    DBG("Table ["%s"] has become empty. Next ID value is set to zero.", this->m_table_name.c_str());
    this->m_next_id = BASE_ID;
  }
  DBG("Deleted record [ID: %lli] in table ["%s"].",  id, this->m_table_name.c_str());
  INF("exit SystemTable::removeRecord().");
}

// ----------------------------------------------
Record SystemTable::getRecord(ID_t i_record_id) {
  INF("enter SystemTable::getRecord().");
  std::string select_statement = "SELECT * FROM '";
  select_statement += this->m_table_name;
  select_statement += "' WHERE ID == '";
  select_statement += std::to_string(i_record_id);
  select_statement += "';";

  this->__prepare_statement__(select_statement);
  sqlite3_step(this->m_db_statement);
  ID_t id = sqlite3_column_int64(this->m_db_statement, 0);
  DBG("Read id [%lli] from  table ["%s"] of database ["%s"], input id was [%lli].",
      id, this->m_table_name.c_str(), this->m_db_name.c_str(), i_record_id);
  TABLE_ASSERT("Input record id does not equal to primary key value from database!" && id == i_record_id);

  Record record = Record::EMPTY;
  if (i_record_id != UNKNOWN_ID) {
    DBG("Read id [%lli] from  table ["%s"] of database ["%s"].",
        id, this->m_table_name.c_str(), this->m_db_name.c_str());

    ID_t extra_id = sqlite3_column_int64(this->m_db_statement, 1);
    uint64_t timestamp = sqlite3_column_int64(this->m_db_statement, 2);
    const void* raw_datetime = reinterpret_cast<const char*>(sqlite3_column_text(this->m_db_statement, 3));
    WrappedString datetime(raw_datetime);
    const void* raw_ipaddress = reinterpret_cast<const char*>(sqlite3_column_text(this->m_db_statement, 4));
    WrappedString ipaddress(raw_ipaddress);
    int port = sqlite3_column_int(this->m_db_statement, 5);

    DBG("Loaded column data: " COLUMN_NAME_EXTRA_ID " [%lli]; " D_COLUMN_NAME_TIMESTAMP " [%lu]; " D_COLUMN_NAME_DATETIME " ["%s"]; " D_COLUMN_NAME_IP_ADDRESS " ["%s"]; " D_COLUMN_NAME_PORT " [%i].",
         extra_id, timestamp, datetime.c_str(), ipaddress.c_str(), port);
    record = Record(extra_id, timestamp, ipaddress.get(), port);
    DBG("Proper record instance has been constructed.");
  } else {
    WRN("ID [%lli] is missing in table ["%s"] of database %p!",
        i_record_id, this->m_table_name.c_str(), this->m_db_handler);
  }

  this->__finalize__(select_statement.c_str());
  INF("exit SystemTable::getRecord().");
  return (record);
}

/* Private members */
// ----------------------------------------------------------------------------
void SystemTable::__init__() {
  DBG("enter SystemTable::__init__().");
  Database::__init__();
  ID_t last_row_id = this->__read_last_id__(this->m_table_name);
  this->m_next_id = last_row_id == 0 ? BASE_ID : last_row_id + 1;
  TRC("Initialization has completed: total rows [%i], last row id [%lli], next_id [%lli].",
      this->m_rows, last_row_id, this->m_next_id);
  DBG("exit SystemTable::__init__().");
}

void SystemTable::__create_table__() {
  DBG("enter SystemTable::__create_table__().");
  std::string statement = "CREATE TABLE IF NOT EXISTS ";
  statement += this->m_table_name;
  statement += "('ID' INTEGER PRIMARY KEY UNIQUE DEFAULT " STR_UNKNOWN_ID ", "
      "'" D_COLUMN_NAME_EXTRA_ID "' INTEGER, "
      "'" D_COLUMN_NAME_TIMESTAMP "' INTEGER, "
      "'" D_COLUMN_NAME_DATETIME "' TEXT, "
      "'" D_COLUMN_NAME_IP_ADDRESS "' TEXT, "
      "'" D_COLUMN_NAME_PORT "' INTEGER);";
  this->__prepare_statement__(statement);
  sqlite3_step(this->m_db_statement);
  DBG("Table ["%s"] has been successfully created.", this->m_table_name.c_str());
  this->__finalize__(statement.c_str());
  DBG("exit SystemTable::__create_table__().");
}

}
Esempio n. 29
0
 static inline void Warning(Event event, Args&& ...args) {
     Record(EventSeverity::Warning, event, ::std::forward<Args>(args)...);
 }
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// The Call back from a MIDI Input Message.  Your job here is to figure out what
// to do in the the host based on which param called you back, and what its
// value is.
HRESULT	CSampleSurface::OnMIDIMessageDelivered( CMidiMsg* pObj, float fValue )
{
	bool bMatch = false;
	InputBindingIterator it = m_mapStripContinuous.find( pObj );
	if ( m_mapStripContinuous.end() != it )
	{
		bMatch = true;
		PMBINDING& pmb = it->second;
		pmb.pParam->SetVal( fValue );
	}

	if ( !bMatch )
	{
		// Look in the strip trigger map
		it = m_mapStripTrigger.find( pObj );
		if ( m_mapStripTrigger.end() != it )
		{
			bMatch = true;
			PMBINDING& pmb = it->second;
			pmb.pParam->ToggleBooleanParam();
		}
	}

	if ( !bMatch )
	{
		// No match, try the Fader Touch switches
		it = m_mapFaderTouch.find( pObj );
		if ( m_mapFaderTouch.end() != it )
		{
			PMBINDING& pmb = it->second;
			pmb.pParam->Touch( fValue > .1f );
		}
	}
	if ( !bMatch )
	{
		if ( m_setBankSwitches.count( pObj ) > 0 )
		{
			bMatch = true;

			StripRangeMapIterator it = m_mapStripRanges.find( MIX_STRIP_TRACK );
			if ( it != m_mapStripRanges.end() )
			{
				STRIPRANGE& sr = it->second;
				int nTrackOrg = (int)sr.dwL;

				// track bank switches?	// opt: put these in a map to quickly narrow them down?
				if ( pObj == m_pmsgBankL )
					nTrackOrg -= 8;
				else if ( pObj == m_pmsgBankR )
					nTrackOrg += 8;
				else if ( pObj == m_pmsgTrkL )
					nTrackOrg -= 1;
				else if ( pObj == m_pmsgTrkR )
					nTrackOrg += 1;

				nTrackOrg = min( (int)(GetStripCount( MIX_STRIP_TRACK ) - 8), nTrackOrg );
				nTrackOrg = max( 0, nTrackOrg );

				updateParamBindings();
				SetHostContextSwitch();
			}
		}
		if ( !bMatch )
		{
			if ( m_setTransportSwitches.count( pObj ) > 0 )
			{
				bMatch = true;
				if ( pObj == m_pmsgPlay )
				{
					Play( true );
				}
				else if ( pObj == m_pmsgStop )
				{
					Stop();
				}
				else if ( pObj == m_pmsgRec )
				{
					Record( true );
				}
			}
		}
	}

	return S_OK;
}