text:
use evolution::Evolvable;

use std::io;
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::env;
use std::process::Command;

use rustc_serialize::*;
use bincode::rustc_serialize::{encode_into, decode_from};
use bincode::SizeLimit;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};

pub struct Options {
    /// The port the master should listen on
    pub port: u16,

    /// Sets the condition when master should start to command slaves
    pub startCondition: StartCondition,
    /// Sets sync condition
    pub syncCondition: SynchronizeCondition
}

impl Options {
    pub fn defaults() -> Self {
        Options {
            port: 1337,

            startCondition: StartCondition::NoConnectsSinceSeconds(15),
            syncCondition: SynchronizeCondition::AfterGenerationsAdvanced(6),
        }
    }
}

pub enum StartCondition {
    /// Starts when x clients are connected and ready
    AmountClientsReady(usize),
    /// Starts when the last connection was x seconds ago
    NoConnectsSinceSeconds(usize)
}

pub enum SynchronizeCondition {
    /// Synchronizes every x seconds
    AfterTimeInSeconds(usize),

    /// Synchronizes every x generations
    AfterGenerationsAdvanced(usize)
}

struct NetworkEvolvable<'a> {
    client: &'a TcpStream,
    fitness: f64
}

impl<'a> Evolvable for NetworkEvolvable<'a> {
    fn cross_over(&self, other: &Self) -> Self {
        panic!("TODO")
    }

    fn mutate(&mut self) {
        // send train request
        self.client.write(&[0x00, 0x02]);

        // read answer
    }
}

/// Creates an host for scaling
pub fn create_scaling_host(options: Options) {
    // create listener
    let listener = TcpListener::bind(("0.0.0.0", options.port)).unwrap();

    // start to listen
    let mut connections = Vec::new();

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                // connection succeeded
                connections.push(stream);
                info!(target: "scaling", "Client connection, No: {}", connections.len());

                // handle startup
                match options.startCondition {
                    StartCondition::AmountClientsReady(x) => {
                        if connections.len() == x {
                            break;
                        }
                    },
                    _ => { }
                }
            }
            Err(_) => {
                // client connection failed
                error!(target: "scaling", "Failed to handle tcp client connection");
            }
        }
    }

    // send start command to all client
    for mut stream in connections {
        let _ = stream.write(&[0x00, 0x01]); // start command
    }
}

/// Creates an client for scaling
pub fn create_scaling_client<T: Encodable + Decodable, Finit, Fcontinue>(master_port: u16, init: Finit, train: Fcontinue)
    where Finit:     Fn() -> (T, f64),
          Fcontinue: Fn(&mut T) -> f64
{
    let mut current_object: Option<&mut T> = None;
    let mut opcode = [0; 2];
    let mut stream = TcpStream::connect(("127.0.0.1", master_port)).unwrap_or_else(|e| {
        error!(target: "scaling", "Failed to connect to master {}", e);
        panic!("can't continue")
    });

    loop {
        let _ = stream.read(&mut opcode);

        // start action
        if opcode[0] == 0x00 && opcode[1] == 0x01 {
            info!(target: "scaling", "Received init request");
            let (initial, fitness) = init();
            current_object = Some(initial);

            stream.write(&[0x00, 0x01]);
            stream.write_f64::<BigEndian>(fitness);
            encode_into(&current_object, &mut stream, SizeLimit::Infinite);
        }

        // train action
        else if opcode[0] == 0x00 && opcode[1] == 0x02 {
            info!(target: "scaling", "Received train request");
            let new_fitness = train(current_object.unwrap_or_else(|e| {
                error!(target: "scaling", "Tried to train without initializing first. Possibly an error in init function.");
                panic!("can't continue")
            }));

            stream.write(&[0x00, 0x02]);
            stream.write_f64::<BigEndian>(new_fitness);
        }

        // get current object request
        else if opcode[0] == 0x00 && opcode[1] == 0x03 {
            info!(target: "scaling", "Received get current object request");

            stream.write(&[0x00, 0x03]);
            encode_into(&current_object, &mut stream, SizeLimit::Infinite);
        }

        // set current object request
        else if opcode[0] == 0x00 && opcode[1] == 0x04 {
            info!(target: "scaling", "Received set current object request");

            match decode_from(&mut stream, SizeLimit::Infinite) {
                Ok(object) => {
                    current_object = object;
                },

                Err(err) => {
                    error!(target: "scaling", "Could not decode set current object request. Ignoring request.");
                }
            }
        }
    }
}

/// Creates one new fork
pub fn fork_scaling() {
    // get path to self
    let self_path = env::current_exe().unwrap_or_else(|e| {
        error!(target: "scaling", "failed to fork process: {}", e);
        panic!("Can't continue")
    });

    // spawn child
    let _ = Command::new(self_path)
        .arg("--type child")
        .spawn();
}

pub enum ProcessType {
    /// Controlls slaves that will actually train
    Master,
    /// Slave that will train given individual from master
    Slave
}

/// Returns current process type
pub fn process_type() -> ProcessType {
    for argument in env::args() {
        if argument == "--type child" {
            return ProcessType::Slave;
        }
    }

    ProcessType::Master
}


text:
package client;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import static org.junit.Assert.*;

/**
 * Created by huanganna on 16/6/5.
 */
