void MongoShell::handle(ExecuteQueryResponse *event) { AppRegistry::instance().bus()->publish(new DocumentListLoadedEvent(this, event->resultIndex, event->queryInfo, query(), event->documents)); }
void notifyChange(const VarT & v) { for (auto & l : query(varsListeners, &v)) l->updateValue(); }
CLASS_D("tianlongsi") + "/benxiang" : 1, CLASS_D("tianlongsi") + "/bencan" : 1, CLASS_D("tianlongsi") + "/benyin" : 1, ])); setup(); } void init() { add_action("do_quit", "quit"); add_action("do_quit", "exit"); } string long() { if (mapp(query("exits"))) return query("long"); return query("long") + " 现在室内剑气纵横,你来" "我往,杀个不停。\n"; } int do_quit() { object me; me = this_player(); if (! mapp(query("exits"))) { write("现在没有出路,你无法离开。\n"); return 1;
/*! * \brief Insert file details into database. * If it is an audio file, read the metadata and insert * that information at the same time. * * If it is an image file, just insert the filename and * type. * * \param filename Full path to file. * * \returns Nothing. */ void FileScanner::AddFileToDB(const QString &filename) { QString extension = filename.section( '.', -1 ) ; QString directory = filename; directory.remove(0, m_startdir.length()); directory = directory.section( '/', 0, -2); QString nameFilter = gCoreContext->GetSetting("AlbumArtFilter", "*.png;*.jpg;*.jpeg;*.gif;*.bmp"); // If this file is an image, insert the details into the music_albumart table if (nameFilter.indexOf(extension.toLower()) > -1) { QString name = filename.section( '/', -1); MSqlQuery query(MSqlQuery::InitCon()); query.prepare("INSERT INTO music_albumart SET filename = :FILE, " "directory_id = :DIRID, imagetype = :TYPE;"); query.bindValue(":FILE", name); query.bindValue(":DIRID", m_directoryid[ QString(directory.toUtf8()).toLower()]); query.bindValue(":TYPE", AlbumArtImages::guessImageType(name)); if (!query.exec() || query.numRowsAffected() <= 0) { MythDB::DBError("music insert artwork", query); } return; } Decoder *decoder = Decoder::create(filename, NULL, NULL, true); if (decoder) { VERBOSE(VB_FILE, QString("Reading metadata from %1").arg(filename)); Metadata *data = decoder->readMetadata(); if (data) { QString album_cache_string; // Set values from cache int did = m_directoryid[QString(directory.toUtf8()).toLower()]; if (did > 0) data->setDirectoryId(did); int aid = m_artistid[QString(data->Artist().toUtf8()).toLower()]; if (aid > 0) { data->setArtistId(aid); // The album cache depends on the artist id album_cache_string = data->getArtistId() + "#" + QString(data->Album().toUtf8()).toLower(); if (m_albumid[album_cache_string] > 0) data->setAlbumId(m_albumid[album_cache_string]); } int gid = m_genreid[QString(data->Genre().toUtf8()).toLower()]; if (gid > 0) data->setGenreId(gid); // Commit track info to database data->dumpToDatabase(); // Update the cache m_artistid[QString(data->Artist().toUtf8()).toLower()] = data->getArtistId(); m_genreid[QString(data->Genre().toUtf8()).toLower()] = data->getGenreId(); album_cache_string = data->getArtistId() + "#" + QString(data->Album().toUtf8()).toLower(); m_albumid[album_cache_string] = data->getAlbumId(); delete data; } delete decoder; } }
/*! * \brief Check a list of files against musics files already in the database * * \param music_files MusicLoadedMap * * \returns Nothing. */ void FileScanner::ScanMusic(MusicLoadedMap &music_files) { MusicLoadedMap::Iterator iter; MSqlQuery query(MSqlQuery::InitCon()); if (!query.exec("SELECT CONCAT_WS('/', path, filename), date_modified " "FROM music_songs LEFT JOIN music_directories ON " "music_songs.directory_id=music_directories.directory_id " "WHERE filename NOT LIKE ('%://%')")) MythDB::DBError("FileScanner::ScanMusic", query); uint counter = 0; MythScreenStack *popupStack = GetMythMainWindow()->GetStack("popup stack"); QString message = QObject::tr("Scanning music files"); MythUIProgressDialog *file_checking = new MythUIProgressDialog(message, popupStack, "scalingprogressdialog"); if (file_checking->Create()) { popupStack->AddScreen(file_checking, false); file_checking->SetTotal(query.size()); } else { delete file_checking; file_checking = NULL; } QString name; if (query.isActive() && query.size() > 0) { while (query.next()) { name = m_startdir + query.value(0).toString(); if (name != QString::null) { if ((iter = music_files.find(name)) != music_files.end()) { if (music_files[name] == kDatabase) { file_checking->SetProgress(++counter); continue; } else if (HasFileChanged(name, query.value(1).toString())) music_files[name] = kNeedUpdate; else music_files.erase(iter); } else { music_files[name] = kDatabase; } } file_checking->SetProgress(++counter); } } file_checking->Close(); }
QTSS_Error EasyRecordList(Easy_RecordList_Params* inParams) { EasyRecordQuery query(EasyRecordSession::sLocalRecordPath, inParams->inStreamName); query.List(inParams->inBeginTime, inParams->inEndTime, inParams->outRecords); return QTSS_NoErr; }
bool ChatLogger::init(QString jid) { Utilities::logData("Initializing logger for " + jid); this->jid = jid; QDir home = QDir::home(); QFile file(home.path() + LOGS_DIR + jid.left(jid.indexOf("@")) + LOG_EXTENSION); bool logAvailable = file.exists(); // Initialization of databases db = QSqlDatabase::addDatabase("QSQLITE",jid); db.setDatabaseName(file.fileName()); if (!db.open()) return false; if (!logAvailable) { QSqlQuery query(db); query.exec("create table log (" "localid integer primary key autoincrement," "name varchar(256)," "from_me boolean," "timestamp integer not null," "id varchar(20) not null," "type integer not null," "data varchar(65535)," "thumb_image varchar(256)," "status integer not null," "media_url varchar(256)," "media_mime_type varchar(20)," "media_wa_type integer," "media_size integer," "media_name varchar(256)," "media_duration_seconds integer," "local_file_uri varchar(512)," "live boolean," "latitude real," "longitude real," "media_caption varchar(160)," "msg_count integer," "msg_delivered varchar(8192)," "msg_read varchar(8192)" ")"); query.exec("create table settings (" "version integer" ")"); query.exec("insert into settings (version) values (" + QString::number(LOG_VERSION) + ")"); lastId = -1; } else { QSqlQuery query(db); // Check the DB is the current version query.prepare("select version from settings"); query.exec(); if (query.next()) { int version = query.value(0).toInt(); if (version == 1) { // Upgrade it to version 2 Utilities::logData("Upgrading log " + jid + " to version 2"); query.prepare("alter table log add column local_file_uri varchar(512)"); query.exec(); query.prepare("update settings set version=2"); query.exec(); version = 2; query.prepare("update settings set version="+ QString::number(version)); query.exec(); } if (version == 2) { // Upgrade it to version 3 Utilities::logData("Upgrading log " + jid + " to version " + QString::number(LOG_VERSION)); query.prepare("alter table log add column live boolean"); query.exec(); query.prepare("alter table log add column latitude real"); query.exec(); query.prepare("alter table log add column longitude real"); query.exec(); version = 3; query.prepare("update settings set version="+ QString::number(version)); query.exec(); } if (version == 3) { // Upgrade it to version 4 Utilities::logData("Upgrading log " + jid + " to version " + QString::number(LOG_VERSION)); query.prepare("alter table log add column media_caption varchar(160)"); query.exec(); version = LOG_VERSION; query.prepare("update settings set version="+ QString::number(version)); query.exec(); } if (version == 4) { // Upgrade it to version 5 Utilities::logData("Upgrading log " + jid + " to version " + QString::number(LOG_VERSION)); query.prepare("alter table log add column msg_count integer"); query.exec(); query.prepare("alter table log add column msg_delivered varchar(8192)"); query.exec(); query.prepare("alter table log add column msg_read varchar(8192)"); query.exec(); version = 5; query.prepare("update settings set version="+ QString::number(version)); query.exec(); } } query.exec("select max(localid) from log"); query.next(); lastId = query.value(0).toInt() + 1; } Utilities::logData("Logger for " + jid + " initialized successfully. LastId: " + QString::number(lastId)); return true; }
//-------------------------------------------------------------------------------- Server::Server(std::size_t io_service_pool_size, const std::string& application_id, const std::string& application_instance, bool runAsDaemon /*= true*/, const std::string& config_root_path /*= ""*/, const std::string& address /*= "get_from_config"*/, const std::string& port /*= "get_from_config"*/) : io_service_pool_ (io_service_pool_size), stop_signals_ (io_service_pool_.get_io_service()), log_reopen_signals_(io_service_pool_.get_io_service()), acceptor_ (io_service_pool_.get_io_service()), new_connection_ (), request_router_ () { if (createLockFile(application_id, application_instance)) { std::cerr << "Lock file created for: [" << application_id << "] [" << application_instance << "]" << std::endl; if(runAsDaemon) { std::cerr << "Running as Daemon." << std::endl; becomeDaemonProcess(); } signalRegistrations(); std::cerr << "Signal registration completed." << std::endl; Config::instance(application_id, application_instance, config_root_path); std::cerr << "Configuration instance created." << std::endl; initializeLogging((!runAsDaemon)); std::cerr << "Initialized Logging." << std::endl; // create the stats keeper instance here. So that it's available as soon as the server is constructed. StatsKeeper::instance(Config::instance()->get<unsigned long int>("kcc-stats.gather-period" ,300), Config::instance()->get<unsigned long int>("kcc-stats.history-length",12)); std::cerr << "Initialized StatsKeeper." << std::endl; ErrorStateList::instance(); // same goes for the error state list. std::cerr << "Initialized ErrorStateList." << std::endl; initialize_standard_handlers(); std::cerr << "Initialized Standard Handlers." << std::endl; boost::asio::ip::tcp::resolver resolver(acceptor_.get_io_service()); // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR). std::cerr << "Initialized resolver." << std::endl; boost::asio::ip::tcp::resolver::query query(Config::instance()->get<std::string>("kcc-server.address"), Config::instance()->get<std::string>("kcc-server.port")); std::cerr << "Initialized query object." << std::endl; boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query); std::cerr << "Initialized endpoint." << std::endl; acceptor_.open(endpoint.protocol()); std::cerr << "Acceptor opened." << std::endl; acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); std::cerr << "Acceptor options set." << std::endl; acceptor_.bind(endpoint); std::cerr << "Acceptor bound." << std::endl; acceptor_.listen(); std::cerr << "Server started, now accepting connections." << std::endl; start_accept(); std::cerr << "Server Ready." << std::endl; } else { std::cerr << "Could not create Lockfile for this appid and instance: [" << lockFilePath.native() << "]" << std::endl << "If this message is not preceded by a message indicating that a lock file already exists, " << "you most likely have a permissions problem, or the directory in which you wish to create lock files, " << "does not exist." << std::endl; throw std::runtime_error("Could not create lock file: Terminating."); } }
void test_query(){ cs_init(); char * dummy1 = "one_is_1"; char * dummy2 = "two_is_2"; char * dummy3 = "three_is_3"; char * dummy4 = "four_is_4"; char * dummy5 = "five_is_5"; add_message(dummy1); add_message(dummy2); add_message(dummy3); add_message(dummy4); add_message(dummy5); printf("Query (7,8):\n"); UnityAssertEqualNumber((_U_SINT)((0)), (_U_SINT)((query(7,8))), (((void *)0)), (_U_UINT)88, UNITY_DISPLAY_STYLE_INT); printf("\nQuery (1,3):\n"); UnityAssertEqualNumber((_U_SINT)((1)), (_U_SINT)((query(1,3))), (((void *)0)), (_U_UINT)91, UNITY_DISPLAY_STYLE_INT); printf("\nQuery (4,5):\n"); UnityAssertEqualNumber((_U_SINT)((1)), (_U_SINT)((query(4,5))), (((void *)0)), (_U_UINT)94, UNITY_DISPLAY_STYLE_INT); printf("\nQuery (2,6):\n"); UnityAssertEqualNumber((_U_SINT)((1)), (_U_SINT)((query(2,6))), (((void *)0)), (_U_UINT)97, UNITY_DISPLAY_STYLE_INT); printf("\nQuery (1,1000):"); UnityAssertEqualNumber((_U_SINT)((1)), (_U_SINT)((query(1,1000))), (((void *)0)), (_U_UINT)100, UNITY_DISPLAY_STYLE_INT); }
bool InitDriveThread::method_resizePartitions() { int newStartOfRescuePartition = getFileContents("/sys/class/block/mmcblk0p1/start").trimmed().toInt(); int newSizeOfRescuePartition = sizeofBootFilesInKB()/1000 + 100; if (!umountSystemPartition()) { emit error(tr("Error unmounting system partition.")); return false; } if (!QFile::exists("/dev/mmcblk0p1")) { // SD card does not have a MBR. // Warn user that their SD card does not have an MBR and ask // if they would like us to create one for them QMessageBox::StandardButton answer; emit query(tr("Would you like NOOBS to create one for you?\nWARNING: This will erase all data on your SD card"), tr("Error: No MBR present on SD Card"), &answer); if(answer == QMessageBox::Yes) { emit statusUpdate(tr("Zeroing partition table")); if (!zeroMbr()) { emit error(tr("Error zero'ing MBR/GPT. SD card may be broken or advertising wrong capacity.")); return false; } // Create MBR containing single FAT partition emit statusUpdate(tr("Writing new MBR")); QProcess proc; proc.setProcessChannelMode(proc.MergedChannels); proc.start("/usr/sbin/parted /dev/mmcblk0 --script -- mktable msdos mkpartfs primary fat32 8192s -1"); proc.waitForFinished(-1); if (proc.exitCode() != 0) { // Warn user if we failed to create an MBR on their card emit error(tr("Error creating MBR")+"\n"+proc.readAll()); return false; } qDebug() << "Created missing MBR on SD card. parted output:" << proc.readAll(); // Advise user that their SD card has now been formatted // suitably for installing NOOBS and that they will have to // re-copy the files before rebooting emit error(tr("SD card has now been formatted ready for NOOBS installation. Please re-copy the NOOBS files onto the card and reboot")); return false; } else { emit error(tr("SD card has not been formatted correctly. Please reformat using the SD Association Formatting Tool and try again.")); return false; } } emit statusUpdate(tr("Removing partitions 2,3,4")); QFile f("/dev/mmcblk0"); f.open(f.ReadWrite); // Seek to partition entry 2 f.seek(462); // Zero out partition 2,3,4 to prevent parted complaining about invalid constraints f.write(QByteArray(16*3, '\0')); f.flush(); // Tell Linux to re-read the partition table ioctl(f.handle(), BLKRRPART); f.close(); QThread::msleep(500); emit statusUpdate(tr("Resizing FAT partition")); /* Relocating the start of the FAT partition is a write intensive operation * only move it when it is not aligned on a MiB boundary already */ if (newStartOfRescuePartition < 2048 || newStartOfRescuePartition % 2048 != 0) { newStartOfRescuePartition = 8192; /* 4 MiB */ } QString cmd = "/usr/sbin/parted --script /dev/mmcblk0 resize 1 "+QString::number(newStartOfRescuePartition)+"s "+QString::number(newSizeOfRescuePartition)+"M"; qDebug() << "Executing" << cmd; QProcess p; p.setProcessChannelMode(p.MergedChannels); p.start(cmd); p.closeWriteChannel(); p.waitForFinished(-1); if (p.exitCode() != 0) { emit error(tr("Error resizing existing FAT partition")+"\n"+p.readAll()); return false; } qDebug() << "parted done, output:" << p.readAll(); QThread::msleep(500); emit statusUpdate(tr("Creating extended partition")); mbr_table extended_mbr; QByteArray partitionTable; int startOfOurPartition = getFileContents("/sys/class/block/mmcblk0p1/start").trimmed().toInt(); int sizeOfOurPartition = getFileContents("/sys/class/block/mmcblk0p1/size").trimmed().toInt(); int startOfExtended = startOfOurPartition+sizeOfOurPartition; // Align on 4 MiB boundary startOfExtended += 8192-(startOfExtended % 8192); int sizeOfDisk = getFileContents("/sys/class/block/mmcblk0/size").trimmed().toULongLong(); int sizeOfExtended = sizeOfDisk - startOfExtended - SETTINGS_PARTITION_SIZE ; int startOfSettings = startOfExtended+sizeOfExtended; partitionTable = QByteArray::number(startOfOurPartition)+","+QByteArray::number(sizeOfOurPartition)+",0E\n"; /* FAT partition */ partitionTable += QByteArray::number(startOfExtended)+","+QByteArray::number(sizeOfExtended)+",X\n"; /* Extended partition with all remaining space */ partitionTable += QByteArray::number(startOfSettings)+",,L\n"; /* Settings partition */ partitionTable += "0,0\n"; qDebug() << "Writing partition table" << partitionTable; /* Write out empty extended partition table with signature */ memset(&extended_mbr, 0, sizeof extended_mbr); extended_mbr.signature[0] = 0x55; extended_mbr.signature[1] = 0xAA; f.open(f.ReadWrite); f.seek(startOfExtended*512); f.write((char *) &extended_mbr, sizeof(extended_mbr)); f.close(); /* Let sfdisk write a proper partition table */ cmd = QString("/sbin/sfdisk -uS /dev/mmcblk0"); QProcess proc; proc.setProcessChannelMode(proc.MergedChannels); proc.start(cmd); proc.write(partitionTable); proc.closeWriteChannel(); proc.waitForFinished(-1); if (proc.exitCode() != 0) { emit error(tr("Error creating extended partition")+"\n"+proc.readAll()); return false; } qDebug() << "sfdisk done, output:" << proc.readAll(); QThread::msleep(500); /* For reasons unknown Linux sometimes * only finds /dev/mmcblk0p2 and /dev/mmcblk0p1 goes missing */ if (!QFile::exists("/dev/mmcblk0p1")) { /* Probe again */ QProcess::execute("/usr/sbin/partprobe"); QThread::msleep(1500); } QProcess::execute("/sbin/mlabel p:RECOVERY"); emit statusUpdate(tr("Mounting FAT partition")); if (!mountSystemPartition()) { emit error(tr("Error mounting system partition.")); return false; } return true; }
bool PersistentStore::init() { QMutexLocker locker(&_mutex); // Get application data directory and database filename. QSettings settings; QString appdata = settings.value("app/app_data").toString(); if(appdata.isEmpty()) { DEBUG << "Error creating the PersistentStore: app.appdata not set."; return false; } bool create = false; QString dbUrl(appdata + QDir::separator() + DEFAULT_DBNAME); QFileInfo dbFileInfo(dbUrl); // Initialize database object. _db = _db.addDatabase("QSQLITE", "tarsnap"); _db.setConnectOptions("QSQLITE_OPEN_URI"); _db.setDatabaseName(dbUrl); // Determine whether to try to open the database. if(!dbFileInfo.exists()) { create = true; } else if(!dbFileInfo.isFile() || !dbFileInfo.isReadable()) { DEBUG << "Error creating the PersistentStore: DB file is not accessible " << dbUrl; return false; } // Database file exists and is readable; attempt to open. else if(!_db.open()) { DEBUG << "Error opening the PersistentStore DB: " << _db.lastError().text(); return false; } else { // Successfully opened database. QStringList tables = _db.tables(); // Is the database valid? if(!tables.contains("archives", Qt::CaseInsensitive)) { _db.close(); DEBUG << "Invalid PersistentStore DB found. Attempting to recover."; QString newName(dbUrl + "." + QString::number(QDateTime::currentMSecsSinceEpoch())); if(!QFile::rename(dbUrl, newName)) { DEBUG << "Failed to rename current invalid PersistentStore DB. " "Please manually clean up the DB directory " << appdata; return false; } create = true; } else { // Check the database version, and upgrade if necessary. if(!tables.contains("version", Qt::CaseInsensitive)) { if(!upgradeVersion0()) { DEBUG << "Failed to upgrade PersistentStore DB. It's best " "to start from scratch by purging the existing DB " "in " << appdata; return false; } } int version = -1; QSqlQuery query(_db); if(query.exec("SELECT version FROM version")) { query.next(); version = query.value(0).toInt(); } else { DEBUG << "Failed to get current DB version: " << query.lastError().text(); return false; } if((version == 0) && upgradeVersion1()) { DEBUG << "DB upgraded to version 1."; version = 1; } if((version == 1) && upgradeVersion2()) { DEBUG << "DB upgraded to version 2."; version = 2; } if((version == 2) && upgradeVersion3()) { DEBUG << "DB upgraded to version 3."; version = 3; } if((version == 3) && upgradeVersion4()) { DEBUG << "DB upgraded to version 4."; version = 4; } } } // Create new database (if needed). if(create) { QFile dbTemplate(":/dbtemplate.db"); if(!dbTemplate.copy(dbUrl)) { DEBUG << "Failed to create the PersistentStore DB."; return false; } // Work around the fact that QFile::copy from the resource system does // not set u+w on the resulted file QFile dbFile(dbUrl); dbFile.setPermissions(dbFile.permissions() | QFileDevice::WriteOwner); dbFile.close(); if(!_db.open()) { DEBUG << "Error opening the PersistentStore DB: " << _db.lastError().text(); return false; } } return _initialized = true; }
int main (int argc, char **argv) { // variables SDL_Surface *screen; // pantalla SDL_Event event; // para los eventos de SDL (teclado y/o mouse) Uint8 *keystates = SDL_GetKeyState(NULL); // para detectar teclas mantenidas presionadas Uint8 salir = 0; // para determinar cuando se cierra la ventana int mouse_x=0, mouse_y=0; // coordenadas del mouse char info1[100]; // texto para mostrar informacion variada linea 1 char info2[100]; // texto para mostrar informacion variada linea 2 short int time; // variable para la hora short int ticks; // variable para mover elementos independiente de los FPS // cargar configuracion struct conf *conf = conf_load(); if (!conf) return EXIT_FAILURE; // verificar a donde nos queremos conectar // se indicó el servidor como 1er parametro if(argc>=2) { free(conf->SERVER); conf->SERVER = malloc(strlen(argv[1])); strcpy(conf->SERVER, argv[1]); } // se indicó el puerto como 2do parametro if(argc>=3) { conf->PORT = atoi(argv[2]); } // conectar al servidor int connection = client_init(conf); if (!connection) return EXIT_FAILURE; // buffer para transferencia entre servidor y cliente char buffer[BUFFER_SIZE]; // obtener id del jugador int playerID = atoi(query("get;id", connection)); // recibir y actualizar configuraciones desde el servidor conf_update(conf, query("get;conf", connection)); // inicializar sistema sdl_init(&screen); // cargar fuente TTF_Font *fuente = ttf_load(FONT_NAME, FONT_SIZE, FONT_STYLE); // cargar todos los posibles objetos de un mapa MapObject *mapobjects = mapobjects_load(screen); if (!mapobjects) return EXIT_FAILURE; // cargar mapa char **map = map_open(conf->MAP); if (!map) return EXIT_FAILURE; // cargar armas Weapon *weapons = weapons_load(); if (!weapons) return EXIT_FAILURE; // crear personaje jugador Player *pj = player_create(playerID, conf->PLAYER_NAME, conf->PLAYER_CHARACTER, screen, weapons, conf); // asignar armas al personaje player_change_weapon(&pj, conf->WEAPON_PRIMARY, 1); player_change_weapon(&pj, conf->WEAPON_SECONDARY, 2); // ubicar personaje en el mapa player_set_position(&pj, map, -1, -1, mapobjects); // informar estado del usuario bzero(buffer, sizeof(buffer)); sprintf(buffer, "info;%s;%s", conf->PLAYER_CHARACTER, conf->PLAYER_NAME); write(connection, buffer, strlen(buffer)); // crear bots y ubicar en el mapa Player *bots = bots_create(screen, weapons, conf); int i; for(i=0; i<conf->BOTS; ++i) { Player *aux = &bots[i]; player_set_position(&aux, map, -1, -1, mapobjects); } // guardar ticks ticks = SDL_GetTicks(); // ciclo infinito para refrescar la imagen de la pantalla while (!salir) { // solicitar informacion de todos los jugadores (menos el mio) char *enemies = query("get;players", connection); // enviar posicion del jugador al servidor sprintf(buffer, "position;%d;%d", (int)(pj->y), (int)(pj->x)); write(connection, buffer, strlen(buffer)); // time time = SDL_GetTicks()/1000; // dibujar mapa map_draw(screen, map, mapobjects, conf->BACKGROUND); // revisar si existen eventos de SDL while (SDL_PollEvent(&event)) { // salir del programa if(event.type==SDL_QUIT) salir = 1; // si se presiona una tecla else if(event.type==SDL_KEYDOWN) { // cambiar a pantalla completa if(event.key.keysym.sym==SDLK_f) SDL_WM_ToggleFullScreen(screen); // salir del juego else if(event.key.keysym.sym==SDLK_ESCAPE) salir = 1; // cambiar arma primaria else if(event.key.keysym.sym>=48&&event.key.keysym.sym<=57) player_change_weapon(&pj, event.key.keysym.sym-48, 1); } // si se mueve el mouse else if(event.type==SDL_MOUSEMOTION) { // guardar coordenadas del mouse mouse_x = event.motion.x; mouse_y = event.motion.y; } // si se presiona el mouse else if(event.type == SDL_MOUSEBUTTONDOWN ) { // guardar coordenadas del mouse mouse_x = event.button.x; mouse_y = event.button.y; // resetear flag de armas disparadas pj->primary->fired = 0; pj->secondary->fired = 0; // si se presiono el boton izquierdo if(event.button.button==SDL_BUTTON_LEFT && pj->primary->ammo) { Mix_PlayChannel(-1, pj->primary->sound, 0); pj->primary->fired = pj->primary->ammo--; } // si se presiono el boton derecho else if(event.button.button==SDL_BUTTON_RIGHT && pj->secondary->ammo) { Mix_PlayChannel(-1, pj->secondary->sound, 0); pj->secondary->fired = pj->secondary->ammo--; } // si se mueve el scroll se cambia el arma principal else if (event.button.button==SDL_BUTTON_WHEELUP) { player_change_weapon(&pj, WEAPON_PREV, 1); } else if (event.button.button==SDL_BUTTON_WHEELDOWN) { player_change_weapon(&pj, WEAPON_NEXT, 1); } // determinar si personaje fue herido if(mouse_x >= pj->x && mouse_x <= pj->x+SPRITE_SIZE && mouse_y >= pj->y && mouse_y <= pj->y+SPRITE_SIZE) { // hacer daño al personaje if(event.button.button==SDL_BUTTON_LEFT && pj->primary->fired) { pj->health -= pj->primary->damage; // reproducir sonido de dolor Mix_PlayChannel(-1, pj->sounds[PLAYER_SOUND_DAMAGED], 0); } else if(event.button.button==SDL_BUTTON_RIGHT && pj->secondary->fired) { pj->health -= pj->secondary->damage; // reproducir sonido de dolor Mix_PlayChannel(-1, pj->sounds[PLAYER_SOUND_DAMAGED], 0); } // si la salud quedo menor o igual a 0 el personaje muere if(pj->health<1) { // incrementar contador de muerte ++pj->dead; pj->health = conf->PLAYER_HEALTH; // descontar vida if(conf->PLAYER_LIFE!=0) { --pj->life; if(pj->life==0) { // GAME OVER } } // reposicionar personaje muerto player_set_position(&pj, map, -1, -1, mapobjects); } } } // si se suelta el mouse else if(event.type==SDL_MOUSEBUTTONUP) { // guardar coordenadas del mouse mouse_x = event.button.x; mouse_y = event.button.y; // si se solto el boton izquierdo if(event.button.button==SDL_BUTTON_LEFT) { } // si se solto el boton derecho else if(event.button.button==SDL_BUTTON_RIGHT) { } } } // mover jugador player_move(&pj, keystates, map, mapobjects, conf, SDL_GetTicks()-ticks); player_get_object(&pj, map, conf); // primera linea informacion sprintf(info1, "time: %02d:%02d, mouse: (%04d,%04d)", time/60, time%60, mouse_x, mouse_y); SDL_Surface *s_info1 = TTF_RenderText_Blended(fuente, info1, (SDL_Color) {255,255,255,255}); SDL_Rect rect = (SDL_Rect) { 10, 0, 100, 20 }; SDL_BlitSurface(s_info1, NULL, screen, &rect); SDL_FreeSurface(s_info1); // segunda linea informacion sprintf(info2, "[%s] +%03d, life: %02d, dead: %02d, weapon: [%d/%03d/%03d] [%d/%03d/%03d]", conf->PLAYER_NAME, pj->health, pj->life, pj->dead, pj->primary->id, pj->primary->damage, pj->primary->ammo, pj->secondary->id, pj->secondary->damage, pj->secondary->ammo); SDL_Surface *s_info2 = TTF_RenderText_Blended(fuente, info2, (SDL_Color) {255,255,255,255}); rect.y += 12; SDL_BlitSurface(s_info2, NULL, screen, &rect); SDL_FreeSurface(s_info2); // dibujar enemigos enemies_draw(screen, enemies); // dibujar bots /*for(i=0; i<conf->BOTS; ++i) { Player *aux = &bots[i]; SDL_BlitSurface(aux->images[PLAYER_IMAGE_SPRITE], &aux->src, screen, &aux->sprite); }*/ // dibujar jugador SDL_BlitSurface(pj->images[PLAYER_IMAGE_SPRITE], &pj->src, screen, &pj->sprite); // actualizar screen sdl SDL_Flip(screen); SDL_Delay(1000/FPS); // resetear ticks ticks = SDL_GetTicks(); } // cerrar conexion al servidor close(connection); // liberar jugador player_free(&pj); // liberar armas weapons_free(&weapons); // libear objetos del mapa mapobjects_free(&mapobjects); // cerrar fuentes TTF_CloseFont(fuente); TTF_Quit(); // cerrar SDL SDL_FreeSurface(screen); SDL_Quit(); // retorno del sistema return EXIT_SUCCESS; }
int vehicle::automatic_fire_turret( vehicle_part &pt ) { auto gun = turret_query( pt ); if( gun.query() != turret_data::status::ready ) { return 0; } tripoint pos = global_part_pos3( pt ); npc tmp; tmp.set_fake( true ); tmp.name = rmp_format( _( "<veh_player>The %s" ), pt.name().c_str() ); tmp.set_skill_level( gun.base()->gun_skill(), 8 ); tmp.set_skill_level( skill_id( "gun" ), 4 ); tmp.recoil = abs( velocity ) / 100 / 4; tmp.setpos( pos ); tmp.str_cur = 16; tmp.dex_cur = 8; tmp.per_cur = 12; // Assume vehicle turrets are friendly to the player. tmp.attitude = NPCATT_FOLLOW; int area = aoe_size( gun.ammo_effects() ); if( area > 0 ) { area += area == 1 ? 1 : 2; // Pad a bit for less friendly fire } tripoint targ = pos; auto &target = pt.target; if( target.first == target.second ) { // Manual target not set, find one automatically const bool u_see = g->u.sees( pos ); int boo_hoo; // @todo calculate chance to hit and cap range based upon this int range = std::min( gun.range(), 12 ); Creature *auto_target = tmp.auto_find_hostile_target( range, boo_hoo, area ); if( auto_target == nullptr ) { if( u_see && boo_hoo ) { add_msg( m_warning, ngettext( "%s points in your direction and emits an IFF warning beep.", "%s points in your direction and emits %d annoyed sounding beeps.", boo_hoo ), tmp.name.c_str(), boo_hoo ); } return 0; } targ = auto_target->pos(); } else if( target.first != target.second ) { // Target set manually // Make sure we didn't move between aiming and firing (it's a bug if we did) if( targ != target.first ) { target.second = target.first; return 0; } targ = target.second; // Remove the target target.second = target.first; } else { // Shouldn't happen target.first = target.second; return 0; } auto shots = gun.fire( tmp, targ ); if( g->u.sees( pos ) && shots ) { add_msg( _( "The %1$s fires its %2$s!" ), name.c_str(), pt.name().c_str() ); } return shots; }
bool ok (int *c, int *s, int p1, int p2){ while (last < p2-p1) modify (c, s[last++], -1); return p1 != m && query (c, s[p2]-1) == low[p1] && query (c, s[p2]) == eq[p1]; }
void CepController::add(Cep cep) { QSqlDatabase db = DBUtil::getDatabase(); QSqlQuery query(db); QString cidade = cep.getCidade().getNome(); QString bairro = cep.getBairro().getNome(); QString endereco = cep.getEndereco().getNome(); QString estado = cep.getEstado().getUF(); int cepint = cep.getCep(); query.prepare("insert into cidade (nome) VALUES (:nome)"); query.bindValue(":nome", cidade); int cidade_id = 0; if(!query.exec()){ query.prepare("select id from cidade where nome = :nome"); query.bindValue(":nome", cidade); query.exec(); query.next(); cidade_id = query.value(0).toInt(); }else{ cidade_id = query.lastInsertId().toInt(); } int bairro_id = 0; query.prepare("insert into bairro (nome) VALUES (:nome)"); query.bindValue(":nome", bairro); if(!query.exec()){ query.prepare("select id from bairro where nome = :nome"); query.bindValue(":nome", bairro); query.exec(); query.next(); bairro_id = query.value(0).toInt(); }else{ bairro_id = query.lastInsertId().toInt(); } int endereco_id = 0; query.prepare("insert into endereco (nome) VALUES (:nome)"); query.bindValue(":nome", endereco); if(!query.exec()){ query.prepare("select id from endereco where nome = :nome"); query.bindValue(":nome", endereco); query.exec(); query.next(); endereco_id = query.value(0).toInt(); }else{ endereco_id = query.lastInsertId().toInt(); } query.prepare("insert into cep (endereco_id,bairro_id,cidade_id,estado_uf,cep) VALUES (:endereco_id,:bairro_id,:cidade_id,:estado_uf,:cep)"); query.bindValue(":endereco_id", endereco_id); query.bindValue(":bairro_id", bairro_id); query.bindValue(":cidade_id", cidade_id); query.bindValue(":estado_uf", estado); query.bindValue(":cep", cepint); if( !query.exec() ) { qDebug() << query.lastError().text(); } }
void MusicSearchEngine::watchForChanges() { // Gather all folders registered on music locations QFileInfoList dirs; for (QString musicPath : SettingsPrivate::instance()->musicLocations()) { QFileInfo location(musicPath); QDirIterator it(location.absoluteFilePath(), QDir::Dirs | QDir::Hidden | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); while (it.hasNext()) { QString entry = it.next(); QFileInfo qFileInfo(entry); dirs << qFileInfo; } } SqlDatabase *db = SqlDatabase::instance(); db->open(); db->exec("PRAGMA journal_mode = MEMORY"); db->exec("PRAGMA synchronous = OFF"); db->exec("PRAGMA temp_store = 2"); db->exec("PRAGMA foreign_keys = 1"); QStringList newFoldersToAddInLibrary; // Add folders that were not found first for (QFileInfo f : dirs) { QSqlQuery query(*db); query.setForwardOnly(true); query.prepare("SELECT * FROM filesystem WHERE path = ?"); query.addBindValue(f.absoluteFilePath()); if (query.exec() && !query.next()) { newFoldersToAddInLibrary << f.absoluteFilePath(); QSqlQuery prepared(*db); prepared.setForwardOnly(true); prepared.prepare("INSERT INTO filesystem (path, lastModified) VALUES (?, ?)"); prepared.addBindValue(f.absoluteFilePath()); prepared.addBindValue(f.lastModified().toTime_t()); prepared.exec(); } } if (!newFoldersToAddInLibrary.isEmpty()) { this->doSearch(newFoldersToAddInLibrary); } // Process in reverse mode to clean cache: from database file and check if entry exists in database QSqlQuery cache("SELECT * FROM filesystem", *db); qDebug() << Q_FUNC_INFO << "SELECT * FROM filesystem"; cache.setForwardOnly(true); if (cache.exec()) { QStringList oldLocations; while (cache.next()) { QDir d(cache.record().value(0).toString()); d.exists(); QFileInfo fileInfo(cache.record().value(0).toString()); // Remove folder in database because it couldn't be find in the filesystem if (!fileInfo.exists()) { QSqlQuery deleteFromFilesystem(*db); deleteFromFilesystem.prepare("DELETE FROM filesystem WHERE path = ?"); deleteFromFilesystem.addBindValue(fileInfo.absoluteFilePath()); qDebug() << Q_FUNC_INFO << "DELETE FROM filesystem WHERE path = ?"; if (deleteFromFilesystem.exec()) { oldLocations << fileInfo.absoluteFilePath(); } } } qDebug() << Q_FUNC_INFO << oldLocations; if (!oldLocations.isEmpty()) { db->rebuild(oldLocations, QStringList()); } } }
void CustomPriority::testSchedule(void) { MythUIButtonListItem *item = m_prioritySpin->GetItemCurrent(); if (!item) return; QString ttable = "powerpriority_tmp"; MSqlQueryInfo dbcon = MSqlQuery::SchedCon(); MSqlQuery query(dbcon); QString thequery; thequery = "SELECT GET_LOCK(:LOCK, 2);"; query.prepare(thequery); query.bindValue(":LOCK", "DiffSchedule"); if (!query.exec()) { QString msg = QString("DB Error (Obtaining lock in testRecording): \n" "Query was: %1 \nError was: %2 \n") .arg(thequery) .arg(MythDB::DBErrorMessage(query.lastError())); LOG(VB_GENERAL, LOG_ERR, msg); return; } thequery = QString("DROP TABLE IF EXISTS %1;").arg(ttable); query.prepare(thequery); if (!query.exec()) { QString msg = QString("DB Error (deleting old table in testRecording): \n" "Query was: %1 \nError was: %2 \n") .arg(thequery) .arg(MythDB::DBErrorMessage(query.lastError())); LOG(VB_GENERAL, LOG_ERR, msg); return; } thequery = QString("CREATE TABLE %1 SELECT * FROM powerpriority;") .arg(ttable); query.prepare(thequery); if (!query.exec()) { QString msg = QString("DB Error (create new table): \n" "Query was: %1 \nError was: %2 \n") .arg(thequery) .arg(MythDB::DBErrorMessage(query.lastError())); LOG(VB_GENERAL, LOG_ERR, msg); return; } query.prepare(QString("DELETE FROM %1 WHERE priorityname = :NAME;") .arg(ttable)); query.bindValue(":NAME", m_titleEdit->GetText()); if (!query.exec()) MythDB::DBError("Test power search delete", query); thequery = QString("INSERT INTO %1 " "(priorityname, recpriority, selectclause) " "VALUES(:NAME,:VALUE,:CLAUSE);").arg(ttable); query.prepare(thequery); query.bindValue(":NAME", m_titleEdit->GetText()); query.bindValue(":VALUE", item->GetText()); query.bindValue(":CLAUSE", m_descriptionEdit->GetText()); if (!query.exec()) MythDB::DBError("Test power search insert", query); QString ltitle = tr("Power Priority"); if (!m_titleEdit->GetText().isEmpty()) ltitle = m_titleEdit->GetText(); MythScreenStack *mainStack = GetMythMainWindow()->GetMainStack(); ViewScheduleDiff *vsd = new ViewScheduleDiff(mainStack, ttable, 0, ltitle); if (vsd->Create()) mainStack->AddScreen(vsd); else delete vsd; thequery = "SELECT RELEASE_LOCK(:LOCK);"; query.prepare(thequery); query.bindValue(":LOCK", "DiffSchedule"); if (!query.exec()) { QString msg = QString("DB Error (free lock): \n" "Query was: %1 \nError was: %2 \n") .arg(thequery) .arg(MythDB::DBErrorMessage(query.lastError())); LOG(VB_GENERAL, LOG_ERR, msg); } }
int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Insufficient number of arguments." << std::endl; usage(argv[0]); return 1; } try { namespace asio = boost::asio; std::string server_addr = argv[1]; std::string server_port = argv[2]; std::cout << "Connecting to " << server_addr << " on port " << server_port << std::endl; asio::io_service io_service; asio::ip::tcp::resolver resolver(io_service); asio::ip::tcp::resolver::query query(server_addr, server_port); asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); asio::ip::tcp::socket socket(io_service); boost::asio::connect(socket, endpoint_iterator); std::ostringstream oss; for (;;) { boost::array<char, 1024> buf; boost::system::error_code error; const std::size_t len = socket.read_some(boost::asio::buffer(buf), error); if (error == boost::asio::error::eof) { break; // Connection closed cleanly by peer. } else if (error) { throw boost::system::system_error(error); // Some other error. } oss << std::string(buf.data(), len); //std::cout.write(buf.data(), len); } socket.close(); if (oss.str().empty()) { std::cout << "Nothing received" << std::endl; } else { boost::uint32_t sz; std::string meminfo; boost::tie(sz, meminfo) = unpack(oss.str().c_str()); std::cerr << "MEMINFO: " << meminfo << std::endl; Json::Value root; // will contains the root value after parsing Json::Reader reader; bool parse_ok = reader.parse(meminfo, root); if (!parse_ok) { std::cerr << "Failed to parse configuration: " << reader.getFormattedErrorMessages() << std::endl; return 1; } long double mem_tot = 0; long double mem_avail = 0; std::istringstream iss; iss.str(root.get("MemTotal", "").asString()); iss >> mem_tot; iss.str(root.get("MemAvailable", "").asString()); iss >> mem_avail; std::cout << "MEMINFO => Tot: " << mem_tot << " kB, Avail: " << mem_avail << " kB" << std::endl; } } catch (std::exception const& e) { std::cerr << e.what() << std::endl; return 1; } }
QSet<int> DirectoryDAO::relocateDirectory(const QString& oldFolder, const QString& newFolder) { // TODO(rryan): This method could use error reporting. It can fail in // mysterious ways for example if a track in the oldFolder also has a zombie // track location in newFolder then the replace query will fail because the // location column becomes non-unique. ScopedTransaction transaction(m_database); QSqlQuery query(m_database); query.prepare("UPDATE " % DIRECTORYDAO_TABLE % " SET " % DIRECTORYDAO_DIR % "=:newFolder WHERE " % DIRECTORYDAO_DIR % " = :oldFolder"); query.bindValue(":newFolder", newFolder); query.bindValue(":oldFolder", oldFolder); if (!query.exec()) { LOG_FAILED_QUERY(query) << "could not relocate directory" << oldFolder << "to" << newFolder; return QSet<int>(); } FieldEscaper escaper(m_database); // on Windows the absolute path starts with the drive name // we also need to check for that QString startsWithOldFolder = escaper.escapeStringForLike( QDir(oldFolder).absolutePath() + "/", '%') + "%"; // Also update information in the track_locations table. This is where mixxx // gets the location information for a track. Put marks around %1 so that // this also works on windows query.prepare(QString("SELECT library.id, track_locations.id, track_locations.location " "FROM library INNER JOIN track_locations ON " "track_locations.id = library.location WHERE " "track_locations.location LIKE '%1' ESCAPE '%'") .arg(startsWithOldFolder)); if (!query.exec()) { LOG_FAILED_QUERY(query) << "could not relocate path of tracks"; return QSet<int>(); } QSet<int> ids; QList<int> loc_ids; QStringList old_locs; while (query.next()) { ids.insert(query.value(0).toInt()); loc_ids.append(query.value(1).toInt()); old_locs.append(query.value(2).toString()); } QString replacement = "UPDATE track_locations SET location = :newloc " "WHERE id = :id"; query.prepare(replacement); for (int i = 0; i < loc_ids.size(); ++i) { QString newloc = old_locs.at(i); newloc.replace(0, oldFolder.size(), newFolder); query.bindValue("newloc", newloc); query.bindValue("id", loc_ids.at(i)); if (!query.exec()) { LOG_FAILED_QUERY(query) << "could not relocate path of tracks"; return QSet<int>(); } } qDebug() << "Relocated tracks:" << ids.size(); transaction.commit(); return ids; }
void SqlEditor::actionRun_as_Script_triggered() { if ((!creator) || !(creator->checkForPending())) { return; } SqlQueryModel * model = 0; bool rebuildTree = false; bool updateTable = false; m_scriptCancelled = false; toSQLParse::editorTokenizer tokens(ui.sqlTextEdit); int cpos, cline; ui.sqlTextEdit->getCursorPosition(&cline, &cpos); QProgressDialog * dialog = new QProgressDialog(tr("Executing all statements"), tr("Cancel"), 0, ui.sqlTextEdit->lines(), this); connect(dialog, SIGNAL(canceled()), this, SLOT(scriptCancelled())); int line; int pos; bool ignore = true; QSqlQuery query(QSqlDatabase::database(SESSION_NAME)); QString sql; bool isError = false; emit sqlScriptStart(); emit showSqlScriptResult("-- " + tr("Script started")); do { line = tokens.line(); pos = tokens.offset(); dialog->setValue(line); qApp->processEvents(); if (m_scriptCancelled) break; toSQLParse::parseStatement(tokens); if (ignore && (tokens.line() > cline || (tokens.line() == cline && tokens.offset() >= cpos))) { ignore = false; cline = line; cpos = pos; } if (tokens.line() < ui.sqlTextEdit->lines() && !ignore) { sql = prepareExec(tokens, line, pos); emit showSqlScriptResult(sql); SqlQueryModel * mdl = new SqlQueryModel(creator); mdl->setQuery(sql, QSqlDatabase::database(SESSION_NAME)); appendHistory(sql); if (mdl->lastError().isValid()) { emit showSqlScriptResult( "-- " + tr("Error: %1.").arg(mdl->lastError().text())); int com = QMessageBox::question(this, tr("Run as Script"), tr("This script contains the following error:\n") + mdl->lastError().text() + tr("\nAt line: %1").arg(line), QMessageBox::Ignore, QMessageBox::Abort); if (com == QMessageBox::Abort) { scriptCancelled(); isError = true; break; } } else { if (Utils::updateObjectTree(sql)) { rebuildTree = true; } if (Utils::updateTables(sql)) { updateTable = true; } emit showSqlScriptResult("-- " + tr("No error")); if (mdl->rowCount() > 0) { model = mdl; } else delete mdl; } emit showSqlScriptResult("--"); } } while (tokens.line() < ui.sqlTextEdit->lines()); delete dialog; ui.sqlTextEdit->setSelection(cline, cpos, tokens.line(), tokens.offset()); if (!isError) emit showSqlScriptResult("-- " + tr("Script finished")); if (rebuildTree) { emit buildTree(); } if (updateTable) { emit refreshTable(); } if (model) { creator->setTableModel(model); } creator->buildPragmasTree(); }
cv::Mat CBIR::getClustersIndices(QString path){ QString imgName = path.section('/', -1); IplImage* img = Utils::loadImage(path.toAscii().data(), true); if(img == NULL){ qDebug() << "La imagen no fue cargada."; exit(1); } //Computo los features. CvSeq *imgKeypoints, *imgDescriptors; CvSURFParams params = cvSURFParams(500, 1); imgKeypoints = 0; imgDescriptors = 0; CvMemStorage* storage = cvCreateMemStorage(0); cvExtractSURF(img, 0, &imgKeypoints, &imgDescriptors, storage, params); qDebug() << "Imagen" << path << "cargada con exito. Features:" << imgKeypoints->total; //Copio los descriptores a una Mat. cv::Mat queryDescriptorsMat(imgDescriptors->total, DESCRIPTOR_DIMS, CV_32F); float* img_ptr = queryDescriptorsMat.ptr<float>(0); CvSeqReader img_reader; cvStartReadSeq(imgDescriptors, &img_reader); for(int j=0; j<imgDescriptors->total; j++){ const float* descriptor = (const float*)img_reader.ptr; CV_NEXT_SEQ_ELEM(img_reader.seq->elem_size, img_reader); memcpy(img_ptr, descriptor, DESCRIPTOR_DIMS*sizeof(float)); img_ptr += DESCRIPTOR_DIMS; } cvReleaseMemStorage(&storage); cvReleaseImage(&img); if(clustersMat.data == NULL) exit(1); //Creo el índice para los cluster centers. cv::flann::KDTreeIndexParams kdtiParams = cv::flann::KDTreeIndexParams(8); cv::flann::Index clustersIndex(clustersMat, kdtiParams); //Clusterizo cada feature de la query según Knn-Search. cv::Mat indices(queryDescriptorsMat.rows, 1, CV_32S); cv::Mat dists(queryDescriptorsMat.rows, 1, CV_32F); clustersIndex.knnSearch(queryDescriptorsMat, indices, dists, 1, cv::flann::SearchParams(1024)); /***************************************************************************************************************/ //Guardo el archivo para realizar la query al índice. QFile query("cbir/lemur/query/" + imgName + ".query"); QTextStream stream(&query); if (!query.open(QIODevice::WriteOnly | QIODevice::Text)) qDebug() << "Ocurrio un error al intentar abrir el archivo" + imgName + ".query"; stream << "<DOC 1>" << endl; // Itero sobre todos los features de la imagen. for(int i=0; i<queryDescriptorsMat.rows ;i++){ stream << indices.at<int>(i, 0) << endl; } stream << "</DOC>"; query.close(); //Guardo el archivo con los parámetros de la query. QFile qP("cbir/lemur/query/query_params"); QTextStream qPStream(&qP); if (!qP.open(QIODevice::WriteOnly | QIODevice::Text)) qDebug() << "Ocurrio un error al intentar abrir el archivo query_params"; qPStream << "<parameters>" << endl << "<index>e:\\Proyectos\\Git\\keepc\\release\\cbir\\lemur\\index\\index.key</index>" << endl << "<retModel>tfidf</retModel>" << endl << "<textQuery>e:\\Proyectos\\Git\\keepc\\release\\cbir\\lemur\\query\\" << imgName << ".query</textQuery>" << endl << "<resultFile>e:\\Proyectos\\Git\\keepc\\release\\cbir\\lemur\\query\\" << imgName << ".results</resultFile>" << endl << "<TRECResultFormat>1</TRECResultFormat>" << endl << "<resultCount>10</resultCount>" << endl << "</parameters>"; qP.close(); return indices; }
void SqlEditor::actionCreateView_triggered() { emit showSqlScriptResult(""); creator->createViewFromSql(query()); }
/*! * \brief Clear orphaned entries from the genre, artist, album and albumart * tables * * \returns Nothing. */ void FileScanner::cleanDB() { MythScreenStack *popupStack = GetMythMainWindow()->GetStack("popup stack"); QString message = QObject::tr("Cleaning music database"); MythUIProgressDialog *clean_progress = new MythUIProgressDialog(message, popupStack, "cleaningprogressdialog"); if (clean_progress->Create()) { popupStack->AddScreen(clean_progress, false); clean_progress->SetTotal(4); } else { delete clean_progress; clean_progress = NULL; } uint counter = 0; MSqlQuery query(MSqlQuery::InitCon()); MSqlQuery deletequery(MSqlQuery::InitCon()); if (!query.exec("SELECT g.genre_id FROM music_genres g " "LEFT JOIN music_songs s ON g.genre_id=s.genre_id " "WHERE s.genre_id IS NULL;")) MythDB::DBError("FileScanner::cleanDB - select music_genres", query); while (query.next()) { int genreid = query.value(0).toInt(); deletequery.prepare("DELETE FROM music_genres WHERE genre_id=:GENREID"); deletequery.bindValue(":GENREID", genreid); if (!deletequery.exec()) MythDB::DBError("FileScanner::cleanDB - delete music_genres", deletequery); } if (clean_progress) clean_progress->SetProgress(++counter); if (!query.exec("SELECT a.album_id FROM music_albums a " "LEFT JOIN music_songs s ON a.album_id=s.album_id " "WHERE s.album_id IS NULL;")) MythDB::DBError("FileScanner::cleanDB - select music_albums", query); while (query.next()) { int albumid = query.value(0).toInt(); deletequery.prepare("DELETE FROM music_albums WHERE album_id=:ALBUMID"); deletequery.bindValue(":ALBUMID", albumid); if (!deletequery.exec()) MythDB::DBError("FileScanner::cleanDB - delete music_albums", deletequery); } if (clean_progress) clean_progress->SetProgress(++counter); if (!query.exec("SELECT a.artist_id FROM music_artists a " "LEFT JOIN music_songs s ON a.artist_id=s.artist_id " "LEFT JOIN music_albums l ON a.artist_id=l.artist_id " "WHERE s.artist_id IS NULL AND l.artist_id IS NULL")) MythDB::DBError("FileScanner::cleanDB - select music_artists", query); while (query.next()) { int artistid = query.value(0).toInt(); deletequery.prepare("DELETE FROM music_artists WHERE artist_id=:ARTISTID"); deletequery.bindValue(":ARTISTID", artistid); if (!deletequery.exec()) MythDB::DBError("FileScanner::cleanDB - delete music_artists", deletequery); } if (clean_progress) clean_progress->SetProgress(++counter); if (!query.exec("SELECT a.albumart_id FROM music_albumart a LEFT JOIN " "music_songs s ON a.song_id=s.song_id WHERE " "embedded='1' AND s.song_id IS NULL;")) MythDB::DBError("FileScanner::cleanDB - select music_albumart", query); while (query.next()) { int albumartid = query.value(0).toInt(); deletequery.prepare("DELETE FROM music_albumart WHERE albumart_id=:ALBUMARTID"); deletequery.bindValue(":ALBUMARTID", albumartid); if (!deletequery.exec()) MythDB::DBError("FileScanner::cleanDB - delete music_albumart", deletequery); } if (clean_progress) { clean_progress->SetProgress(++counter); clean_progress->Close(); } }
void DiscreteVariableRecord_Impl::saveRow(ProjectDatabase& projectDatabase) { QSqlQuery query(*(projectDatabase.qSqlDatabase())); this->makeUpdateByIdQuery<DiscreteVariableRecord>(query); this->bindValues(query); assertExec(query); }
/*! * \brief Check a list of files against images already in the database * * \param music_files MusicLoadedMap * * \returns Nothing. */ void FileScanner::ScanArtwork(MusicLoadedMap &music_files) { MusicLoadedMap::Iterator iter; MSqlQuery query(MSqlQuery::InitCon()); if (!query.exec("SELECT CONCAT_WS('/', path, filename) " "FROM music_albumart LEFT JOIN music_directories ON " "music_albumart.directory_id=music_directories.directory_id" " WHERE music_albumart.embedded=0")) MythDB::DBError("FileScanner::ScanArtwork", query); uint counter = 0; MythScreenStack *popupStack = GetMythMainWindow()->GetStack("popup stack"); QString message = QObject::tr("Scanning Album Artwork"); MythUIProgressDialog *file_checking = new MythUIProgressDialog(message, popupStack, "albumprogressdialog"); if (file_checking->Create()) { popupStack->AddScreen(file_checking, false); file_checking->SetTotal(query.size()); } else { delete file_checking; file_checking = NULL; } if (query.isActive() && query.size() > 0) { while (query.next()) { QString name; name = m_startdir + query.value(0).toString(); if (name != QString::null) { if ((iter = music_files.find(name)) != music_files.end()) { if (music_files[name] == kDatabase) { if (file_checking) file_checking->SetProgress(++counter); continue; } else music_files.erase(iter); } else { music_files[name] = kDatabase; } } if (file_checking) file_checking->SetProgress(++counter); } } if (file_checking) file_checking->Close(); }
QFileInfo Content::GetAlbumArt( int nId, int nWidth, int nHeight ) { QString sFullFileName; // ---------------------------------------------------------------------- // Read AlbumArt file path from database // ---------------------------------------------------------------------- MSqlQuery query(MSqlQuery::InitCon()); query.prepare("SELECT CONCAT_WS('/', music_directories.path, " "music_albumart.filename) FROM music_albumart " "LEFT JOIN music_directories ON " "music_directories.directory_id=music_albumart.directory_id " "WHERE music_albumart.albumart_id = :ARTID;"); query.bindValue(":ARTID", nId ); if (!query.exec()) MythDB::DBError("Select ArtId", query); QString sMusicBasePath = gCoreContext->GetSetting("MusicLocation", ""); if (query.next()) { sFullFileName = QString( "%1/%2" ) .arg( sMusicBasePath ) .arg( query.value(0).toString() ); } if (!QFile::exists( sFullFileName )) return QFileInfo(); if ((nWidth == 0) && (nHeight == 0)) return QFileInfo( sFullFileName ); QString sNewFileName = QString( "%1.%2x%3.png" ) .arg( sFullFileName ) .arg( nWidth ) .arg( nHeight ); // ---------------------------------------------------------------------- // check to see if albumart image is already created. // ---------------------------------------------------------------------- if (QFile::exists( sNewFileName )) return QFileInfo( sNewFileName ); // ---------------------------------------------------------------------- // Must generate Albumart Image, Generate Image and save. // ---------------------------------------------------------------------- float fAspect = 0.0; QImage *pImage = new QImage( sFullFileName); if (!pImage) return QFileInfo(); if (fAspect <= 0) fAspect = (float)(pImage->width()) / pImage->height(); if ( nWidth == 0 ) nWidth = (int)rint(nHeight * fAspect); if ( nHeight == 0 ) nHeight = (int)rint(nWidth / fAspect); QImage img = pImage->scaled( nWidth, nHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); QByteArray fname = sNewFileName.toAscii(); img.save( fname.constData(), "PNG" ); delete pImage; return QFileInfo( sNewFileName ); }
void Setup::enter() { QDir dir; dir.mkdir(QDir::homePath() + "/.booker"); QByteArray pwOffice = this->pwOffice->text().toLatin1(); QByteArray pwMaster = this->pwMaster->text().toLatin1(); QByteArray pwEncryption = this->pwEncryption->text().toLatin1(); Cryptor cryptor(pwOffice+pwOffice); QString dbHost = this->dbHost->text(); QString dbDatabase = this->dbDatabase->text(); QString dbUsername = this->dbUsername->text(); QString dbPassword = this->dbPassword->text(); QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL","test"); db.setHostName(dbHost); db.setDatabaseName(dbDatabase); db.setUserName(dbUsername); db.setPassword(dbPassword); db.open(); if(pwMasterCheck->isChecked()) { QSqlQuery query(db); QString sql = ""; sql += "INSERT INTO connectiontest (`passwordfor`,`password`) VALUES ('master',:master);"; query.prepare(sql); query.bindValue(":master",pwMaster); query.exec(); query.clear(); } else { QSqlQuery query(db); query.prepare("SELECT * FROM connectiontest WHERE passwordfor LIKE 'encryption' OR passwordfor LIKE 'master'"); query.exec(); while(query.next()) if(query.value(query.record().indexOf("passwordfor")).toByteArray() == "master") pwMaster = cryptor.decrypt(query.value(query.record().indexOf("password")).toByteArray()).data(); query.clear(); } QFile cryptPwFile(QDir::homePath() + "/.booker/cryptPassword"); if(!cryptPwFile.open(QIODevice::WriteOnly)) { QMessageBox::critical(this,"Failed file saving","ERROR! Can't save encryption password! Quitting..."); this->reject(); return; } QTextStream outPw(&cryptPwFile); outPw << cryptor.encrypt(pwEncryption).join("\n"); cryptPwFile.close(); QFile dbfile(QDir::homePath() + "/.booker/db"); if(!dbfile.open(QIODevice::WriteOnly)) { QMessageBox::critical(this,"Failed file saving","ERROR! Can't save database connection details! Quitting..."); this->reject(); return; } QTextStream outDb(&dbfile); outDb << cryptor.encrypt(QString("host=%1\ndb=%2\nuname=%3\npw=%4") .arg(dbHost) .arg(dbDatabase) .arg(dbUsername) .arg(dbPassword).toLatin1()).join("\n"); dbfile.close(); QFile cryptCredentials(QDir::homePath() + "/.booker/officePassword"); if(!cryptCredentials.open(QIODevice::WriteOnly)) { QMessageBox::critical(this,"Failed file saving","ERROR! Can't save office password! Quitting..."); this->reject(); return; } QTextStream outCred(&cryptCredentials); outCred << cryptor.encrypt(pwOffice).join("\n"); cryptCredentials.close(); this->accept(); }
Cep CepController::getByCep(int cepnumber) { QSqlDatabase db = DBUtil::getDatabase(); QSqlQuery query(db); QString sql = "select es.nome as estado,es.uf as uf,e.nome as endereco"; sql.append(",e.id as endereco_id,c.cep as cep,b.nome as bairro,b.id as bairro_id,"); sql.append("ci.nome as cidade, ci.id as cidade_id from endereco e,cep c,bairro b,cidade ci,"); sql.append("estado es where cep = :cep and c.endereco_id=e.id and c.bairro_id=b.id "); sql.append("and ci.id=c.cidade_id and es.uf=c.estado_uf limit 1"); query.prepare(sql); query.bindValue(":cep",cepnumber); Cep cep; if( !query.exec()) { qDebug() << query.lastError().text(); return cep; } int fieldEndereco = query.record().indexOf("endereco"); int fieldEndereco_id = query.record().indexOf("endereco_id"); int fieldCep = query.record().indexOf("cep"); int fieldBairro = query.record().indexOf("bairro"); int fieldBairro_id = query.record().indexOf("bairro_id"); int fieldCidade = query.record().indexOf("cidade"); int fieldCidade_id = query.record().indexOf("cidade_id"); int fieldEstado_uf = query.record().indexOf("uf"); int fieldEstado = query.record().indexOf("estado"); Cidade cidade; Estado estado; Bairro bairro; Endereco endereco; query.next(); if (!query.isValid()) return cep; cep.setCep(query.value(fieldCep).toInt()); cidade.setId(query.value(fieldCidade_id).toInt()); cidade.setNome(query.value(fieldCidade).toString()); cep.setCidade(cidade); estado.setUF(query.value(fieldEstado_uf).toString()); estado.setNome(query.value(fieldEstado).toString()); cep.setEstado(estado); bairro.setId(query.value(fieldBairro_id).toInt()); bairro.setNome(query.value(fieldBairro).toString()); cep.setBairro(bairro); endereco.setId(query.value(fieldEndereco_id).toInt()); endereco.setNome(query.value(fieldEndereco).toString()); cep.setEndereco(endereco); return cep; }
/** * @param start, end: Indices * @return: The sum from start to end */ long long query(int start, int end) { return query(root, start, end); }
int main(int argc, char *argv[]) { int c; char *raw_name; char *block_name; int retval; int block_major, block_minor; int i, rc; struct stat statbuf; static const struct option longopts[] = { {"query", no_argument, 0, 'q'}, {"all", no_argument, 0, 'a'}, {"version", no_argument, 0, 'V'}, {"help", no_argument, 0, 'h'}, {NULL, no_argument, 0, '0'}, }; setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); atexit(close_stdout); while ((c = getopt_long(argc, argv, "qaVh", longopts, NULL)) != -1) switch (c) { case 'q': do_query = 1; break; case 'a': do_query_all = 1; break; case 'V': printf(UTIL_LINUX_VERSION); return EXIT_SUCCESS; case 'h': usage(EXIT_SUCCESS); default: usage(EXIT_FAILURE); } /* * Check for, and open, the master raw device, /dev/raw */ open_raw_ctl(); if (do_query_all) { if (optind < argc) usage(EXIT_FAILURE); for (i = 1; i < RAW_NR_MINORS; i++) query(i, NULL, 1); exit(EXIT_SUCCESS); } /* * It's a bind or a single query. Either way we need a raw device. */ if (optind >= argc) usage(EXIT_FAILURE); raw_name = argv[optind++]; /* * try to check the device name before stat(), because on systems with * udev the raw0 causes a create udev event for char 162/0, which * causes udev to *remove* /dev/rawctl */ rc = sscanf(raw_name, _PATH_RAWDEVDIR "raw%d", &raw_minor); if (rc != 1) usage(EXIT_FAILURE); if (raw_minor == 0) errx(EXIT_RAW_ACCESS, _("Device '%s' is the control raw device " "(use raw<N> where <N> is greater than zero)"), raw_name); if (do_query) return query(raw_minor, raw_name, 0); /* * It's not a query, so we still have some parsing to do. Have we been * given a block device filename or a major/minor pair? */ switch (argc - optind) { case 1: block_name = argv[optind]; retval = stat(block_name, &statbuf); if (retval) err(EXIT_RAW_ACCESS, _("Cannot locate block device '%s'"), block_name); if (!S_ISBLK(statbuf.st_mode)) errx(EXIT_RAW_ACCESS, _("Device '%s' is not a block device"), block_name); block_major = major(statbuf.st_rdev); block_minor = minor(statbuf.st_rdev); break; case 2: block_major = strtol_octal_or_err(argv[optind], _("failed to parse argument")); block_minor = strtol_octal_or_err(argv[optind + 1], _("failed to parse argument")); break; default: usage(EXIT_FAILURE); } return bind(raw_minor, block_major, block_minor); }