Ejemplo n.º 1
0
void SearchEnginesDialog::addEngine()
{
    EditSearchEngine dialog(tr("Add Search Engine"), this);
    dialog.hideIconLabels();

    if (dialog.exec() != QDialog::Accepted) {
        return;
    }

    SearchEngine engine;
    engine.name = dialog.name();
    engine.url = dialog.url();
    engine.postData = dialog.postData().toUtf8();
    engine.shortcut = dialog.shortcut();
    engine.icon = SearchEnginesManager::iconForSearchEngine(QUrl::fromEncoded(dialog.url().toUtf8()));

    if (engine.name.isEmpty() || engine.url.isEmpty()) {
        return;
    }

    QTreeWidgetItem* item = new QTreeWidgetItem();
    setEngine(item, engine);

    changeItemToDefault(item, false);
    item->setIcon(0, engine.icon);
    item->setText(1, engine.shortcut);

    ui->treeWidget->addTopLevelItem(item);
}
Ejemplo n.º 2
0
void SearchEnginesDialog::editEngine()
{
    QTreeWidgetItem* item = ui->treeWidget->currentItem();
    if (!item) {
        return;
    }

    SearchEngine engine = getEngine(item);

    EditSearchEngine dialog(tr("Edit Search Engine"), this);

    dialog.setName(engine.name);
    dialog.setUrl(engine.url);
    dialog.setShortcut(engine.shortcut);
    dialog.setIcon(engine.icon);

    if (dialog.exec() != QDialog::Accepted) {
        return;
    }

    engine.name = dialog.name();
    engine.url = dialog.url();
    engine.shortcut = dialog.shortcut();
    engine.icon = dialog.icon();

    if (engine.name.isEmpty() || engine.url.isEmpty()) {
        return;
    }

    setEngine(item, engine);

    changeItemToDefault(item, isDefaultEngine(item));
    item->setIcon(0, engine.icon);
    item->setText(1, engine.shortcut);
}
Ejemplo n.º 3
0
/**
 * Creates instances of BasicBehaviours, needed according to the PlanRepository, with the help of the given
 * BehaviourCreator. If a BasicBehaviour cannot be instantiated, the Initialisation of the Pool is cancelled.
 * @param bc A BehaviourCreator.
 * @return True, if all necessary BasicBehaviours could be constructed. False, if the Initialisation was cancelled.
 */