public class ModalDeleteGroupDialogTest extends Application {
    public static void main(String[] args) {
        Application.launch(ModalDeleteGroupDialogTest.class, args);
    }

    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("Hello World");
        Group root = new Group();
        Scene scene = new Scene(root, 500, 450, Color.LIGHTBLUE);
        Button btn = new Button();
        btn.setLayoutX(250);
        btn.setLayoutY(240);
        btn.setText("Show modal dialog");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            public void handle(ActionEvent event) {
                try {
//                    ModalDeleteGroupDialog md = new ModalDeleteGroupDialog(primaryStage);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        root.getChildren().add(btn);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.openmuc.framework.data;

import java.nio.ByteBuffer;

public class DoubleValue extends NumberValue {

    public DoubleValue(double value) {
        super(value);
    }

    public DoubleValue(String value) {
        super(Double.parseDouble(value));
    }

    @Override
    public byte[] asByteArray() {
        byte[] bytes = new byte[8];
        ByteBuffer.wrap(bytes).putDouble(super.asDouble());
        return bytes;
    }

    @Override
    public ValueType getValueType() {
        return ValueType.DOUBLE;
    }

}


text:
import json

from awxkit.utils import (
    filter_by_class,
    not_provided,
    random_title,
    suppress,
    update_payload,
    PseudoNamespace)
from awxkit.api.pages import Credential, Inventory, Project, UnifiedJobTemplate
from awxkit.api.mixins import HasCreate, HasInstanceGroups, HasNotifications, HasSurvey, HasCopy, DSAdapter
from awxkit.api.resources import resources
import awxkit.exceptions as exc
from . import base
from . import page

class JobTemplate(
        HasCopy,
        HasCreate,
        HasInstanceGroups,
        HasNotifications,
        HasSurvey,
        UnifiedJobTemplate):

    optional_dependencies = [Inventory, Credential, Project]
    NATURAL_KEY = ('organization', 'name')

    def launch(self, payload={}):
        """Launch the job_template using related->launch endpoint."""
        # get related->launch
        launch_pg = self.get_related('launch')

        # launch the job_template
        result = launch_pg.post(payload)

        # return job
        if result.json['type'] == 'job':
            jobs_pg = self.get_related('jobs', id=result.json['job'])
            assert jobs_pg.count == 1, \
                "job_template launched (id:%s) but job not found in response at %s/jobs/" % \
                (result.json['job'], self.url)
            return jobs_pg.results[0]
        elif result.json['type'] == 'workflow_job':
            slice_workflow_jobs = self.get_related(
                'slice_workflow_jobs', id=result.json['id'])
            assert slice_workflow_jobs.count == 1, (
                "job_template launched sliced job (id:%s) but not found in related %s/slice_workflow_jobs/" %
                (result.json['id'], self.url)
            )
            return slice_workflow_jobs.results[0]
        else:
            raise RuntimeError('Unexpected type of job template spawned job.')

    def payload(self, job_type='run', playbook='ping.yml', **kwargs):
        name = kwargs.get('name') or 'JobTemplate - {}'.format(random_title())
        description = kwargs.get('description') or random_title(10)
        payload = PseudoNamespace(
            name=name,
            description=description,
            job_type=job_type)

        optional_fields = (
            'ask_scm_branch_on_launch',
            'ask_credential_on_launch',
            'ask_diff_mode_on_launch',
            'ask_inventory_on_launch',
            'ask_job_type_on_launch',
            'ask_limit_on_launch',
            'ask_skip_tags_on_launch',
            'ask_tags_on_launch',
            'ask_variables_on_launch',
            'ask_verbosity_on_launch',
            'allow_simultaneous',
            'become_enabled',
            'diff_mode',
            'force_handlers',
            'forks',
            'host_config_key',
            'job_tags',
            'limit',
            'skip_tags',
            'start_at_task',
            'survey_enabled',
            'timeout',
            'use_fact_cache',
            'vault_credential',
            'verbosity',
            'job_slice_count',
            'webhook_service',
            'webhook_credential',
            'scm_branch')

        update_payload(payload, optional_fields, kwargs)

        extra_vars = kwargs.get('extra_vars', not_provided)
        if extra_vars != not_provided:
            if isinstance(extra_vars, dict):
                extra_vars = json.dumps(extra_vars)
            payload.update(extra_vars=extra_vars)

        if kwargs.get('project'):
            payload.update(project=kwargs.get('project').id, playbook=playbook)
        if kwargs.get('inventory'):
            payload.update(inventory=kwargs.get('inventory').id)
        if kwargs.get('credential'):
            payload.update(credential=kwargs.get('credential').id)
        if kwargs.get('webhook_credential'):
            webhook_cred = kwargs.get('webhook_credential')
            if isinstance(webhook_cred, int):
                payload.update(webhook_credential=int(webhook_cred))
            elif hasattr(webhook_cred, 'id'):
                payload.update(webhook_credential=webhook_cred.id)
            else:
                raise AttributeError("Webhook credential must either be integer of pkid or Credential object")

        return payload

    def add_label(self, label):
        if isinstance(label, page.Page):
            label = label.json
        with suppress(exc.NoContent):
            self.related.labels.post(label)

    def create_payload(
            self,
            name='',
            description='',
            job_type='run',
            playbook='ping.yml',
            credential=Credential,
            inventory=Inventory,
            project=None,
            **kwargs):
        if not project:
            project = Project
        if not inventory and not kwargs.get('ask_inventory_on_launch', False):
            inventory = Inventory

        self.create_and_update_dependencies(
            *
            filter_by_class(
                (credential,
                 Credential),
                (inventory,
                 Inventory),
                (project,
                 Project)))
        project = self.ds.project if project else None
        inventory = self.ds.inventory if inventory else None
        credential = self.ds.credential if credential else None

        payload = self.payload(
            name=name,
            description=description,
            job_type=job_type,
            playbook=playbook,
            credential=credential,
            inventory=inventory,
            project=project,
            **kwargs)
        payload.ds = DSAdapter(self.__class__.__name__, self._dependency_store)
        return payload, credential

    def create(
            self,
            name='',
            description='',
            job_type='run',
            playbook='ping.yml',
            credential=Credential,
            inventory=Inventory,
            project=None,
            **kwargs):
        payload, credential = self.create_payload(name=name, description=description, job_type=job_type,
                                                  playbook=playbook, credential=credential, inventory=inventory,
                                                  project=project, **kwargs)
        ret = self.update_identity(
            JobTemplates(
                self.connection).post(payload))
        if credential:
            with suppress(exc.NoContent):
                self.related.credentials.post(dict(id=credential.id))
        if 'vault_credential' in kwargs:
            with suppress(exc.NoContent):
                if not isinstance(kwargs['vault_credential'], int):
                    raise ValueError(
                        "Expected 'vault_credential' value to be an integer, the id of the desired vault credential")
                self.related.credentials.post(
                    dict(id=kwargs['vault_credential']))
        return ret

    def add_credential(self, credential):
        with suppress(exc.NoContent):
            self.related.credentials.post(
                dict(id=credential.id, associate=True))

    def remove_credential(self, credential):
        with suppress(exc.NoContent):
            self.related.credentials.post(
                dict(id=credential.id, disassociate=True))

    def remove_all_credentials(self):
        for cred in self.related.credentials.get().results:
            with suppress(exc.NoContent):
                self.related.credentials.post(
                    dict(id=cred.id, disassociate=True))

page.register_page([resources.job_template,
                    (resources.job_templates, 'post'),
                    (resources.job_template_copy, 'post')], JobTemplate)

class JobTemplates(page.PageList, JobTemplate):

    pass

page.register_page([resources.job_templates,
                    resources.related_job_templates], JobTemplates)

class JobTemplateCallback(base.Base):

    pass

page.register_page(resources.job_template_callback, JobTemplateCallback)

class JobTemplateLaunch(base.Base):

    pass

page.register_page(resources.job_template_launch, JobTemplateLaunch)

class JobTemplateCopy(base.Base):

    pass

page.register_page([resources.job_template_copy], JobTemplateCopy)


text:
var Project = require('../models/project.mdl');
var Calendar = require('../models/calendar.mdl');
var Gantt = require('../models/gantt.chart.mdl');
var mongoose=require('mongoose');
var router = require('express').Router()
var _ = require('lodash');
var express = require('express');
var wsocket = require('./wsocket');
var app = express()
app.use(require('body-parser').json())

router.post('/auth/project',createProject);
router.get('/auth/project',myProjects);
router.get('/auth/project/user/:userId',userProjects);
router.get('/auth/project/:projectId',projectDetails);
router.post('/auth/project/update',updateProject);
function createProject(req, res, next) {
    var project = new Project({
        title: req.body.title,
        Description: req.body.description,
        createdBy: req.user,
        status: req.body.status,
        members: {userId:req.user}
    })
    console.log(project);
    project.save(function (err, proj) {
        if (err) {
            console.log(err);
            next(err);
        }
      //  wsocket.broadcast([req.user],'project:new:A new project was created');
        console.log(proj);
        //create a new calendar assigned to this project
        var calendar = new Calendar({
            createdBy: req.user,
            title: req.body.title,
            description: req.body.description,
            status: req.body.status,
            project: proj._id
        })
        console.log(calendar);
        calendar.save(function (err, cal) {
            if (err) {
                console.log(err);
                next(err);
            }
            console.log(cal);
        })
        // create a new gantt chart assigned to this project
        var gantt = new Gantt({
            name: req.body.title,
            createdBy: req.user,
            project: proj._id

        })
        console.log(gantt);
        gantt.save(function (err, gantt) {
            if (err) {
                console.log(err);
                next(err);
            }
        })
        // create a budget

        //create a messaging room

        //create a workspace for collaboration
        res.json(proj);
    });
}
function myProjects(req, res, next) {
    console.log(req.user);
    Project.find({members:{$elemMatch:{userId:  req.user}}}, function (err, proj) {
        if (err) {
            console.log(err);
            next(err);
        }
        res.send(proj);
    })
}
function userProjects (req, res, next) {
    Project.find({members:{$elemMatch:{userId:  req.params.user}}},function (err, proj) {
        if (err) {
            next(err);
        }
        res.send(proj);
    })
}
function projectDetails (req, res, next) {
    //check to make sure that req.user has access to the project
    Project.findById(req.params.projectId,function (err, proj) {
        if (err) {
            next(err);
        }
        res.send(proj);
    })
}
function updateProject(req,res,next){
    Project.findByIdAndUpdate( mongoose.Types.ObjectId(req.body.projectId),
    {$addToSet:{'members': {userId:req.body.userId,RACI:req.body.raci}}},
    function(err,result){
        if(err){console.log(err);next(err);}
        res.send(result);
    }
    );
}

module.exports = router;


text:
'use strict';

/* jshint -W110 */
const Utils = require('../../utils');
const DataTypes = require('../../data-types');
const oracleDb = require('oracledb');
const AbstractQueryGenerator = require('../abstract/query-generator');
const _ = require('lodash');
const crc32 = require('js-crc').crc32;
const uuid = require('uuid');
const util = require('util');

//List of Oracle reserved words https://docs.oracle.com/cd/B19306_01/em.102/b40103/app_oracle_reserved_words.htm
const oracleReservedWords = ['ACCESS', 'ACCOUNT', 'ACTIVATE', 'ADD', 'ADMIN', 'ADVISE', 'AFTER', 'ALL', 'ALL_ROWS', 'ALLOCATE', 'ALTER', 'ANALYZE', 'AND', 'ANY', 'ARCHIVE',
  'ARCHIVELOG', 'ARRAY', 'AS', 'ASC', 'AT', 'AUDIT', 'AUTHENTICATED', 'AUTHORIZATION', 'AUTOEXTEND', 'AUTOMATIC', 'BACKUP', 'BECOME', 'BEFORE', 'BEGIN', 'BETWEEN', 'BFILE',
  'BITMAP', 'BLOB', 'BLOCK', 'BODY', 'BY', 'CACHE', 'CACHE_INSTANCES', 'CANCEL', 'CASCADE', 'CAST', 'CFILE', 'CHAINED', 'CHANGE', 'CHAR', 'CHAR_CS', 'CHARACTER', 'CHECK', 'CHECKPOINT',
  'CHOOSE', 'CHUNK', 'CLEAR', 'CLOB', 'CLONE', 'CLOSE', 'CLOSE_CACHED_OPEN_CURSORS', 'CLUSTER', 'COALESCE', 'COLUMN', 'COLUMNS', 'COMMENT', 'COMMIT', 'COMMITTED', 'COMPATIBILITY',
  'COMPILE', 'COMPLETE', 'COMPOSITE_LIMIT', 'COMPRESS', 'COMPUTE', 'CONNECT', 'CONNECT_TIME', 'CONSTRAINT', 'CONSTRAINTS', 'CONTENTS', 'CONTINUE', 'CONTROLFILE', 'CONVERT', 'COST',
  'CPU_PER_CALL', 'CPU_PER_SESSION', 'CREATE', 'CURRENT', 'CURRENT_SCHEMA', 'CURREN_USER', 'CURSOR', 'CYCLE', 'DANGLING', 'DATABASE', 'DATAFILE', 'DATAFILES', 'DATAOBJNO', 'DATE', 'DBA',
  'DBHIGH', 'DBLOW', 'DBMAC', 'DEALLOCATE', 'DEBUG', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DEFERRABLE', 'DEFERRED', 'DEGREE', 'DELETE', 'DEREF', 'DESC', 'DIRECTORY', 'DISABLE', 'DISCONNECT',
  'DISMOUNT', 'DISTINCT', 'DISTRIBUTED', 'DML', 'DOUBLE', 'DROP', 'DUMP', 'EACH', 'ELSE', 'ENABLE', 'END', 'ENFORCE', 'ENTRY', 'ESCAPE', 'EXCEPT', 'EXCEPTIONS', 'EXCHANGE', 'EXCLUDING',
  'EXCLUSIVE', 'EXECUTE', 'EXISTS', 'EXPIRE', 'EXPLAIN', 'EXTENT', 'EXTENTS', 'EXTERNALLY', 'FAILED_LOGIN_ATTEMPTS', 'FALSE', 'FAST', 'FILE', 'FIRST_ROWS', 'FLAGGER', 'FLOAT', 'FLOB',
  'FLUSH', 'FOR', 'FORCE', 'FOREIGN', 'FREELIST', 'FREELISTS', 'FROM', 'FULL', 'FUNCTION', 'GLOBAL', 'GLOBALLY', 'GLOBAL_NAME', 'GRANT', 'GROUP', 'GROUPS', 'HASH', 'HASHKEYS', 'HAVING',
  'HEADER', 'HEAP', 'IDENTIFIED', 'IDGENERATORS', 'IDLE_TIME', 'IF', 'IMMEDIATE', 'IN', 'INCLUDING', 'INCREMENT', 'INDEX', 'INDEXED', 'INDEXES', 'INDICATOR', 'IND_PARTITION', 'INITIAL',
  'INITIALLY', 'INITRANS', 'INSERT', 'INSTANCE', 'INSTANCES', 'INSTEAD', 'INT', 'INTEGER', 'INTERMEDIATE', 'INTERSECT', 'INTO', 'IS', 'ISOLATION', 'ISOLATION_LEVEL', 'KEEP', 'KEY', 'KILL',
  'LABEL', 'LAYER', 'LESS', 'LEVEL', 'LIBRARY', 'LIKE', 'LIMIT', 'LINK', 'LIST', 'LOB', 'LOCAL', 'LOCK', 'LOCKED', 'LOG', 'LOGFILE', 'LOGGING', 'LOGICAL_READS_PER_CALL',
  'LOGICAL_READS_PER_SESSION', 'LONG', 'MANAGE', 'MASTER', 'MAX', 'MAXARCHLOGS', 'MAXDATAFILES', 'MAXEXTENTS', 'MAXINSTANCES', 'MAXLOGFILES', 'MAXLOGHISTORY', 'MAXLOGMEMBERS', 'MAXSIZE',
  'MAXTRANS', 'MAXVALUE', 'MIN', 'MEMBER', 'MINIMUM', 'MINEXTENTS', 'MINUS', 'MINVALUE', 'MLSLABEL', 'MLS_LABEL_FORMAT', 'MODE', 'MODIFY', 'MOUNT', 'MOVE', 'MTS_DISPATCHERS', 'MULTISET',
  'NATIONAL', 'NCHAR', 'NCHAR_CS', 'NCLOB', 'NEEDED', 'NESTED', 'NETWORK', 'NEW', 'NEXT', 'NOARCHIVELOG', 'NOAUDIT', 'NOCACHE', 'NOCOMPRESS', 'NOCYCLE', 'NOFORCE', 'NOLOGGING', 'NOMAXVALUE',
  'NOMINVALUE', 'NONE', 'NOORDER', 'NOOVERRIDE', 'NOPARALLEL', 'NOPARALLEL', 'NOREVERSE', 'NORMAL', 'NOSORT', 'NOT', 'NOTHING', 'NOWAIT', 'NULL', 'NUMBER', 'NUMERIC', 'NVARCHAR2', 'OBJECT',
  'OBJNO', 'OBJNO_REUSE', 'OF', 'OFF', 'OFFLINE', 'OID', 'OIDINDEX', 'OLD', 'ON', 'ONLINE', 'ONLY', 'OPCODE', 'OPEN', 'OPTIMAL', 'OPTIMIZER_GOAL', 'OPTION', 'OR', 'ORDER', 'ORGANIZATION',
  'OSLABEL', 'OVERFLOW', 'OWN', 'PACKAGE', 'PARALLEL', 'PARTITION', 'PASSWORD', 'PASSWORD_GRACE_TIME', 'PASSWORD_LIFE_TIME', 'PASSWORD_LOCK_TIME', 'PASSWORD_REUSE_MAX', 'PASSWORD_REUSE_TIME',
  'PASSWORD_VERIFY_FUNCTION', 'PCTFREE', 'PCTINCREASE', 'PCTTHRESHOLD', 'PCTUSED', 'PCTVERSION', 'PERCENT', 'PERMANENT', 'PLAN', 'PLSQL_DEBUG', 'POST_TRANSACTION', 'PRECISION', 'PRESERVE',
  'PRIMARY', 'PRIOR', 'PRIVATE', 'PRIVATE_SGA', 'PRIVILEGE', 'PRIVILEGES', 'PROCEDURE', 'PROFILE', 'PUBLIC', 'PURGE', 'QUEUE', 'QUOTA', 'RANGE', 'RAW', 'RBA', 'READ', 'READUP', 'REAL', 'REBUILD',
  'RECOVER', 'RECOVERABLE', 'RECOVERY', 'REF', 'REFERENCES', 'REFERENCING', 'REFRESH', 'RENAME', 'REPLACE', 'RESET', 'RESETLOGS', 'RESIZE', 'RESOURCE', 'RESTRICTED', 'RETURN', 'RETURNING',
  'REUSE', 'REVERSE', 'REVOKE', 'ROLE', 'ROLES', 'ROLLBACK', 'ROW', 'ROWID', 'ROWNUM', 'ROWS', 'RULE', 'SAMPLE', 'SAVEPOINT', 'SB4', 'SCAN_INSTANCES', 'SCHEMA', 'SCN', 'SCOPE', 'SD_ALL',
  'SD_INHIBIT', 'SD_SHOW', 'SEGMENT', 'SEG_BLOCK', 'SEG_FILE', 'SELECT', 'SEQUENCE', 'SERIALIZABLE', 'SESSION', 'SESSION_CACHED_CURSORS', 'SESSIONS_PER_USER', 'SET', 'SHARE', 'SHARED',
  'SHARED_POOL', 'SHRINK', 'SIZE', 'SKIP', 'SKIP_UNUSABLE_INDEXES', 'SMALLINT', 'SNAPSHOT', 'SOME', 'SORT', 'SPECIFICATION', 'SPLIT', 'SQL_TRACE', 'STANDBY', 'START', 'STATEMENT_ID',
  'STATISTICS', 'STOP', 'STORAGE', 'STORE', 'STRUCTURE', 'SUCCESSFUL', 'SWITCH', 'SYS_OP_ENFORCE_NOT_NULL$', 'SYS_OP_NTCIMG$', 'SYNONYM', 'SYSDATE', 'SYSDBA', 'SYSOPER', 'SYSTEM', 'TABLE',
  'TABLES', 'TABLESPACE', 'TABLESPACE_NO', 'TABNO', 'TEMPORARY', 'THAN', 'THE', 'THEN', 'THREAD', 'TIMESTAMP', 'TIME', 'TO', 'TOPLEVEL', 'TRACE', 'TRACING', 'TRANSACTION', 'TRANSITIONAL',
  'TRIGGER', 'TRIGGERS', 'TRUE', 'TRUNCATE', 'TX', 'TYPE', 'UB2', 'UBA', 'UID', 'UNARCHIVED', 'UNDO', 'UNION', 'UNIQUE', 'UNLIMITED', 'UNLOCK', 'UNRECOVERABLE', 'UNTIL', 'UNUSABLE', 'UNUSED',
  'UPDATABLE', 'UPDATE', 'USAGE', 'USE', 'USER', 'USING', 'VALIDATE', 'VALIDATION', 'VALUE', 'VALUES', 'VARCHAR', 'VARCHAR2', 'VARYING', 'VIEW', 'WHEN', 'WHENEVER', 'WHERE', 'WITH', 'WITHOUT',
  'WORK', 'WRITE', 'WRITEDOWN', 'WRITEUP', 'XID', 'YEAR', 'ZONE'];

/* istanbul ignore next */
const throwMethodUndefined = function (methodName) {
  throw new Error('The method "' + methodName + '" is not defined! Please add it to your sql dialect.');
};

const QueryGenerator = {
  __proto__: AbstractQueryGenerator,
  options: {},
  dialect: 'oracle',

   /**
   * Warning oracle schema ≠ mssql schema or postgres schema DO NOT USE
   */
  createSchema(schema) {
    return 'SELECT USERNAME AS "schema_name" FROM ALL_USERS WHERE ORACLE_MAINTAINED = (\'N\') AND USERNAME != user';
  },

  /**
   * Warning oracle schema ≠ mssql schema or postgres schema
   */
  showSchemasQuery() {
    return 'SELECT USERNAME AS "schema_name" FROM ALL_USERS WHERE ORACLE_MAINTAINED = (\'N\') AND USERNAME != user';
  },

  /**
   * Warning oracle schema ≠ mssql schema or postgres schema
   */
  dropSchema(tableName) {
    return 'SELECT USERNAME AS "schema_name" FROM ALL_USERS WHERE ORACLE_MAINTAINED = (\'N\') AND USERNAME != user';
  },

  // We take the specified schema delimiter or '_' by default
  addSchema(param) {

    if (!param._schema) return param.tableName || param;

    const schema = super.addSchema(param);
    schema.delimiter = param._schemaDelimiter || '_';
    return schema;
  },

  versionQuery() {
    return 'SELECT VERSION FROM PRODUCT_COMPONENT_VERSION WHERE PRODUCT LIKE \'Oracle%\'';
  },

  createTableQuery(tableName, attributes, options) {
    let query = 'CREATE TABLE <%= table %> (<%= attributes %>)';
    const completeQuery = "BEGIN EXECUTE IMMEDIATE '<%= createTableQuery %>'; EXCEPTION WHEN OTHERS THEN IF SQLCODE != -955 THEN RAISE; END IF; END;",
      self = this;
    const primaryKeys = [], foreignKeys = {}, attrStr = [], checkStr = [];

    const values = {
      table: this.quoteTable(tableName)
    };

    const regex = /REFERENCES ([a-zA-Z_.0-9]*) \((.*)\)/g; //Global regex
    const chkRegex = /CHECK \(([a-zA-Z_.0-9]*) (.*)\)/g; //Check regex
    const jsonRegex = /ISJSON \(([a-zA-Z_.0-9]*) (.*)\)/g; //Check regex

    //Starting by dealing with all attributes
    for (let attr in attributes) {
      if (attributes.hasOwnProperty(attr)) {
        const dataType = attributes[attr];
        let match;

        attr = this.quoteIdentifier(attr);

        // ORACLE doesn't support inline REFERENCES declarations: move to the end
        if (_.includes(dataType, 'PRIMARY KEY')) {
          //Primary key
          primaryKeys.push(attr);
          if (_.includes(dataType, 'REFERENCES')) {
            match = dataType.match(/^(.+) (REFERENCES.*)$/);
            attrStr.push(attr + ' ' + match[1].replace(/PRIMARY KEY/, ''));

            foreignKeys[attr] = match[2].replace(regex, (match, table, column) => {
              //We don't want the table name to be quoted if we pass the schema name
              let tableName = '';
              if (_.isPlainObject(table)) {
                if (table.schema) {
                  tableName = this.quoteTable(table.schema) + '.';
                }
                tableName += this.quoteTable(table.tableName);
              } else {
                tableName = _.includes(oracleReservedWords, table.toUpperCase()) ? '"' + table + '"' : table;
              }

              return `REFERENCES ${tableName} (${this.quoteIdentifier(column)})`;
            });
          } else {
            attrStr.push(attr + ' ' + dataType.replace(/PRIMARY KEY/, '').trim());
          }

        } else if (_.includes(dataType, 'REFERENCES')) {

          //Foreign key
          match = dataType.match(/^(.+) (REFERENCES.*)$/);
          attrStr.push(attr + ' ' + match[1]);

          foreignKeys[attr] = match[2].replace(regex, (match, table, column) => {
            //We don't want the table name to be quoted if we pass the schema name
            let tableName = '';
            if (_.isPlainObject(table)) {
              if (table.schema) {
                tableName = this.quoteTable(table.schema) + '.';
              }
              tableName += this.quoteTable(table.tableName);
            } else {
              tableName = _.includes(oracleReservedWords, table.toUpperCase()) ? '"' + table + '"' : table;
            }
            return `REFERENCES ${tableName} (${this.quoteIdentifier(column)})`;
          });
        } else if (_.includes(dataType, 'CHECK')) {
          //Check constraints go to the end
          match = dataType.match(/^(.+) (CHECK.*)$/);
          attrStr.push(attr + ' ' + match[1]);
          match[2] = match[2].replace('ATTRIBUTENAME', attr);
          const checkCond = match[2].replace(chkRegex, (match, column, condition) => {
            return `CHECK (${this.quoteIdentifier(column)} ${condition})`;
          });

          checkStr.push(checkCond);
        } else if (_.includes(dataType, 'ISJSON')) {
          //Check constraints go to the end
          match = dataType.match(/^(.+) (ISJSON.*)$/);
          attrStr.push(attr + ' ' + match[1]);

          const checkCond = `CONSTRAINT ${tableName}_${attr}_isjson_chk CHECK( ${attr} IS JSON)`;

          checkStr.push(checkCond);
        } else {
          attrStr.push(attr + ' ' + dataType);
        }
      }
    }

    values['attributes'] = attrStr.join(', ');

    const pkString = primaryKeys.map((pk => {
      return this.quoteIdentifier(pk);
    }).bind(this)).join(', ');

    if (pkString.length > 0) {

      let primaryKeyName = `PK${values.table}${pkString}`.replace(/[.,"\s]/g, ''); //We replace the space if there are multiple columns

      //Oracle doesn't support names with more that 32 characters, so we replace it by PK CRC32
      if (primaryKeyName.length > 30) {
        primaryKeyName = `PK${values.table}${crc32(pkString)}`.replace(/[.,"\s]/g, '');
        if (primaryKeyName.length > 30) {
          const crcName = crc32(`${values.table}_${pkString}`);
          primaryKeyName = `PK${crcName}`.replace(/[.,"\s]/g, '');
        }
      }

      values.attributes += ',CONSTRAINT ' + primaryKeyName + ' PRIMARY KEY (' + pkString + ')';
    }

    //Dealing with FKs
    for (const fkey in foreignKeys) {
      if (foreignKeys.hasOwnProperty(fkey)) {

        //Oracle default response for FK, doesn't support if defined
        if (foreignKeys[fkey].indexOf('ON DELETE NO ACTION') > - 1) {
          foreignKeys[fkey] = foreignKeys[fkey].replace('ON DELETE NO ACTION', '');
        }

        let fkName = `FK${values.table}${fkey}`.replace(/[."]/g, '');
        //Oracle doesn't support names with more that 32 characters, so we replace it by FK CRC(columns)
        if (fkName.length > 30) {
          fkName = `FK${values.table}${crc32(fkey)}`.replace(/[."]/g, '');
          //If the name is still too long (table name very long), we generate only FK CRC(table_columns)
          if (fkName.length > 30) {
            const crcName = crc32(`${values.table}_${fkey}`);
            fkName = `FK${crcName}`.replace(/[."]/g, '');
          }
        }

        values.attributes += ',CONSTRAINT ' + fkName + ' FOREIGN KEY (' + this.quoteIdentifier(fkey) + ') ' + foreignKeys[fkey];
      }
    }

    if (checkStr.length > 0) {
      values.attributes += ', ' + checkStr.join(', ');
    }

    //Specific case for unique indexes with Oracle, we have to set the constraint on the column, if not, no FK will be possible (ORA-02270: no matching unique or primary key for this column-list)
    if (options && options.indexes && options.indexes.length > 0) {

      const idxToDelete = [];
      options.indexes.forEach((index, idx) => {
        if ('unique' in index && (index.unique === true || (index.unique.length > 0 && index.unique !== false))) {
          //If unique index, transform to unique constraint on column
          const fields = index.fields.map(field => {
            if (typeof field === 'string') {
              return field;
            } else {
              return field.attribute;
            }
          });

          //Now we have to be sure that the constraint isn't already declared in uniqueKeys
          let canContinue = true;
          if (options.uniqueKeys) {
            const keys = Object.keys(options.uniqueKeys);

            for (let fieldIdx = 0; fieldIdx < keys.length; fieldIdx++) {
              const currUnique = options.uniqueKeys[keys[fieldIdx]];

              if (currUnique.fields.length === fields.length) {
                //lengths are the same, possible same constraint
                for (let i = 0; i < currUnique.fields.length; i++) {
                  const field = currUnique.fields[i];

                  if (_.includes(fields, field)) {
                    canContinue = false;
                  } else {
                    //We have at least one different column, even if we found the same columns previously, we let the constraint be created
                    canContinue = true;
                    break;
                  }
                }
              }
            }

            if (canContinue) {
              let indexName = 'name' in index ? index.name : '';

              if (indexName === '' || indexName.length > 30) {
                indexName = this._generateUniqueConstraintName(values.table, fields);
              }
              const constraintToAdd = {
                name: indexName,
                fields
              };
              if (!('uniqueKeys' in options)) {
                options.uniqueKeys = {};
              }

              options.uniqueKeys[indexName] = constraintToAdd;
              idxToDelete.push(idx);
            } else {
              //The constraint already exists, we remove it from the list
              idxToDelete.push(idx);
            }
          }
        }
      });
      idxToDelete.forEach(idx => {
        options.indexes.splice(idx, 1);
      });
    }

    if (options && !!options.uniqueKeys) {
      _.each(options.uniqueKeys, (columns, indexName) => {
        let canBeUniq = false;

        //Check if we can create the unique key
        primaryKeys.forEach(primaryKey => {
          //We can create an unique constraint if it's not on the primary key AND if it doesn't have unique in its definition

          if (!_.includes(columns.fields, primaryKey)) {
            canBeUniq = true;
          }
        });

        columns.fields.forEach(field => {
          let currField = '';
          if (!_.isString(field)) {
            currField = field.attribute.replace(/[.,"\s]/g, '');
          } else {
            currField = field.replace(/[.,"\s]/g, '');
          }
          if (currField in attributes) {
            if (attributes[currField].toUpperCase().indexOf('UNIQUE') > -1) {
              //We generate the attribute without UNIQUE
              const attrToReplace = attributes[currField].replace('UNIQUE', '');
              //We replace in the final string
              values.attributes = values.attributes.replace(attributes[currField], attrToReplace);
            }
          }
        });

        //Oracle cannot have an unique AND a primary key on the same fields, prior to the primary key
        if (canBeUniq) {
          if (!_.isString(indexName)) {
            indexName = this._generateUniqueConstraintName(values.table, columns.fields);
          }

          //Oracle doesn't support names with more that 32 characters, so we replace it by PK timestamp
          if (indexName.length > 30) {
            indexName = this._generateUniqueConstraintName(values.table, columns.fields);
          }

          const indexUpperName = indexName.toUpperCase();

          if (_.includes(oracleReservedWords, indexUpperName) || indexUpperName.charAt(0) === '_') {
            indexName = '"' + indexName + '"';
          }

          const index = options.uniqueKeys[columns.name];
          delete options.uniqueKeys[columns.name];
          indexName = indexName.replace(/[.,\s]/g, '');
          columns.name = indexName;
          options.uniqueKeys[indexName] = index;
          values.attributes += ', CONSTRAINT ' + indexName + ' UNIQUE (' + _.map(columns.fields, self.quoteIdentifier).join(', ') + ')';
        }
      });
    }

    query = _.template(query)(values).trim();
    //we replace single quotes by two quotes in order for the execute statement to work
    query = query.replace(/'/g, "''");
    values.createTableQuery = query;

    return _.template(completeQuery)(values).trim();
  },

  /**
   * Generates a name for an unique constraint with the pattern : uniqTABLENAMECOLUMNNAMES
   * If this indexName is too long for Oracle, it's hashed to have an acceptable length
   */
  _generateUniqueConstraintName(table, columns) {

    let indexName = `uniq${table}${columns.join('')}`.replace(/[.,"\s]/g, '').toLowerCase();

    //Oracle doesn't support names with more that 32 characters, so we replace it by PK timestamp
    if (indexName.length > 30) {
      indexName = `uniq${table}${crc32(columns.join(''))}`.replace(/[.,"\s]/g, '').toLowerCase();

      if (indexName.length > 30) {
        const crcName = crc32(`${table}_${columns.join('')}`);
        indexName = `uniq${crcName}`.replace(/[.,"\s]/g, '').toLowerCase();
      }
    }

    return indexName;
  },

  describeTableQuery(tableName, schema, schemaDelimiter) {
    //name, type, datalength (except number / nvarchar), datalength varchar, datalength number, nullable, default value, primary ?
    const sql = ['SELECT atc.COLUMN_NAME, atc.DATA_TYPE, atc.DATA_DEFAULT, atc.DATA_LENGTH, atc.CHAR_LENGTH, atc.DEFAULT_LENGTH, atc.NULLABLE, ',
      'CASE WHEN ucc.CONSTRAINT_NAME  LIKE \'%PK%\' THEN \'PRIMARY\' ELSE \'\' END AS "PRIMARY" ',
      'FROM all_tab_columns atc ',
      'LEFT OUTER JOIN all_cons_columns ucc ON(atc.TABLE_NAME = ucc.TABLE_NAME AND atc.COLUMN_NAME = ucc.COLUMN_NAME and atc.OWNER = ucc.OWNER ) ',
      'WHERE atc.OWNER=(SELECT USER FROM DUAL) ',
      'AND (atc.TABLE_NAME=UPPER(\'<%= tableName %>\') OR atc.TABLE_NAME=\'<%= tableName %>\')',
      ' ORDER BY "PRIMARY", atc.COLUMN_NAME'].join('');

    let currTableName = _.isPlainObject(tableName) ? tableName.tableName : tableName;
    currTableName = schema ? schemaDelimiter ? schema + schemaDelimiter + currTableName : schema + '_' + currTableName : currTableName
    const values = {
      tableName: currTableName,
      schema
    };

    return _.template(sql)(values).trim();
  },

    /**
     * Generates an SQL query that extract JSON property of given path.
     *
     * @param   {String}               column  The JSON column
     * @param   {String|Array<String>} [path]  The path to extract (optional)
     * @returns {String}                       The generated sql query
     * @private
     */
    jsonPathExtractionQuery(column, path) {
      const paths = _.toPath(path).map( f => {
        if (/^\w+$/.test(f) === false) {
          return `"${f}"`;
        } else {
          return f;
        }
      });
      const pathStr = this.escape(['$']
        .concat(paths)
        .join('.')
        .replace(/\.(\d+)(?:(?=\.)|$)/g, (_, digit) => `[${digit}]`));

      // const quotedColumn = this.isIdentifierQuoted(column) ? column : this.quoteIdentifier(column);
      return `JSON_VALUE(${column}, ${pathStr})`;
    },

  //Manque la méthode pour gérer le JSON depuis un WHERE
  handleSequelizeMethod(smth, tableName, factory, options, prepend) {
    if (smth instanceof Utils.Json) {
      // Parse nested object
      if (smth.conditions) {
        const conditions = _.map(this.parseConditionObject(smth.conditions), condition =>
          `JSON_VALUE(${this.quoteIdentifier(_.first(condition.path))}, '\$.${_.tail(condition.path).join('.')}') = '${condition.value}'`
        );

        return conditions.join(' and ');
      } else if (smth.path) {
        let str;

        // Allow specifying conditions using the sqlite json functions
        if (this._checkValidJsonStatement(smth.path)) {
          str = smth.path;
        } else {
          // Also support json dot notation
          let path = smth.path;
          let startWithDot = true;

          // Convert .number. to [number].
          path = path.replace(/\.(\d+)\./g, '[$1].');
          // Convert .number$ to [number]
          path = path.replace(/\.(\d+)$/, '[$1]');

          path = path.split('.');
          let columnName = path.shift();

          const match = columnName.match(/\[\d+\]$/);
          // If columnName ends with [\d+]
          if (match !== null) {
            path.unshift(columnName.substr(match.index));
            columnName = columnName.substr(0, match.index);
            startWithDot = false;
          }

          str = `JSON_VALUE(${this.quoteIdentifier(columnName)}, '\$${startWithDot ? '.' : ''}${path.join('.')}')`;
        }

        if (smth.value) {
          str += util.format(' = %s', this.escape(smth.value));
        }

        return str;
      }
    } /*else if (smth instanceof Utils.Cast) {
      if (/timestamp/i.test(smth.type)) {
        smth.type = 'datetimeoffset';
      } else if (smth.json && /boolean/i.test(smth.type)) {
        // true or false cannot be casted as booleans within a JSON structure
        smth.type = 'char';
      } else if (/boolean/i.test(smth.type)) {
        smth.type = 'bit';
      } else if (/integer/i.test(smth.type)) {
        smth.type = 'integer';
      } else if (/double precision/i.test(smth.type)) {
        smth.type = 'decimal';
      } else if (/text/i.test(smth.type)) {
        smth.type = 'char';
      }
    }*/

    return super.handleSequelizeMethod(smth, tableName, factory, options, prepend);
  },

   /**
     * Check whether the statmement is json function or simple path
     *
     * @param   {String}  stmt  The statement to validate
     * @returns {Boolean}       true if the given statement is json function
     * @throws  {Error}         throw if the statement looks like json function but has invalid token
     * @private
     */
    _checkValidJsonStatement(stmt) {
      if (!_.isString(stmt)) {
        return false;
      }

      const jsonFunctionRegex = /^\s*((?:[a-z]+_){0,2}jsonb?(?:_[a-z]+){0,2})\([^)]*\)/i;
      const jsonOperatorRegex = /^\s*(->>?|@>|<@|\?[|&]?|\|{2}|#-)/i;
      const tokenCaptureRegex = /^\s*((?:([`"'])(?:(?!\2).|\2{2})*\2)|[\w\d\s]+|[().,;+-])/i;

      let currentIndex = 0;
      let openingBrackets = 0;
      let closingBrackets = 0;
      let hasJsonFunction = false;
      let hasInvalidToken = false;

      while (currentIndex < stmt.length) {
        const string = stmt.substr(currentIndex);
        const functionMatches = jsonFunctionRegex.exec(string);
        if (functionMatches) {
          currentIndex += functionMatches[0].indexOf('(');
          hasJsonFunction = true;
          continue;
        }

        const operatorMatches = jsonOperatorRegex.exec(string);
        if (operatorMatches) {
          currentIndex += operatorMatches[0].length;
          hasJsonFunction = true;
          continue;
        }

        const tokenMatches = tokenCaptureRegex.exec(string);
        if (tokenMatches) {
          const capturedToken = tokenMatches[1];
          if (capturedToken === '(') {
            openingBrackets++;
          } else if (capturedToken === ')') {
            closingBrackets++;
          } else if (capturedToken === ';') {
            hasInvalidToken = true;
            break;
          }
          currentIndex += tokenMatches[0].length;
          continue;
        }

        break;
      }

      // Check invalid json statement
      hasInvalidToken |= openingBrackets !== closingBrackets;
      if (hasJsonFunction && hasInvalidToken) {
        throw new Error('Invalid json statement: ' + stmt);
      }

      // return true if the statement has valid json function
      return hasJsonFunction;
    },

  renameTableQuery(before, after) {
    const query = 'ALTER TABLE <%= before %> RENAME TO <%= after %>';
    return _.template(query)({
      before : this.quoteTable(before),
      after : this.quoteTable(after)
    });
  },

  showConstraintsQuery(tableName) {
    return `SELECT constraint_name "constraintName", constraint_type "constraintType" , column_name "columnName" from user_constraints natural join user_cons_columns where table_name = '${tableName.toUpperCase()}'`;
  },

  showTablesQuery() {
    return 'SELECT owner as table_schema, table_name, 0 as lvl FROM all_tables where OWNER IN (SELECT USER FROM DUAL)';
  },

  dropTableQuery(tableName) {
    let table = '';
    table = this.quoteTable(tableName);

    const query = [
      'BEGIN ',
      'EXECUTE IMMEDIATE \'DROP TABLE <%= table %> CASCADE CONSTRAINTS PURGE\';',
      ' EXCEPTION WHEN OTHERS THEN IF SQLCODE != -942 THEN',
      ' RAISE; END IF;',
      'END;'];

    const values = {
      table
    };

    return _.template(query.join(''))(values).trim();
  },

  addConstraintQuery(tableName, options) {
    options = options || {};

    //Oracle doesn't support On update
    delete options.onUpdate;
    const constraintSnippet = this.getConstraintSnippet(tableName, options);

    if (typeof tableName === 'string') {
      tableName = this.quoteIdentifiers(tableName);
    } else {
      tableName = this.quoteTable(tableName);
    }

    return `ALTER TABLE ${tableName} ADD ${constraintSnippet}`;
  },

  addColumnQuery(table, key, dataType) {
    dataType.field = key;

    const query = 'ALTER TABLE <%= table %> ADD (<%= attribute %>)'
      , attribute = _.template('<%= key %> <%= definition %>')({
        key : this.quoteIdentifier(key),
        definition: this.attributeToSQL(dataType, {
          context: 'addColumn',
          tableName: table,
          attr: key
        }).replace('ATTRIBUTENAME', key).replace(/'/g, "'")
      });

    return _.template(query)({
      table: this.quoteTable(table),
      attribute
    });
  },

  removeColumnQuery(tableName, attributeName) {
    const query = 'ALTER TABLE <%= tableName %> DROP COLUMN <%= attributeName %>';

    return _.template(query)({
      tableName: this.quoteTable(tableName),
      attributeName : this.quoteIdentifier(attributeName)
    });
  },

  changeColumnQuery(tableName, attributes) {
    const modifyQuery = 'ALTER TABLE <%= tableName %> MODIFY (<%= query %>)';
    const alterQuery = 'ALTER TABLE <%= tableName %> <%= query %>';
    let query = '';
    const attrString = [], constraintString = [];

    for (const attributeName in attributes) {
      let definition = attributes[attributeName];
      if (definition.match(/REFERENCES/)) {
        constraintString.push(_.template('<%= fkName %> FOREIGN KEY (<%= attrName %>) <%= definition %>')({
          fkName: attributeName + '_foreign_idx',
          attrName: attributeName,
          definition: definition.replace(/.+?(?=REFERENCES)/, '')
        }));
      } else {
        attrString.push(_.template('<%= attrName %> <%= definition %>')({
          attrName: attributeName,
          definition
        }));
      }
    }

    let fullQuery = 'BEGIN '
      + 'EXECUTE IMMEDIATE \'<%= fullQuery %>\';'
      + ' EXCEPTION'
      + ' WHEN OTHERS THEN'
      + ' IF SQLCODE = -1442 OR SQLCODE = -1451 THEN'
      + ' EXECUTE IMMEDIATE \'<%= secondQuery %>\';' //We execute the statement without the NULL / NOT NULL clause if the first statement failed due to this
      + ' ELSE'
      + ' RAISE;'
      + ' END IF;'
      + ' END;';

    let finalQuery = '';
    if (attrString.length) {
      finalQuery += attrString.join(', ');
      finalQuery += constraintString.length ? ' ' : '';
    }
    if (constraintString.length) {
      finalQuery += 'ADD CONSTRAINT ' + constraintString.join(', ');
      //Here, we don't use modify
      query = alterQuery;
    } else {
      query = modifyQuery;
    }

    query = _.template(query)({
      tableName: this.quoteTable(tableName),
      query: finalQuery
    });

    //we replace single quotes by two quotes in order for the execute statement to work
    query = query.replace(/'/g, "''");

    //Oracle doesn't support if we try to define a NULL / NOT NULL column if it is already in this case
    //see https://docs.oracle.com/cd/B28359_01/server.111/b28278/e900.htm#ORA-01451
    //if we have a default null we keep it
    const secondQuery = query.replace('DEFAULT NULL', 'REPLACEDEFAULTVAL').replace('NOT NULL', '').replace('NULL', '').replace('REPLACEDEFAULTVAL', 'DEFAULT NULL');

    return fullQuery = _.template(fullQuery)({
      fullQuery: query,
      secondQuery
    });
  },

  renameColumnQuery(tableName, attrBefore, attributes) {
    const query = 'ALTER TABLE <%= tableName %> RENAME COLUMN <%= before %> TO <%= after %>'
      , newName = Object.keys(attributes)[0];

    return _.template(query)({
      tableName: this.quoteTable(tableName),
      before: this.quoteIdentifier(attrBefore),
      after: this.quoteIdentifier(newName)
    });
  },

  /**
   * Override of upsertQuery, Oracle specific
   * Using PL/SQL for finding the row
   */
  upsertQuery(tableName, insertValues, updateValues, where, model, options) {
    const rawAttributes = model.rawAttributes;
    const sql = [
      'DECLARE ',
      'CURSOR findingRow IS ',
      `SELECT * FROM ${this.quoteTable(tableName)}`,
      where !== null && where !== undefined ? ' ' + this.whereQuery(where, options) : '',
      '; firstRow findingRow%ROWTYPE;',
      'BEGIN ',
      'OPEN findingRow; ',
      'FETCH findingRow INTO firstRow; ',
      'IF findingRow%FOUND THEN ',
      this.updateQuery(tableName, updateValues, where, options, rawAttributes),
      '; $:isUpdate;NUMBER$ := 2; ',
      'ELSE ',
      this.insertQuery(tableName, insertValues, rawAttributes, options),
      '; $:isUpdate;NUMBER$ := 1; ',
      'END IF; ',
      'CLOSE findingRow; ',
      'END;'
    ];

    return sql.join('');
  },

  /*
  * Override of insertQuery, Oracle specific
  */
  insertQuery(table, valueHash, modelAttributes, options) {
    options = options || {};
    _.defaults(options, this.options);

    const valueQuery = 'INSERT INTO <%= table %> (<%= attributes %>) VALUES (<%= values %>)'
      , emptyQuery = 'INSERT INTO <%= table %> VALUES (DEFAULT)'
      , fields = []
      , values = []
      , primaryKeys = []
      , modelAttributeMap = {}
      , realTableName = this.quoteTable(table)
      , primaryKeyReturn = [];
    let key
      , query
      , value;
    const inputParameters = {};
    let inputParamCpt = 0;

    //We have to specify a variable that will be used as return value for the id
    const returningQuery = '<%=valueQuery %> RETURNING <%=primaryKey %> INTO <%=primaryKeyReturn %>';

    if (modelAttributes) {

      //We search for the primaryKey
      const keys = Object.keys(modelAttributes);
      let idx = 0;

      while (idx < keys.length) {
        const AttributeKey = keys[idx];
        const modelAttribute = modelAttributes[AttributeKey];
        if (modelAttribute.primaryKey) {
          primaryKeys.push(modelAttribute);

        }
        idx++;
      }

      _.each(modelAttributes, (attribute, key) => {
        modelAttributeMap[key] = attribute;
        if (attribute.field) {
          modelAttributeMap[attribute.field] = attribute;
        }
      });
    }

    valueHash = Utils.removeNullValuesFromHash(valueHash, this.options.omitNull);
    for (key in valueHash) {
      if (valueHash.hasOwnProperty(key)) {
        value = valueHash[key];
        fields.push(this.quoteIdentifier(key));

        if (modelAttributeMap && modelAttributeMap[key] && modelAttributeMap[key].autoIncrement === true && !value) {
          values.push('DEFAULT');

        } else {
          if (modelAttributeMap && modelAttributeMap[key] && !modelAttributeMap[key].allowNull && (value != null && value && !(value instanceof Array) && value.length === 0)) {
            //Oracle refuses an insert in not null column with empty value (considered as null)
            value = ' ';
          }
          const currAttribute = modelAttributeMap[key];
          if (currAttribute && currAttribute.type != null && (currAttribute.type.key === DataTypes.TEXT.key || currAttribute.type.key === DataTypes.BLOB.key)) {
            //If we try to insert into TEXT or BLOB, we need to pass by input-parameters to avoid the 4000 char length limit
            //Gestion de l'utilisation des binding dans la fonction execute d'oracle-db (pour les CLOB etc ...)
            const paramName = this._handleBindingParameters(key, inputParamCpt, valueHash, modelAttributes, inputParameters);
            values.push(paramName);
          } else {
            // return this.escape(value) + ' AS "' + key + '"';
            values.push(this.escape(value, (modelAttributeMap && modelAttributeMap[key]) || undefined, { context: 'INSERT' }));
          }
        }
      }
    }

    if (Object.keys(inputParameters).length > 0) {
      options.inputParameters = inputParameters;
    }

    let primaryKey = '';

    primaryKeys.forEach(element => {
      if (element.field.toLowerCase() === 'uid') {
        primaryKey += primaryKey.length > 0 ? ',"uid"' : '"uid"';

        const pkReturn = `$:pkReturnVal;${element.type.toSql()}$`;
        primaryKeyReturn.push(pkReturn);
      } else {
        primaryKey += primaryKey.length > 0 ? ',' + this.quoteIdentifier(element.field) : this.quoteIdentifier(element.field);
        const pkReturn = `$:${element.field};${element.type.toSql()}$`;
        primaryKeyReturn.push(pkReturn);
      }
    });

    //If we want a return AND we haven't specified a primary key in the column list
    if (options.returning && primaryKey === '') {
      const tableKeys = Object.keys(this.sequelize.models);
      const currTableName = _.isPlainObject(table) ? table.tableName : table;

      const currentModelKey = tableKeys.find(modelKey => {
        return this.sequelize.models[modelKey].tableName === currTableName;
      });

      const currentModel = this.sequelize.models[currentModelKey];
      if ((!currentModel || !currentModel.hasPrimaryKeys) && modelAttributes) {
        //We don't have a primaryKey, so we will return the first column inserted
        let field = modelAttributes[Object.keys(modelAttributes)[0]].field;

        if (_.includes(oracleReservedWords, field.toUpperCase())) {
          //The column name we want to return is a reserved word, so we change it for the request to be OK
          field = 'pkReturnVal';
        }
        const pkReturn = `$:${field};string$`;
        primaryKey = this.quoteIdentifier(modelAttributes[Object.keys(modelAttributes)[0]].field);
        primaryKeyReturn.push(pkReturn);
      }
    }

    const replacements = {
      primaryKey,
      primaryKeyReturn: primaryKeyReturn.join(','),
      table: realTableName,
      attributes: fields.join(','),
      values: values.join(',')
    };

    if (options.returning && replacements.attributes && replacements.attributes.length > 0) {
      query = returningQuery;
      replacements.valueQuery = _.template(valueQuery)(replacements);
    } else {
      query = (replacements.attributes.length ? valueQuery : emptyQuery);
    }

    return _.template(query)(replacements);
  },

  /*
  Returns an update query.
  Parameters:
    - tableName -> Name of the table
    - values -> A hash with attribute-value-pairs
    - where -> A hash with conditions (e.g. {name: 'foo'})
                OR an ID as integer
                OR a string with conditions (e.g. 'name="foo"').
                If you use a string, you have to escape it on your own.
  @private
  */
  updateQuery(tableName, attrValueHash, where, options, attributes) {
    options = options || {};
    _.defaults(options, this.options);

    attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, options.omitNull, options);

    const values = [];
    const modelAttributeMap = {};
    let query = '<%= tmpTable %>UPDATE <%= table %> SET <%= values %><%= output %> <%= where %>';
    let outputFragment;
    let tmpTable = '';        // tmpTable declaration for trigger
    const inputParameters = {};
    let inputParamCpt = 0;

    if (this._dialect.supports['LIMIT ON UPDATE'] && options.limit) {

      //This cannot be setted in where because rownum will be quoted
      if (where && ((where.length && where.length > 0) || (Object.keys(where).length > 0))) {
        //If we have a where clause, we add AND
        query += ' AND ';
      } else {
        //No where clause, we add where
        query += ' WHERE ';
      }
      query += `rownum <= ${this.escape(options.limit)} `;
    }

    if (attributes) {
      _.each(attributes, (attribute, key) => {
        modelAttributeMap[key] = attribute;
        if (attribute.field) {
          modelAttributeMap[attribute.field] = attribute;
        }
      });
    }

    for (const key in attrValueHash) {
      if (modelAttributeMap && modelAttributeMap[key] &&
          modelAttributeMap[key].autoIncrement === true &&
          !this._dialect.supports.autoIncrement.update) {
        // not allowed to update identity column
        continue;
      }

      const currAttribute = modelAttributeMap[key];
      if (currAttribute && currAttribute.type != null && (currAttribute.type.key === DataTypes.TEXT.key || currAttribute.type.key === DataTypes.BLOB.key)) {
        //If we try to update into TEXT or BLOB, we need to pass by input-parameters to avoid the 4000 char length limit
        //Gestion de l'utilisation des binding dans la fonction execute d'oracle-db (pour les CLOB etc ...)
        const paramName = this._handleBindingParameters(key, inputParamCpt, attrValueHash, attributes, inputParameters);
        values.push(this.quoteIdentifier(key) + '=' + paramName);
      } else {
        const value = attrValueHash[key];
        values.push(this.quoteIdentifier(key) + '=' + this.escape(value, modelAttributeMap && modelAttributeMap[key] || undefined, { context: 'UPDATE' }));
      }
    }

    if (Object.keys(inputParameters).length > 0) {
      options.inputParameters = inputParameters;
    }

    const replacements = {
      table: this.quoteTable(tableName),
      values: values.join(','),
      output: outputFragment,
      where: this.whereQuery(where, options),
      tmpTable
    };

    if (values.length === 0) {
      return '';
    }

    return _.template(query, this._templateSettings)(replacements).trim();
  },

  _handleBindingParameters(key, inputParamCpt, attrValueHash, attributes, inputParameters) {

    //If we try to insert into TEXT or BLOB, we need to pass by input-parameters to avoid the 4000 char length limit

    const paramName = `:input${key}${inputParamCpt}`;
    const inputParam = {
      // dir : oracleDb.BIND_IN,
      val : attrValueHash[key]
    };
    //Binding type to parameter
    if (attributes[key].type.key === DataTypes.TEXT.key) {
      //if text with length, it's generated as a String inside Oracle,
      if (attributes[key].type._length !== '') {
        inputParam['type'] = oracleDb.STRING;
      } else {
        //No length -> it's a CLOB
        inputParam['type'] = oracleDb.CLOB;
      }
    } else {
      //No TEXT, it's a BLOB
      // inputParam['type'] =  oracleDb.BLOB;
      inputParam['val'] = Buffer.from(inputParam['val']);
    }
    inputParameters[paramName.slice(1, paramName.length)] = inputParam;

    return paramName;
  },

  /**
   * Oracle way to insert multiple rows inside a single statement
   * INSERT ALL INSERT INTO table (column_name1,column_name2)
      with row as (
        SELECT value as "column_name1",value as "column_name2" FROM DUAL UNION ALL
        SELECT value as "column_name1",value as "column_name2" FROM DUAL
      )
    SELECT * FROM row
   * Unfortunately, with version minor 11 and sequences, we can't use this, we have to chain multiple insert queries
   */
  bulkInsertQuery(tableName, attrValueHashes, options, attributes) {
    const query = 'INSERT ALL INTO <%= table %> (<%= attributes %>) WITH rowAttr AS (<%= rows %>) SELECT * FROM rowAttr;'
      , emptyQuery = 'INSERT INTO <%= table %> (<%= attributes %>) VALUES (DEFAULT)'
      , tuples = []
      , allAttributes = [];
    let allQueries = [];
    const inputParameters = {};
    let inputParamCpt = 0;

    // options.model.attributes.memo.type; -> "TEXT"

    _.forEach(attrValueHashes, attrValueHash => {
      // special case for empty objects with primary keys
      const fields = Object.keys(attrValueHash);
      if (fields.length === 1 && attributes[fields[0]].autoIncrement && attrValueHash[fields[0]] === null) {
        allQueries.push(emptyQuery);
        return;
      }

      // normal case
      _.forOwn(attrValueHash, (value, key) => {
        if (allAttributes.indexOf(key) === -1) {
          if (value === null && attributes[key].autoIncrement)
            return;

          allAttributes.push(key);
        }
      });
    });

    //Loop over each row to insert
    if (allAttributes.length > 0) {
      //Loop over each attribute
      _.forEach(attrValueHashes, (attrValueHash, idx, array) => {
        //Generating the row
        let row = 'SELECT ';
        const attrs = allAttributes.map(key => {
          let currAttribute = key in attributes ? attributes[key] : key;
          if (currAttribute === null) {
            //Maybe we should find the attribute by field and not fieldName
            for (const attr in options.model.attributes) {
              const attribute = options.model.attributes[attr];
              if (attribute.field === key) {
                currAttribute = attribute;
                break;
              }
            }
          }
          if (currAttribute && currAttribute.type != null && (currAttribute.type.key === DataTypes.TEXT.key || currAttribute.type.key === DataTypes.BLOB.key)) {
            //If we try to insert into TEXT or BLOB, we need to pass by input-parameters to avoid the 4000 char length limit

            const paramName = `:input${key}${inputParamCpt}`;
            const inputParam = {
              dir : oracleDb.BIND_IN,
              val : attrValueHash[key]
            };
            //Binding type to parameter
            if (options.model.attributes[key].type.key === DataTypes.TEXT.key) {
              //if text with length, it's generated as a String inside Oracle,
              if (options.model.attributes[key].type._length !== '') {
                inputParam['type'] = oracleDb.STRING;
              } else {
                //No length -> it's a CLOB
                inputParam['type'] = oracleDb.CLOB;
              }
            } else {
              //No TEXT, it's a BLOB
              inputParam['type'] =  oracleDb.BLOB;
            }
            inputParameters[paramName.slice(1, paramName.length)] = inputParam;
            return paramName + ' AS "' + key + '"';
          } else if (currAttribute && currAttribute.type != null && (attributes[key].type instanceof DataTypes.JSON || attributes[key].type.key === 'JSON')) {
            return this.escape(JSON.stringify(attrValueHash[key])) + ' AS "' + key + '"';
          } else {
            return this.escape(attrValueHash[key]) + ' AS "' + key + '"';
          }
        }).join(',');
        row += attrs;
        row += idx < array.length - 1 ? ' FROM DUAL UNION ALL' : ' FROM DUAL';
        inputParamCpt++;
        tuples.push(row);
      });
      allQueries.push(query);
      if (Object.keys(inputParameters).length > 0) {
        options.inputParameters = inputParameters;
      }
    } else {
      //If we pass here, we don't have any attribute, just the id, so we take it to place it in the queries
      let queryToLaunch = "DECLARE x NUMBER := 0; BEGIN LOOP EXECUTE IMMEDIATE '";
      queryToLaunch += allQueries[0];
      queryToLaunch += "'; x:= x+1; IF x > ";
      queryToLaunch += (allQueries.length - 1);
      queryToLaunch += ' THEN EXIT; END IF; END LOOP; EXCEPTION WHEN OTHERS THEN IF SQLCODE != -942 THEN RAISE; END IF; END;';

      allQueries = [queryToLaunch];
      allAttributes.push(Object.keys(attrValueHashes[0])[0]);
    }

    const replacements = {
      table: this.quoteTable(tableName),
      attributes: allAttributes.map(attr => {
        return this.quoteIdentifier(attr);
      }).join(','),
      rows: tuples.join(' ')
    };

    return _.template(allQueries.join(';'))(replacements);
  },

  deleteQuery(tableName, where, options, model) {
    options = options || {};

    const table = tableName;
    if (options.truncate === true) {
      // Truncate does not allow LIMIT and WHERE
      return 'TRUNCATE TABLE ' + table;
    }

    where = this.getWhereConditions(where, null, model, options);
    const replacements = {
      table: this.quoteTable(table),
      limit: options.limit,
      where
    };

    let queryTmpl;
    // delete with limit <l> and optional condition <e> on Oracle: DELETE FROM <t> WHERE rowid in (SELECT rowid FROM <t> WHERE <e> AND rownum <= <l>)
    // Note that the condition <e> has to be in the subquery; otherwise, the subquery would select <l> arbitrary rows.
    if (!!options.limit) {
      const whereTmpl = where ? ' AND <%= where %>' : '';
      queryTmpl = 'DELETE FROM <%= table %> WHERE rowid IN (SELECT rowid FROM <%= table %> WHERE rownum <= <%= limit %>' + whereTmpl + ')';
    } else {
      const whereTmpl = where ? ' WHERE <%= where %>' : '';
      queryTmpl = 'DELETE FROM <%= table %>' + whereTmpl;
    }

    return _.template(queryTmpl)(replacements);
  },

  showIndexesQuery(tableName, options) {

    if (_.isPlainObject(tableName)) {
      const schema = tableName.schema ? options && options.delimiter ? tableName.schema + options.delimiter : tableName.schema + '_' : '';
      tableName = schema + tableName.tableName;
    }

    const sql = ['SELECT i.index_name,i.table_name, i.column_name, u.uniqueness, i.descend ',
      'FROM all_ind_columns i ',
      'INNER JOIN all_indexes u ',
      'ON (u.table_name = i.table_name AND u.index_name = i.index_name AND u.owner = i.index_owner) ',
      'WHERE (i.table_name = UPPER(\'<%= tableName %>\') OR i.table_name = \'<%= tableName %>\')',
      'AND u.OWNER = (SELECT USER FROM DUAL)',
      ' ORDER BY INDEX_NAME, COLUMN_NAME'];

    const request = sql.join('');
    return _.template(request)({
      tableName
    });
  },

  removeIndexQuery(tableName, indexNameOrAttributes) {
    const sql = 'DROP INDEX <%= indexName %>';
    let indexName = indexNameOrAttributes;

    if (typeof indexName !== 'string') {
      indexName = Utils.underscore(tableName + '_' + indexNameOrAttributes.join('_'));
    }

    const values = {
      tableName,
      indexName
    };

    return _.template(sql)(values);
  },

  attributeToSQL(attribute, options) {
    if (!_.isPlainObject(attribute)) {
      attribute = {
        type: attribute
      };
    }

    // handle self referential constraints
    if (attribute.references) {

      if (attribute.Model && attribute.Model.tableName === attribute.references.model) {
        this.sequelize.log('Oracle does not support self referencial constraints, '
          + 'we will remove it but we recommend restructuring your query');
        attribute.onDelete = '';
        attribute.onUpdate = '';
      }
    }

    let template;

    if (attribute.type instanceof DataTypes.ENUM) {
      if (attribute.type.values && !attribute.values) attribute.values = attribute.type.values;

      // enums are a special case
      template = attribute.type.toSql();
      template += ' CHECK (ATTRIBUTENAME IN(' + _.map(attribute.values, value => {
        return this.escape(value);
      }).join(', ') + '))';
      return template;
    } else {
      if (attribute.autoIncrement) {
        template = ' NUMBER(*,0) GENERATED BY DEFAULT ON NULL AS IDENTITY';
      } else {
        if (attribute.type && attribute.type.key === DataTypes.DOUBLE.key) {
          template = attribute.type.toSql();
        } else if (attribute.type && attribute.type.key === DataTypes.JSON.key) {
          if (options.context === 'addColumn') {
            template = ` CLOB CONSTRAINT ${options.tableName}_${options.attr}_isjson_chk CHECK( ${options.attr} IS JSON)`;
          } else {
            template = ' CLOB ISJSON';
          }

        } else {
          if (attribute.type) {
            template = attribute.type.toString();
          } else {
            template = '';
          }
        }
      }
    }

    // Blobs/texts cannot have a defaultValue
    if (attribute.type && attribute.type !== 'TEXT' && attribute.type._binary !== true &&
      Utils.defaultValueSchemable(attribute.defaultValue)) {
      if (attribute.defaultValue instanceof DataTypes.NOW) {
        template += ' DEFAULT ' + DataTypes[this.dialect].NOW().toSql();
      } else {
        template += ' DEFAULT ' + this.escape(attribute.defaultValue, attribute);
      }
    } else if (attribute.defaultValue == null && (options && options.context === 'alterColumn')) {
        //if we change a column and their is no default value oracle must know
        if (!attribute.type || attribute.type !== 'TEXT') {
          template += ' DEFAULT NULL';
        }

    }

    if (!attribute.autoIncrement) {
      //If autoincrement, not null is setted automatically
      if (attribute.allowNull === false) {
        template += ' NOT NULL';
      } else if (!attribute.primaryKey) { //&& !Utils.defaultValueSchemable(attribute.defaultValue)
        template += ' NULL';
      }
    }

    if (attribute.unique === true && !attribute.primaryKey) {
      template += ' UNIQUE';
    }

    if (attribute.primaryKey) {
      template += ' PRIMARY KEY';
    }

    if (attribute.references) {
      template += ' REFERENCES ' + this.quoteTable(attribute.references.model);

      if (attribute.references.key) {
        template += ' (' + attribute.references.key + ')';
      } else {
        template += ' (' + 'id' + ')';
      }

      if (attribute.onDelete) {
        template += ' ON DELETE ' + attribute.onDelete.toUpperCase();
      }
    }

    return template;
  },

  attributesToSQL(attributes, options) {
    const result = {};

    for (const key in attributes) {
      const attribute = attributes[key];
      const attributeName = attribute.field || key;
      result[attributeName] = this.attributeToSQL(attribute, options).replace('ATTRIBUTENAME', attributeName);
    }

    return result;
  },

  createTrigger() {
    throwMethodUndefined('createTrigger');
  },

  dropTrigger() {
    throwMethodUndefined('dropTrigger');
  },

  renameTrigger() {
    throwMethodUndefined('renameTrigger');
  },

  createFunction() {
    throwMethodUndefined('createFunction');
  },

  dropFunction() {
    throwMethodUndefined('dropFunction');
  },

  renameFunction() {
    throwMethodUndefined('renameFunction');
  },

  quoteIdentifier(identifier, force) {
    if (identifier === '*') {
      return identifier;
    }

    if (force === true) {
      return Utils.addTicks(identifier, '"');
    } else if (identifier.indexOf('.') > - 1 || identifier.indexOf('->') > - 1 || identifier.indexOf(' ') > - 1) {
      return Utils.addTicks(identifier, '"');
    } else {
      //If there is a reserved word, we have to quote it

      if (_.includes(oracleReservedWords, identifier.toUpperCase())) {
        return Utils.addTicks(identifier, '"');
      }
      return identifier;
    }
  },

  getConstraintsOnColumn(table, column) {
    const tableName = table.tableName || table;

    const sql = ['SELECT CONSTRAINT_NAME FROM user_cons_columns WHERE TABLE_NAME = \'',
      tableName.toUpperCase(),
      '\' ',
      ' and COLUMN_NAME = \'',
      column.toUpperCase(),
      '\' AND POSITION IS NOT NULL ORDER BY POSITION'].join('');

    return sql;
  },

  getForeignKeysQuery(table) {
    //We don't call quoteTable as we don't want the schema in the table name, Oracle seperates it on another field
    const tableName = table.tableName || table;
    const sql = ['select table_name,constraint_name, owner from all_constraints where constraint_type in (\'U\', \'R\') and table_name = \'',
      tableName.toUpperCase(),
      '\'',
      ' order by table_name, constraint_name'].join('');

    return sql;
  },

  quoteTable(param, as) {
    let table = '';

    if (_.isObject(param)) {
      if (param.schema) {

        // Oracle schema ≠ mssql schema or postgres schema DO NOT USE
        table += param.schema + (param.delimiter || '_') + param.tableName;

      } else {
        if (_.includes(oracleReservedWords, param.tableName.toUpperCase()) || param.tableName.indexOf('_') === 0) {
          table += this.quoteIdentifier(param.tableName, true);
        } else {
          table += this.quoteIdentifier(param.tableName);
        }
      }
    } else {
      //If there is a reserved word, we have to quote it
      if (_.includes(oracleReservedWords, param.toUpperCase()) || param.indexOf('_') === 0) {
        table = this.quoteIdentifier(param, true);
      } else {
        table = this.quoteIdentifier(param);
      }
    }

    //Oracle don't support as for table aliases
    if (as) {
      if (as.indexOf('.') > - 1 || as.indexOf('_') === 0) {
        table += ' ' + this.quoteIdentifier(as, true);
      } else {
        table += ' ' + this.quoteIdentifier(as);
      }
    }
    return table;
  },

  //sqlite can't cast to datetime so we need to convert date values to their ISO strings
  _toJSONValue(value) {
    if (value instanceof Date) {
      return value.toISOString();
    } else if (Array.isArray(value) && value[0] instanceof Date) {
      return value.map(val => val.toISOString());
    } else if (typeof value === 'boolean') {
      return value.toString();
    } else if (Array.isArray(value) && typeof value[0] === 'boolean') {
      return value.map(val => val.toString());
    }
    return value;
  },

  _getJsonCast(value) {
    if (typeof value === 'number') {
      return 'number';
    }
    return;
  },

  nameIndexes(indexes, rawTablename) {
    let tableName;
    if (_.isObject(rawTablename)) {
      tableName = rawTablename.schema  + '_' + rawTablename.tableName;
    } else {
      tableName = rawTablename;
    }
    return _.map(indexes, index => {
      if (!index.hasOwnProperty('name')) {
        if (index.unique) {
          index.name = this._generateUniqueConstraintName(tableName, index.fields);
        } else {
          const onlyAttributeNames = index.fields.map(field => typeof field === 'string' ? field : field.name || field.attribute);
          index.name = Utils.underscore(tableName + '_' + onlyAttributeNames.join('_'));
        }
      }
      return index;
    });
  },

  dropForeignKeyQuery(tableName, foreignKey) {
    return this.dropConstraintQuery(tableName, foreignKey);
  },

  getPrimaryKeyConstraintQuery(tableName) {

    const sql = ['SELECT cols.column_name, atc.identity_column ',
      'FROM all_constraints cons, all_cons_columns cols ',
      'INNER JOIN all_tab_columns atc ON(atc.table_name = cols.table_name AND atc.COLUMN_NAME = cols.COLUMN_NAME )',
      'WHERE cols.table_name = \'',
      tableName.tableName ? tableName.tableName.toUpperCase() : tableName.toUpperCase(),
      '\' ',
      'AND cons.constraint_type = \'P\' ',
      'AND cons.constraint_name = cols.constraint_name ',
      'AND cons.owner = cols.owner ',
      'ORDER BY cols.table_name, cols.position'].join('');

    return sql;
  },

  /**
   * Request to know if the table has a identity primary key, returns the name of the declaration of the identity if true
   */
  isIdentityPrimaryKey(tableName) {
    return ['SELECT TABLE_NAME,COLUMN_NAME, COLUMN_NAME,GENERATION_TYPE,IDENTITY_OPTIONS FROM ALL_TAB_IDENTITY_COLS WHERE TABLE_NAME=\'',
      tableName.tableName ? tableName.tableName.toUpperCase() : tableName.toUpperCase(),
      '\' '].join('');
  },

  /**
   * Drop identity
   * Mandatory, Oracle doesn't support dropping a PK column if it's an identity -> results in database corruption
   */
  dropIdentityColumn(tableName, columnName) {
    const table = this.quoteTable(tableName);

    return 'ALTER TABLE ' + table + ' MODIFY ' + columnName + ' DROP IDENTITY';
  },

  dropConstraintQuery(tableName, constraintName) {
    const sql = 'ALTER TABLE <%= table %> DROP CONSTRAINT "<%= constraint %>"';

    return _.template(sql)({
      table: this.quoteTable(tableName),
      constraint: constraintName
    });
  },

  setAutocommitQuery(value) {
    if (value) {
      //Do nothing, just for eslint
    }
    return '';
  },

  setIsolationLevelQuery(value, options) {
    if (options.parent) {
      return;
    }

    //We force the transaction level to the highest to have consistent datas
    return 'SET TRANSACTION ISOLATION LEVEL READ COMMITTED;';
  },

  generateTransactionId() {
    //Oracle doesn't support transaction names > 32...
    //To deal with -savepoint-XX , we generate the uuid and then get the crc32 of it
    return crc32(uuid.v4());
  },

  startTransactionQuery(transaction) {
    if (transaction.parent) {
      return 'SAVEPOINT "' + transaction.name + '"';
    }

    return 'BEGIN TRANSACTION';
  },

  commitTransactionQuery(transaction) {
    if (transaction.parent) {
      return;
    }

    return 'COMMIT TRANSACTION';
  },

  rollbackTransactionQuery(transaction) {
    if (transaction.parent) {
      return 'ROLLBACK TO SAVEPOINT "' + transaction.name + '"';
    }

    return 'ROLLBACK TRANSACTION';
  },

  selectFromTableFragment(options, model, attributes, tables, mainTableAs) {
    let mainFragment = 'SELECT ' + attributes.join(', ') + ' FROM ' + tables;

    if (mainTableAs) {
      mainFragment += ' ' + mainTableAs;
    }

    return mainFragment;
  },

  addLimitAndOffset(options, model) {
    let fragment = '';
    const offset = options.offset || 0
      , isSubQuery = options.hasIncludeWhere || options.hasIncludeRequired || options.hasMultiAssociation;

    let orders = {};
    if (options.order) {
      orders = this.getQueryOrders(options, model, isSubQuery);
    }

    if (options.limit || options.offset) {
      if (!(options.order && options.group) && (!options.order || options.include && !orders.subQueryOrder.length)) {
        fragment += (options.order && !isSubQuery) ? ', ' : ' ORDER BY ';
        fragment += this.quoteTable(options.tableAs || model.name) + '.' + this.quoteIdentifier(model.primaryKeyField);
      }

      if (options.offset || options.limit) {
        fragment += ' OFFSET ' + this.escape(offset) + ' ROWS';
      }

      if (options.limit) {
        fragment += ' FETCH NEXT ' + this.escape(options.limit) + ' ROWS ONLY';
      }
    }

    return fragment;
  },

  booleanValue(value) {
    return !!value ? 1 : 0;
  }

};

// private methods
function wrapSingleQuote(identifier) {
  return Utils.addTicks(identifier, "'");
}

module.exports = _.extend(_.clone(AbstractQueryGenerator), QueryGenerator);


text:
<?php

class Presenter_Layouts_Fleet extends Presenter
{
    public function before() {
        parent::before();

        // Load list of aircraft here
        $this->aircraft_models = Model_Aircraft::find('all');
        $this->aircraft_options = ['_new' => 'Create new aircraft'];
        foreach($this->aircraft_models as $aircraft_model)
        {
            $this->aircraft_options[$aircraft_model->id] = $aircraft_model->name;
        }

    }

    public function view()
    {
        $form_sections = [
            View::forge('form/group', [
                'inputs' => [
                    View::forge('form/group/input', [
                        'label' => 'Select',
                        'label_coltype' => 'col-xs-2',
                        'input_coltype' => 'col-xs-8',
                        'input' => Form::select('aircraft_id', '', $this->aircraft_options,
                            [
                                'class' => 'form-control',
                                'data-change' => '[{"action":"attribute","target":"./button","attributes":{"data-link":"view/aircraft/_value"}}]'
                            ]
                        ),
                    ], false),
                    View::forge('form/button', [
                        'label' => 'GO!',
                        'link' => 'view/aircraft',
                        'response_target' => './aircraft_form',
                        'request_data' => '',
                        'class' => 'btn btn-success',
                        'coltype' => 'col-xs-2'
                    ], false)
                ]
            ], false),
            View::forge('layout/panel_simple', [
                'content_context' => 'aircraft_form',
                'scroll_content' => true,
            ])
        ];

        $form = View::forge('form/container', [
            'name' => 'aircraft',
            'type' => 'form-horizontal ebs-fullheight',
            'sections' => $form_sections,
        ], false);

        $this->fleet = $form;

    }
}


text:
from typing import Any, TYPE_CHECKING

from azure.core import AsyncPipelineClient
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from msrest import Deserializer, Serializer

if TYPE_CHECKING:
    # pylint: disable=unused-import,ungrouped-imports
    from azure.core.credentials_async import AsyncTokenCredential

from ._configuration import AccessControlClientConfiguration
from .operations import RoleAssignmentsOperations
from .operations import RoleDefinitionsOperations
from .. import models

class AccessControlClient(object):
    """AccessControlClient.

    :ivar role_assignments: RoleAssignmentsOperations operations
    :vartype role_assignments: azure.synapse.accesscontrol.aio.operations.RoleAssignmentsOperations
    :ivar role_definitions: RoleDefinitionsOperations operations
    :vartype role_definitions: azure.synapse.accesscontrol.aio.operations.RoleDefinitionsOperations
    :param credential: Credential needed for the client to connect to Azure.
    :type credential: ~azure.core.credentials_async.AsyncTokenCredential
    :param endpoint: The workspace development endpoint, for example https://myworkspace.dev.azuresynapse.net.
    :type endpoint: str
    """

    def __init__(
        self,
        credential: "AsyncTokenCredential",
        endpoint: str,
        **kwargs: Any
    ) -> None:
        base_url = '{endpoint}'
        self._config = AccessControlClientConfiguration(credential, endpoint, **kwargs)
        self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self._serialize = Serializer(client_models)
        self._serialize.client_side_validation = False
        self._deserialize = Deserializer(client_models)

        self.role_assignments = RoleAssignmentsOperations(
            self._client, self._config, self._serialize, self._deserialize)
        self.role_definitions = RoleDefinitionsOperations(
            self._client, self._config, self._serialize, self._deserialize)

    async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse:
        """Runs the network request through the client's chained policies.

        :param http_request: The network request you want to make. Required.
        :type http_request: ~azure.core.pipeline.transport.HttpRequest
        :keyword bool stream: Whether the response payload will be streamed. Defaults to True.
        :return: The response of your network call. Does not do error handling on your response.
        :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse
        """
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        http_request.url = self._client.format_url(http_request.url, **path_format_arguments)
        stream = kwargs.pop("stream", True)
        pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs)
        return pipeline_response.http_response

    async def close(self) -> None:
        await self._client.close()

    async def __aenter__(self) -> "AccessControlClient":
        await self._client.__aenter__()
        return self

    async def __aexit__(self, *exc_details) -> None:
        await self._client.__aexit__(*exc_details)


text:
"""
This callback plugin verifies the required minimum version of Ansible
is installed for proper operation of the OpenShift Ansible Installer.
The plugin is named with leading `aa_` to ensure this plugin is loaded
first (alphanumerically) by Ansible.
"""
import sys
from subprocess import check_output
from ansible import __version__

if __version__ < '2.0':
    # pylint: disable=import-error,no-name-in-module
    # Disabled because pylint warns when Ansible v2 is installed
    from ansible.callbacks import display as pre2_display
    CallbackBase = object

    def display(*args, **kwargs):
        """Set up display function for pre Ansible v2"""
        pre2_display(*args, **kwargs)
else:
    from ansible.plugins.callback import CallbackBase
    from ansible.utils.display import Display

    def display(*args, **kwargs):
        """Set up display function for Ansible v2"""
        display_instance = Display()
        display_instance.display(*args, **kwargs)

# Set to minimum required Ansible version
REQUIRED_VERSION = '2.2.0.0'
DESCRIPTION = "Supported versions: %s or newer (except 2.2.1.0)" % REQUIRED_VERSION
FAIL_ON_2_2_1_0 = "There are known issues with Ansible version 2.2.1.0 which " \
                  "are impacting OpenShift-Ansible. Please use Ansible " \
                  "version 2.2.0.0 or a version greater than 2.2.1.0. " \
                  "See this issue for more details: " \
                  "https://github.com/openshift/openshift-ansible/issues/3111"

def version_requirement(version):
    """Test for minimum required version"""
    return version >= REQUIRED_VERSION

class CallbackModule(CallbackBase):
    """
    Ansible callback plugin
    """

    CALLBACK_VERSION = 1.0
    CALLBACK_NAME = 'version_requirement'

    def __init__(self):
        """
        Version verification is performed in __init__ to catch the
        requirement early in the execution of Ansible and fail gracefully
        """
        super(CallbackModule, self).__init__()

        if not version_requirement(__version__):
            display(
                'FATAL: Current Ansible version (%s) is not supported. %s'
                % (__version__, DESCRIPTION), color='red')
            sys.exit(1)

        if __version__ == '2.2.1.0':
            rpm_ver = str(check_output(["rpm", "-qa", "ansible"]))
            patched_ansible = '2.2.1.0-2'

            if patched_ansible not in rpm_ver:
                display(
                    'FATAL: Current Ansible version (%s) is not supported. %s'
                    % (__version__, FAIL_ON_2_2_1_0), color='red')
                sys.exit(1)


text:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.esri.arcgisruntime.mapping.view.MapView
        android:id="@+id/mapView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_constraintBottom_creator="1"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/calendarButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="48dp"
        android:clickable="true"
        android:focusable="true"
        android:src="@android:drawable/ic_menu_my_calendar"
        app:backgroundTint="@color/colorPrimary"
        app:elevation="6dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>


text:
package org.apache.camel.management.mbean;

import org.apache.camel.CamelContext;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.api.management.mbean.ManagedRuntimeCamelCatalogMBean;
import org.apache.camel.runtimecatalog.RuntimeCamelCatalog;
import org.apache.camel.spi.ManagementStrategy;

@ManagedResource(description = "Managed RuntimeCamelCatalog")
public class ManagedRuntimeCamelCatalog extends ManagedService implements ManagedRuntimeCamelCatalogMBean {
    private final CamelContext camelContext;
    private final RuntimeCamelCatalog camelCatalog;

    public ManagedRuntimeCamelCatalog(CamelContext camelContext, RuntimeCamelCatalog camelCatalog) {
        super(camelContext, camelCatalog);
        this.camelContext = camelContext;
        this.camelCatalog = camelCatalog;
    }

    public void init(ManagementStrategy strategy) {
        // do nothing
    }

    @Override
    public String componentJSonSchema(String name) {
        return camelCatalog.componentJSonSchema(name);
    }

    @Override
    public String dataFormatJSonSchema(String name) {
        return camelCatalog.dataFormatJSonSchema(name);
    }

    @Override
    public String languageJSonSchema(String name) {
        return camelCatalog.languageJSonSchema(name);
    }

    @Override
    public String modelJSonSchema(String name) {
        return camelCatalog.modelJSonSchema(name);
    }
}


text:
export function setIcon(bookmarks, url, tabId) {
  if (bookmarks && bookmarks.filter(b => b.url === url).length) {
    chrome.browserAction.setIcon({ path: '/img/icon-48.png', tabId });
  } else {
    chrome.browserAction.setIcon({ path: '/img/icon-48-plain.png', tabId });
  }
}

export default () => {
  chrome.tabs.onActivated.addListener((info) => {
    chrome.tabs.get(info.tabId, (tab) => {
      chrome.storage.sync.get('state', (obj) => {
        let { state } = obj;
        state = JSON.parse(state || '{}');
        setIcon(state.bookmarks, tab.url, info.tabId);
      });
    });
  });
  chrome.extension.onMessage.addListener((request) => {
    if (request.cmd === 'updateIcon') {
      setIcon(request.bookmarks, request.url, request.id);
    }
  });
};


text:
import os.path
import shutil

def copytree(src, dest, symlinks=False):
       """My own copyTree which does not fail if the directory exists.

       Recursively copy a directory tree using copy2().

       If the optional symlinks flag is true, symbolic links in the
       source tree result in symbolic links in the destination tree; if
       it is false, the contents of the files pointed to by symbolic
       links are copied.

       Behavior is meant to be identical to GNU 'cp -R'.
       """
       def copyItems(src, dest, symlinks=False):
           """Function that does all the work.

           It is necessary to handle the two 'cp' cases:
           - destination does exist
           - destination does not exist

           See 'cp -R' documentation for more details
           """
           for item in os.listdir(src):
              srcPath = os.path.join(src, item)
              if os.path.isdir(srcPath):
                  srcBasename = os.path.basename(srcPath)
                  destDirPath = os.path.join(dest, srcBasename)
                  if not os.path.exists(destDirPath):
                      os.makedirs(destDirPath)
                  copyItems(srcPath, destDirPath)
              elif os.path.islink(item) and symlinks:
                  linkto = os.readlink(item)
                  os.symlink(linkto, dest)
              else:
                  shutil.copy2(srcPath, dest)

       # case 'cp -R src/ dest/' where dest/ already exists
       if os.path.exists(dest):
          destPath = os.path.join(dest, os.path.basename(src))
          if not os.path.exists(destPath):
              os.makedirs(destPath)
       # case 'cp -R src/ dest/' where dest/ does not exist
       else:
          os.makedirs(dest)
          destPath = dest
       # actually copy the files
       copyItems(src, destPath)


text:
namespace SuperheroesUniverse.Data.Common
{
    using System;

    using Models;

    public class SuperheroesDataProvider : ISuperheroesDataProvider
    {
        private IRepository<Superhero> superheroes;
        private IRepository<City> cities;
        private IRepository<Planet> planets;
        private IRepository<Country> countries;
        private IRepository<Fraction> fractions;
        private IRepository<HeroRelationship> relationships;
        private IRepository<Power> powers;
        private Func<IUnitOfWork> unitOfWork;

        public SuperheroesDataProvider(
            IRepository<Superhero> superheroes,
            IRepository<City> cities,
            IRepository<Planet> planets,
            IRepository<Country> countries,
            IRepository<Fraction> fractions,
            IRepository<HeroRelationship> relationships,
            IRepository<Power> powers,
            Func<IUnitOfWork> unitOfWork)
        {
            this.Superheroes = superheroes;
            this.Cities = cities;
            this.Planets = planets;
            this.Countries = countries;
            this.Fractions = fractions;
            this.Relationships = relationships;
            this.Powers = powers;
            this.UnitOfWork = unitOfWork;
        }

        public IRepository<Superhero> Superheroes
        {
            get { return this.superheroes; }
            set { this.superheroes = value; }
        }

        public IRepository<City> Cities
        {
            get { return this.cities; }
            set { this.cities = value; }
        }

        public IRepository<Planet> Planets
        {
            get { return this.planets; }
            set { this.planets = value; }
        }

        public IRepository<Country> Countries
        {
            get { return this.countries; }
            set { this.countries = value; }
        }

        public IRepository<Fraction> Fractions
        {
            get { return this.fractions; }
            set { this.fractions = value; }
        }

        public IRepository<HeroRelationship> Relationships
        {
            get { return this.relationships; }
            set { this.relationships = value; }
        }

        public IRepository<Power> Powers
        {
            get { return this.powers; }
            set { this.powers = value; }
        }

        public Func<IUnitOfWork> UnitOfWork
        {
            get { return this.unitOfWork; }
            set { this.unitOfWork = value; }
        }
    }
}