bool BehaviourPool::init(IBehaviourCreator* bc)
{
    if (_behaviourCreator != nullptr) {
        delete _behaviourCreator;
    }

    _behaviourCreator = bc;

    const PlanRepository::Accessor<BehaviourConfiguration>& behaviourConfs = _ae->getPlanRepository()->getBehaviourConfigurations();
    for (const BehaviourConfiguration* beh : behaviourConfs) {
        auto basicBeh = _behaviourCreator->createBehaviour(beh->getId());
        if (basicBeh != nullptr) {
            // set stuff from behaviour configuration in basic behaviour object
            basicBeh->setConfiguration(beh);
            basicBeh->setDelayedStart(beh->getDeferring());
            basicBeh->setInterval(1000 / beh->getFrequency());
            basicBeh->setEngine(_ae);
            basicBeh->init();

            _availableBehaviours.insert(make_pair(beh, basicBeh));
        } else {
            return false;
        }
    }
    return true;
}
Ejemplo n.º 4
0
void HWInfo::init()
{
    KGlobal::locale()->insertCatalog("plasma_applet_system-monitor");
    setTitle(i18n("Hardware Info"));
    setEngine(dataEngine("soliddevice"));
    setSources();
    connectToEngine();
}
Ejemplo n.º 5
0
ScriptCache::ScriptCache() :
    _engine(NULL)
{
    setEngine(new QScriptEngine(this));
    
    const qint64 SCRIPT_DEFAULT_UNUSED_MAX_SIZE = 50 * BYTES_PER_MEGABYTES;
    setUnusedResourceCacheSize(SCRIPT_DEFAULT_UNUSED_MAX_SIZE);
}
Ejemplo n.º 6
0
void Hdd::init()
{
    KGlobal::locale()->insertCatalog("plasma_applet_system-monitor");
    QString predicateString("IS StorageVolume");
    setEngine(dataEngine("soliddevice"));

    setTitle(i18n("Disk Space"), true);

    configChanged();
}
Ejemplo n.º 7
0
void SM::Ram::init()
{
    KGlobal::locale()->insertCatalog("plasma_applet_system-monitor");
    setEngine(dataEngine("systemmonitor"));
    setTitle(i18n("RAM"));

    /* At the time this method is running, not all source may be connected. */
    connect(engine(), SIGNAL(sourceAdded(QString)), this, SLOT(sourceAdded(QString)));
    foreach (const QString& source, engine()->sources()) {
        sourceAdded(source);
    }
Ejemplo n.º 8
0
void Hdd_Activity::init()
{
    KGlobal::locale()->insertCatalog("plasma_applet_system-monitor");
    setEngine(dataEngine("systemmonitor"));
    setTitle(i18n("Disk Activity"), true);

    /* At the time this method is running, not all sources may be connected. */
    connect(engine(), SIGNAL(sourceAdded(QString)), this, SLOT(sourceChanged(QString)));
    connect(engine(), SIGNAL(sourceRemoved(QString)), this, SLOT(sourceChanged(QString)));

    foreach (const QString& source, engine()->sources()) {
        sourceChanged(source);
    }
Ejemplo n.º 9
0
void SearchEnginesDialog::reloadEngines()
{
    ui->treeWidget->clear();
    const QString defaultEngineName = mApp->searchEnginesManager()->defaultEngine().name;

    foreach (const SearchEngine &en, m_manager->allEngines()) {
        QTreeWidgetItem* item = new QTreeWidgetItem();
        setEngine(item, en);
        changeItemToDefault(item, en.name == defaultEngineName);
        item->setIcon(0, en.icon);
        item->setText(1, en.shortcut);

        ui->treeWidget->addTopLevelItem(item);
    }
}
Ejemplo n.º 10
0
EditorView::EditorView(QWidget * parent)
    : KGLView(parent),
      m_engine(0),
      m_selectedItem(0),
      m_moving(false),
      m_grid(true),
      m_gridSize(1)
{
    grabMouse();
    setMouseTracking(true);

    QRect screenDim = QApplication::desktop()->screenGeometry();
    m_ratio = (double)screenDim.width()/screenDim.height();

    m_engine= new KGLPhysicsEngine;
    setEngine(m_engine);
    m_wallPaperItem = new KGLBoxItem(20*m_ratio, 20);
    m_groundItem = new KGLPhysicsItem;
    initEngine();
}
Ejemplo n.º 11
0
ScriptCache::ScriptCache() :
    _engine(NULL) {
    
    setEngine(new QScriptEngine(this));
}
BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create)
{
    if (!create.cluster.empty())
    {
        NameSet databases{create.database};
        if (!create.to_table.empty())
            databases.emplace(create.to_database);

        return executeDDLQueryOnCluster(query_ptr, context, std::move(databases));
    }

    String path = context.getPath();
    String current_database = context.getCurrentDatabase();

    String database_name = create.database.empty() ? current_database : create.database;
    String table_name = create.table;
    String table_name_escaped = escapeForFileName(table_name);

    // If this is a stub ATTACH query, read the query definition from the database
    if (create.attach && !create.storage && !create.columns)
    {
        // Table SQL definition is available even if the table is detached
        auto query = context.getCreateTableQuery(database_name, table_name);
        auto & as_create = typeid_cast<const ASTCreateQuery &>(*query);
        create = as_create; // Copy the saved create query, but use ATTACH instead of CREATE
        create.attach = true;
    }

    if (create.to_database.empty())
        create.to_database = current_database;

    if (create.select && (create.is_view || create.is_materialized_view))
    {
        AddDefaultDatabaseVisitor visitor(current_database);
        visitor.visit(*create.select);
    }

    Block as_select_sample;
    if (create.select && (!create.attach || !create.columns))
        as_select_sample = InterpreterSelectWithUnionQuery::getSampleBlock(create.select->clone(), context);

    String as_database_name = create.as_database.empty() ? current_database : create.as_database;
    String as_table_name = create.as_table;

    StoragePtr as_storage;
    TableStructureReadLockPtr as_storage_lock;
    if (!as_table_name.empty())
    {
        as_storage = context.getTable(as_database_name, as_table_name);
        as_storage_lock = as_storage->lockStructure(false);
    }

    /// Set and retrieve list of columns.
    ColumnsDescription columns = setColumns(create, as_select_sample, as_storage);

    /// Some column types may be not allowed according to settings.
    if (!create.attach)
        checkSupportedTypes(columns, context);

    /// Set the table engine if it was not specified explicitly.
    setEngine(create);

    StoragePtr res;

    {
        std::unique_ptr<DDLGuard> guard;

        String data_path;
        DatabasePtr database;

        if (!create.temporary)
        {
            database = context.getDatabase(database_name);
            data_path = database->getDataPath();

            /** If the request specifies IF NOT EXISTS, we allow concurrent CREATE queries (which do nothing).
              * If table doesnt exist, one thread is creating table, while others wait in DDLGuard.
              */
            guard = context.getDDLGuard(database_name, table_name);

            /// Table can be created before or it can be created concurrently in another thread, while we were waiting in DDLGuard.
            if (database->isTableExist(context, table_name))
            {
                if (create.if_not_exists)
                    return {};
                else
                    throw Exception("Table " + database_name + "." + table_name + " already exists.", ErrorCodes::TABLE_ALREADY_EXISTS);
            }
        }
        else if (context.tryGetExternalTable(table_name) && create.if_not_exists)
             return {};

        res = StorageFactory::instance().get(create,
            data_path,
            table_name,
            database_name,
            context,
            context.getGlobalContext(),
            columns,
            create.attach,
            false);

        if (create.temporary)
            context.getSessionContext().addExternalTable(table_name, res, query_ptr);
        else
            database->createTable(context, table_name, res, query_ptr);

        /// We must call "startup" and "shutdown" while holding DDLGuard.
        /// Because otherwise method "shutdown" (from InterpreterDropQuery) can be called before startup
        /// (in case when table was created and instantly dropped before started up)
        ///
        /// Method "startup" may create background tasks and method "shutdown" will wait for them.
        /// But if "shutdown" is called before "startup", it will exit early, because there are no background tasks to wait.
        /// Then background task is created by "startup" method. And when destructor of a table object is called, background task is still active,
        /// and the task will use references to freed data.

        res->startup();
    }

    /// If the query is a CREATE SELECT, insert the data into the table.
    if (create.select && !create.attach
        && !create.is_view && (!create.is_materialized_view || create.is_populate))
    {
        auto insert = std::make_shared<ASTInsertQuery>();

        if (!create.temporary)
            insert->database = database_name;

        insert->table = table_name;
        insert->select = create.select->clone();

        if (create.temporary && !context.getSessionContext().hasQueryContext())
            context.getSessionContext().setQueryContext(context.getSessionContext());

        return InterpreterInsertQuery(insert,
            create.temporary ? context.getSessionContext() : context,
            context.getSettingsRef().insert_allow_materialized_columns).execute();
    }

    return {};
}
Ejemplo n.º 13
0
 void Linear::set(const std::vector<scalar>& coeffs, const Engine* engine) {
     setCoefficients(coeffs);
     setEngine(engine);
 }
Ejemplo n.º 14
0
void pidDriver (void)
{
    ADC_OFF;

    Pitch_Difference 	= ADC_standStill[ADC_PITCH]-ADC_runtime[ADC_PITCH]-(int)ADC_drift[ADC_PITCH];
    Y_Difference_AccY 	= ADC_standStill[ADC_ACCY]-ADC_runtime[ADC_ACCY];
    Y_Difference_GyrN 	= -1*(ADC_standStill[ADC_NICK]-ADC_runtime[ADC_NICK]-(int)ADC_drift[ADC_NICK]);
    X_Difference_AccX 	= ADC_standStill[ADC_ACCX]-ADC_runtime[ADC_ACCX];
//X_Difference_AccX 	= -1*(ADC_standStill[ADC_ACCX]-ADC_runtime[ADC_ACCX]);
    X_Difference_GyrR 	= ADC_standStill[ADC_ROLL]-ADC_runtime[ADC_ROLL]-(int)ADC_drift[ADC_ROLL];
//X_Difference_GyrR 	= -1*(ADC_standStill[ADC_ROLL]-ADC_runtime[ADC_ROLL]-(int)ADC_drift[ADC_ROLL]);
    ADC_ON;


    //Pitch axis
    //the raw sensor value
    DifferencePitchGyr = Pitch_Difference;
    //limit the raw value
    DifferencePitchFact = (signed int)(Pitch_Difference * fcSetup.pid_GyroPitchFact);
    //add limited raw value to I
    Pitch_Difference_Sum += DifferencePitchFact;
    //integral > max limit to max
    if (Pitch_Difference_Sum > fcSetup.pid_Pitch_IntegralMax)
    {
        Pitch_Difference_Sum = fcSetup.pid_Pitch_IntegralMax;
    }
    //integral < min limit to min
    if (Pitch_Difference_Sum < fcSetup.pid_Pitch_IntegralMin)
    {
        Pitch_Difference_Sum = fcSetup.pid_Pitch_IntegralMin;
    }



    //Pitch P
    Pitch_Difference = (signed int)(fcSetup.pid_PitchP  * DifferencePitchFact);
    //Pitch I
    Pitch_Difference += (signed int)(fcSetup.pid_PitchI * Pitch_Difference_Sum);
    //Pitch D
    Pitch_Difference += (signed int)(fcSetup.pid_PitchD * (DifferencePitchFact + Pitch_Difference_old));
    //Pitch Stick
    Pitch_Difference += (signed int)(fcSetup.pid_PitchStickFact * PWM_channel[PWM_G]);

    Pitch_Difference_old = DifferencePitchFact;

//DifferencePitchFact = 0;
//Pitch_Difference = 0;
    //Normalize throttle value to get -120 -> 120 to 0 -> 240
    throttle = PWM_channel[PWM_THROTTLE] + fcSetup.pid_throttleOffset;

    if (fcSetup.components[airpressureComponent])
    {
        altActual = ADC_standStill[AIRPRESSURE] - ADC_runtime[AIRPRESSURE];
        if (PWM_channel[baroChan] < 50) {
            targetAlt = altActual;
            LED4_OFF;
        } else {

            if (altActual > targetAlt)
            {
                LED4_ON;
                throttle -= targetAlt - altActual;
            }
        }
    }



    //here we try to tackle the changes in throttle due to Pitch control
    //Subtract Pitch reaction from throttle
    signed int PitchLimiter = (Pitch_Difference * fcSetup.pid_PitchThrottleFact);

    PitchLimiter = 0;

    //Roll axis
    XACCDelta = (X_Gyr_ACC_Difference_old - X_Gyr_ACC_Difference) / 50;
    X_Gyr_ACC_Difference_old = X_Gyr_ACC_Difference;
    //Normalize Gyro and ACC Signal
    X_Gyr_ACC_Difference = (signed int)(X_Difference_AccX * fcSetup.pid_X_AccX_Fact);
    // ACC limits the Gyro to help ACC to have more force when having large ACC values
    // this should help ACC force to be more reactive and not to force against the gyro
    X_AccGyroLimiter = X_Difference_GyrR + XACCDelta;
    X_AccGyroLimiter = 0.0;

    X_Gyr_ACC_Difference += (signed int)(X_Difference_GyrR * (fcSetup.pid_X_GyroFact - X_AccGyroLimiter));
    //X_Gyr_ACC_Difference += (signed int)(X_Difference_GyrR - X_AccGyroLimiter * (fcSetup.pid_X_GyroFact));


    //Gyr ACC > max limit to max
    if(X_Gyr_ACC_Difference > fcSetup.pid_X_GyroACCFactMax)
    {
        X_Gyr_ACC_Difference = fcSetup.pid_X_GyroACCFactMax;
    }
    //Gyr ACC < min limit to min
    if(X_Gyr_ACC_Difference < fcSetup.pid_X_GyroACCFactMin)
    {
        X_Gyr_ACC_Difference = fcSetup.pid_X_GyroACCFactMin;
    }


    //PID - controller
    //Limits the Gyro ACC reaction relative to what the Stick wants to achieve
    //This should help the stick has not to work against the sensors
    XStickLimiter = fcSetup.pid_X_GyroACCFact / 120 * abs(PWM_channel[PWM_R]);
    XStickLimiter = 0.0;
    //Difference = X_DifferenceFact * factor from setting (expected = 0) 0 is expected as in a perfect world no change would ever happen
    X_DifferenceFact = X_Gyr_ACC_Difference * (fcSetup.pid_X_GyroACCFact - XStickLimiter);

    //calculate Integral I
    X_Difference_Sum += X_DifferenceFact;

    //integral > max limit to max integral coming from setting
    if (X_Difference_Sum > fcSetup.pid_X_IntegralMax)
    {
        X_Difference_Sum = fcSetup.pid_X_IntegralMax;
    }

    //integral < min limit to min integral coming from setting
    if (X_Difference_Sum < fcSetup.pid_X_IntegralMin)
    {
        X_Difference_Sum = fcSetup.pid_X_IntegralMin;
    }


    //Roll P
    X_Response  = (signed int)(fcSetup.pid_X_P * X_DifferenceFact);
    //Roll I
    X_Response += (signed int)(fcSetup.pid_X_I * X_Difference_Sum);
    //Roll D
    X_Response += (signed int)(fcSetup.pid_X_D * (X_DifferenceFact + X_Difference_old));
    //Roll Stick
    X_Response -= (signed int)(fcSetup.pid_RollStickFact * PWM_channel[PWM_R]);


    //save old value for D
    X_Difference_old = X_DifferenceFact;


    //Nick axis

    //Normalize Gyr Signal and AAC
    Y_Gyr_ACC_Difference = (signed int)(Y_Difference_GyrN * fcSetup.pid_Y_GyroFact);
    // ACC limits the Gyro to help ACC to have more force when having large ACC values
    // this should help ACC force to be more reactive and not to force against the gyro
    YAccGyroLimiter = fcSetup.pid_Y_GyroFact / accOneG * abs(X_Difference_AccX);
    YAccGyroLimiter = 0;
    Y_Gyr_ACC_Difference += (signed int)(Y_Difference_AccY * (fcSetup.pid_Y_AccY_Fact - YAccGyroLimiter));

    //Gyr ACC > max limit to max
    if(Y_Gyr_ACC_Difference > fcSetup.pid_Y_GyroACCFactMax)
    {
        Y_Gyr_ACC_Difference = fcSetup.pid_Y_GyroACCFactMax;
    }
    //Gyr ACC < min limit to min
    if(Y_Gyr_ACC_Difference < fcSetup.pid_Y_GyroACCFactMin)
    {
        Y_Gyr_ACC_Difference = fcSetup.pid_Y_GyroACCFactMin;
    }


    //Limits the Gyro ACC reaction relative to what the Stick wants to achieve
    //This should help the stick has not to work against the sensors
    YStickLimiter = fcSetup.pid_Y_GyroACCFact / 120 * abs(PWM_channel[PWM_N]);
    YStickLimiter = 0;
    //Difference gets regulated to limit max reaction to it
    Y_DifferenceFact = (signed int)(Y_Gyr_ACC_Difference * (fcSetup.pid_Y_GyroACCFact - YStickLimiter));

    //calculate Integral
    Y_Difference_Sum += Y_DifferenceFact;
    //integral > max limit to max
    if (Y_Difference_Sum > fcSetup.pid_Y_IntegralMax)
    {
        Y_Difference_Sum = fcSetup.pid_Y_IntegralMax;
    }
    //integral < min limit to min
    if (Y_Difference_Sum < fcSetup.pid_Y_IntegralMin)
    {
        Y_Difference_Sum = fcSetup.pid_Y_IntegralMin;
    }

    //do the controlling PID math
    //Nick P
    Y_Response  = (signed int)(fcSetup.pid_Y_P * Y_DifferenceFact);
    //Nick I
    Y_Response += (signed int)(fcSetup.pid_Y_I * Y_Difference_Sum);
    //Nick D
    Y_Response += (signed int)(fcSetup.pid_Y_D * (Y_DifferenceFact + Y_Difference_old));
    //Nick Stick
    Y_Response -= (signed int)(fcSetup.pid_NickStickFact * PWM_channel[PWM_N]);


    //save old value for D
    Y_Difference_old = Y_DifferenceFact;


    //set the engine values
    signed int pitchFact = (int)((fcSetup.pid_X_PitchFact * Pitch_Difference) + PitchLimiter) * pitchCorrection;
    Engine_value = (int)((throttle - X_Response) - pitchFact);
    setEngine(RIGHTENGINE,Engine_value);
    Engine_value = (int)((throttle + X_Response) - pitchFact);
    setEngine(LEFTENGINE,Engine_value);
    //this is for single axis testing
    //PWMEngOut[RIGHTENGINE] = 0;
    //PWMEngOut[LEFTENGINE] = 0;


    pitchFact = (int)((fcSetup.pid_Y_PitchFact * Pitch_Difference)- PitchLimiter) * pitchCorrection;
    Engine_value = (int)((throttle + Y_Response) + pitchFact);
    setEngine(FRONTENGINE,Engine_value);
    Engine_value = (int)((throttle - Y_Response) + pitchFact);
    setEngine(BACKENGINE,Engine_value);
    //this is for single axis testing
    //PWMEngOut[FRONTENGINE] = 0;
    //PWMEngOut[BACKENGINE] = 0;
}
Ejemplo n.º 15
0
BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create)
{
    if (!create.cluster.empty())
    {
        NameSet databases{create.database};
        if (!create.to_table.empty())
            databases.emplace(create.to_database);

        return executeDDLQueryOnCluster(query_ptr, context, databases);
    }

    String path = context.getPath();
    String current_database = context.getCurrentDatabase();

    String database_name = create.database.empty() ? current_database : create.database;
    String table_name = create.table;
    String table_name_escaped = escapeForFileName(table_name);

    // If this is a stub ATTACH query, read the query definition from the database
    if (create.attach && !create.storage && !create.columns)
    {
        // Table SQL definition is available even if the table is detached
        auto query = context.getCreateTableQuery(database_name, table_name);
        auto & as_create = typeid_cast<const ASTCreateQuery &>(*query);
        create = as_create; // Copy the saved create query, but use ATTACH instead of CREATE
        create.attach = true;
    }

    if (create.to_database.empty())
        create.to_database = current_database;

    if (create.select && (create.is_view || create.is_materialized_view))
        create.select->setDatabaseIfNeeded(current_database);

    Block as_select_sample;
    if (create.select && (!create.attach || !create.columns))
        as_select_sample = InterpreterSelectWithUnionQuery::getSampleBlock(create.select->clone(), context);

    String as_database_name = create.as_database.empty() ? current_database : create.as_database;
    String as_table_name = create.as_table;

    StoragePtr as_storage;
    TableStructureReadLockPtr as_storage_lock;
    if (!as_table_name.empty())
    {
        as_storage = context.getTable(as_database_name, as_table_name);
        as_storage_lock = as_storage->lockStructure(false, __PRETTY_FUNCTION__);
    }

    /// Set and retrieve list of columns.
    ColumnsDescription columns = setColumns(create, as_select_sample, as_storage);

    /// Set the table engine if it was not specified explicitly.
    setEngine(create);

    StoragePtr res;

    {
        std::unique_ptr<DDLGuard> guard;

        String data_path;
        DatabasePtr database;

        if (!create.is_temporary)
        {
            database = context.getDatabase(database_name);
            data_path = database->getDataPath();

            /** If the table already exists, and the request specifies IF NOT EXISTS,
              *  then we allow concurrent CREATE queries (which do nothing).
              * Otherwise, concurrent queries for creating a table, if the table does not exist,
              *  can throw an exception, even if IF NOT EXISTS is specified.
              */
            guard = context.getDDLGuardIfTableDoesntExist(database_name, table_name,
                "Table " + database_name + "." + table_name + " is creating or attaching right now");

            if (!guard)
            {
                if (create.if_not_exists)
                    return {};
                else
                    throw Exception("Table " + database_name + "." + table_name + " already exists.", ErrorCodes::TABLE_ALREADY_EXISTS);
            }
        }
        else if (context.tryGetExternalTable(table_name) && create.if_not_exists)
             return {};

        res = StorageFactory::instance().get(create,
            data_path,
            table_name,
            database_name,
            context,
            context.getGlobalContext(),
            columns,
            create.attach,
            false);

        if (create.is_temporary)
            context.getSessionContext().addExternalTable(table_name, res, query_ptr);
        else
            database->createTable(context, table_name, res, query_ptr);
    }

    res->startup();

    /// If the query is a CREATE SELECT, insert the data into the table.
    if (create.select && !create.attach
        && !create.is_view && (!create.is_materialized_view || create.is_populate))
    {
        auto insert = std::make_shared<ASTInsertQuery>();

        if (!create.is_temporary)
            insert->database = database_name;

        insert->table = table_name;
        insert->select = create.select->clone();

        return InterpreterInsertQuery(insert,
            create.is_temporary ? context.getSessionContext() : context,
            context.getSettingsRef().insert_allow_materialized_columns).execute();
    }

    return {};
}
Ejemplo n.º 16
0
ScriptCache::ScriptCache() :
    _networkAccessManager(NULL),
    _engine(NULL) {
    
    setEngine(new QScriptEngine(this));
}
Ejemplo n.º 17
0
int main(void)
{
	time_t start, end;

    string dir = string("./moviesdb");	// Stores the path of the folder with the files
    
    multimap<int, string> results; // Stores the qualifying files and sorts them
    
    std::tr1::unordered_set<string> stops; // Stores the stop words
    
    std::tr1::unordered_map< string, std::tr1::unordered_map<std::string,int> > files_freq; // Stores the words, files and frequency
    
	vector<string> inputs; // Stores the inputs of the user
	
    vector<ParsedFile> files; // Stores the files of the directory
    
    char searching[256];
    
    int count = 0;
    
    cout << endl << " Building the Search Engine... "<< endl ;
    time (&start);
  	
  	// Starts the engine 
  	setEngine(dir, stops, files, files_freq);
  	
  	time (&end);
    cout << " The search engine finished building. It took: " << difftime(end,start) << " seconds" << endl << endl;
  	
  	do{
  	
  		
  		// Displays the logo
  		displayLogo();
  		
    	// Gets the inputs of the user
    	getWords(inputs, count);
    	
    	//for (int i = 0; i < inputs.size(); i++)
    	//	cout << inputs[i] << " ";
		
		// Gets results of case with two words
		if(inputs.size() == 2){ 
			results = getResults(inputs[0], inputs[1], files_freq);
		}
	
		// Gets results of case with one word
		else if (inputs.size() == 1){
			results = getResults(inputs[0], inputs[0], files_freq);
		}
	
		//Display the three most highest files based on frequency
		displayResults(results);
		
		cout << "Want to keep searching? Enter 'y' if yes or 'n' if no" << endl;
		cin >> searching;
		
		results.clear();
		
		count++;
		
	}while(strcmp(searching, "y") == 0 || strcmp(searching, "Y") == 0);
	
    return 0;
}
Ejemplo n.º 18
0
 Engine::Engine(unsigned int engid, double aforce[3], double pos[3], double orient[3], float force)
 {
   setEngine(engid, aforce, pos, orient, force);
 }
BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create)
{
    String path = context.getPath();
    String current_database = context.getCurrentDatabase();

    String database_name = create.database.empty() ? current_database : create.database;
    String database_name_escaped = escapeForFileName(database_name);
    String table_name = create.table;
    String table_name_escaped = escapeForFileName(table_name);

    String data_path = path + "data/" + database_name_escaped + "/";
    String metadata_path = path + "metadata/" + database_name_escaped + "/" + table_name_escaped + ".sql";

    std::unique_ptr<InterpreterSelectQuery> interpreter_select;
    Block as_select_sample;
    /// Для таблиц типа view, чтобы получить столбцы, может понадобиться sample_block.
    if (create.select && (!create.attach || (!create.columns && (create.is_view || create.is_materialized_view))))
    {
        interpreter_select = std::make_unique<InterpreterSelectQuery>(create.select, context);
        as_select_sample = interpreter_select->getSampleBlock();
    }

    String as_database_name = create.as_database.empty() ? current_database : create.as_database;
    String as_table_name = create.as_table;

    StoragePtr as_storage;
    IStorage::TableStructureReadLockPtr as_storage_lock;
    if (!as_table_name.empty())
    {
        as_storage = context.getTable(as_database_name, as_table_name);
        as_storage_lock = as_storage->lockStructure(false);
    }

    /// Устанавливаем и получаем список столбцов.
    ColumnsInfo columns = setColumns(create, as_select_sample, as_storage);

    /// Выбор нужного движка таблицы
    String storage_name = setEngine(create, as_storage);

    StoragePtr res;

    {
        std::unique_ptr<DDLGuard> guard;

        if (!create.is_temporary)
        {
            context.assertDatabaseExists(database_name);

            /** Если таблица уже существует, и в запросе указано IF NOT EXISTS,
              *  то мы разрешаем конкуррентные запросы CREATE (которые ничего не делают).
              * Иначе конкуррентные запросы на создание таблицы, если таблицы не существует,
              *  могут кидать исключение, даже если указано IF NOT EXISTS.
              */
            guard = context.getDDLGuardIfTableDoesntExist(database_name, table_name,
                    "Table " + database_name + "." + table_name + " is creating or attaching right now");

            if (!guard)
            {
                if (create.if_not_exists)
                    return {};
                else
                    throw Exception("Table " + database_name + "." + table_name + " already exists.", ErrorCodes::TABLE_ALREADY_EXISTS);
            }
        }

        res = StorageFactory::instance().get(
                  storage_name, data_path, table_name, database_name, context,
                  context.getGlobalContext(), query_ptr, columns.columns,
                  columns.materialized_columns, columns.alias_columns, columns.column_defaults, create.attach);

        if (create.is_temporary)
            context.getSessionContext().addExternalTable(table_name, res);
        else
            context.getDatabase(database_name)->createTable(table_name, res, query_ptr, storage_name);
    }

    /// Если запрос CREATE SELECT, то вставим в таблицу данные
    if (create.select && storage_name != "View" && (storage_name != "MaterializedView" || create.is_populate))
    {
        auto table_lock = res->lockStructure(true);

        /// Также см. InterpreterInsertQuery.
        BlockOutputStreamPtr out =
            std::make_shared<ProhibitColumnsBlockOutputStream>(
                std::make_shared<AddingDefaultBlockOutputStream>(
                    std::make_shared<MaterializingBlockOutputStream>(
                        std::make_shared<PushingToViewsBlockOutputStream>(
                            create.database, create.table,
                            create.is_temporary ? context.getSessionContext() : context,
                            query_ptr)),
                    /// @note shouldn't these two contexts be session contexts in case of temporary table?
                    columns.columns, columns.column_defaults, context, static_cast<bool>(context.getSettingsRef().strict_insert_defaults)),
                columns.materialized_columns);

        BlockIO io;
        io.in_sample = as_select_sample;
        io.in = std::make_shared<NullAndDoCopyBlockInputStream>(interpreter_select->execute().in, out);

        return io;
    }

    return {};
}