<commit_before>/**
 *  KitScript - A User Script Manager For Safari
 *
 *  KitScriptStorage.js - Javascript file containing the main storage class
 *  (by Prototype.js) used globally in the extension.
 *
 *  @author Seraf Dos Santos <webmaster@cyb3r.ca>
 *  @copyright 2011-2012 Seraf Dos Santos - All rights reserved.
 *  @license MIT License
 *  @version 0.1
 */

//"use strict";

/**
*  KSStorage (KitScript Storage Class)
*/
var KSStorage = Class.create(Storage, {

    initialize: function ($super) {

        this._dbName = 'KitScript';
        this._dbVersion = '1.0';
        this._dbDisplayName = 'KitScript Database';
        this._dbSize = 10 * 1024 * 1024; // 10 MB in bytes

        $super(this._dbName, this._dbVersion, this._dbDisplayName, this._dbSize);

        this._isDbExistant = false;

        this._dbTableUserScriptFiles = "UserScriptFiles";
        this._dbTableUserScriptsMetadata = "UserScriptsMetadata";
        this._dbTableGlobalExcludes = "GlobalExcludes";
        this._dbTableKitScript = "KitScript";
    },
    connect: function ($super) {

        try {

            _db = $super();
        } catch (e) {

            throw new StorageException(e.getMessage());
        }

        //this.verifyDb();

        return _db;
    },
    isDbExistant: function () {

        return this._isDbExistant;
    },
    verifyDb: function () {

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "SELECT enabled FROM "+this._dbTableKitScript+";", [], this._dbq_onQueryAnyTable, SFH_errorHandler);

        this.transact(sqlArray);
    },
    _dbq_onQueryAnyTable: function (transact, resultSet) {

        var _this = transact.objInstance;

        if (resultSet.rows.length > 0)
            _this._isDbExistant = true;
        else {
            _this.createTables();
            _this.insertInitData();
        }

    },
    createTables: function (doDrop) {

        if (doDrop === true) {

            _sC = function () { console.log("Table dropped."); };

            sqlArray = new SQLStatementsArray();

            sqlArray.push(this, 'DROP TABLE '+this._dbTableUserScriptFiles+';', [], _sC, SFH_errorHandler);
            sqlArray.push(this, 'DROP TABLE '+this._dbTableUserScriptsMetadata+';', [], _sC, SFH_errorHandler);
            sqlArray.push(this, 'DROP TABLE '+this._dbTableGlobalExcludes+';', [], _sC, SFH_errorHandler);
            sqlArray.push(this, 'DROP TABLE '+this._dbTableKitScript+';', [], _sC, SFH_errorHandler);

            this.transact(sqlArray);
        }

        _sC1 = function () { console.log("Table created."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, 'CREATE TABLE IF NOT EXISTS '+this._dbTableUserScriptFiles+' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, userscript BLOB NOT NULL);', [], _sC1, SFH_errorHandler);
        sqlArray.push(this, 'CREATE TABLE IF NOT EXISTS '+this._dbTableUserScriptsMetadata+' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, namespace TEXT NOT NULL, description TEXT NOT NULL, includes TEXT NOT NULL, excludes TEXT NOT NULL, userscript_id INT NOT NULL, disabled INT NOT NULL DEFAULT 0, user_includes TEXT NULL, user_excludes TEXT NULL);', [], _sC1, SFH_errorHandler);
        sqlArray.push(this, 'CREATE TABLE IF NOT EXISTS '+this._dbTableGlobalExcludes+' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL);', [], _sC1, SFH_errorHandler);
        sqlArray.push(this, 'CREATE TABLE IF NOT EXISTS '+this._dbTableKitScript+' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, enabled INT NOT NULL DEFAULT 1);', [], _sC1, SFH_errorHandler);

        this.transact(sqlArray);

        this._isDbExistant = true;
    },
    insertInitData:function () {

        _sC2 = function () { console.log("Data inserted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "INSERT INTO "+this._dbTableKitScript+" (enabled) VALUES (1);", [], _sC2, SFH_errorHandler);

        this.transact(sqlArray);
    },
    /**
     *  ================
     *  User Script File
     *  ================
     */
    insertUserScriptFile: function (blob, statementCallback, obj) {

        _sC = statementCallback || function () { console.log("User script inserted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "INSERT INTO "+this._dbTableUserScriptFiles+" (userscript) VALUES (?);", [blob], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    updateUserScriptFile: function (code, statementCallback, obj) {

        _sC = statementCallback || function () { console.log("User script updated."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableUserScriptFiles+" SET userscript = ? WHERE id = ?;", [code, id], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    fetchUserScriptFile: function (id, statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "SELECT * FROM "+this._dbTableUserScriptFiles+" WHERE id = ?;", [id], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    deleteUserScriptFile: function (id, statementCallback, obj) {

        _sC = statementCallback || function () { console.log("User script deleted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "DELETE FROM "+this._dbTableUserScriptFiles+" WHERE id = ?;", [id], _sC, SFH_killTransaction);

        this.transact(sqlArray);
    },
    /**
     *  ====================
     *  User Script Metadata
     *  ====================
     */
    insertUserScriptMetadata: function (name, space, desc, includes, excludes, usid, disabled, user_includes, user_excludes, statementCallback, obj) {

        _sC = statementCallback || function () { console.log("User script metadata inserted.") };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "INSERT INTO "+this._dbTableUserScriptsMetadata+" (name, namespace, description, includes, excludes, userscript_id, disabled, user_includes, user_excludes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);", [name, space, desc, includes, excludes, usid, disabled, user_includes, user_excludes], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    updateUserScriptMetadata: function (id, name, space, desc, includes, excludes, disabled, user_includes, user_excludes, statementCallback, obj) {

        _sC = statementCallback || function () { console.log("User script metadata updated."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableUserScriptsMetadata+" SET name = ?, namespace = ?, description = ?, includes = ?, excludes = ?, disabled = ?, user_includes = ?, user_excludes = ? WHERE id = ?;", [name, space, desc, includes, excludes, disabled, user_includes, user_excludes, id], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    fetchUserScriptMetadata: function (id, statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "SELECT * FROM "+this._dbTableUserScriptsMetadata+" WHERE id = ?;", [id], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    fetchAllUserScriptsMetadata: function (offset, limit, statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "SELECT * FROM "+this._dbTableUserScriptsMetadata+" LIMIT ?, ?;", [offset, limit], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    deleteUserScriptMetadata: function (id, statementCallback, obj) {

        _sC = statementCallback || function () { console.log("User script metadata deleted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "DELETE FROM "+this._dbTableUserScriptsMetadata+" WHERE id = ?;", [id], _sC, SFH_killTransaction);

        this.transact(sqlArray);
    },
    updateUserScriptUserSettings: function (id, user_includes, user_excludes, statementCallback, obj) {

        _sC = statementCallback || function () { console.log("User script (user settings) updated."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableUserScriptsMetadata+" SET user_includes = ?, user_excludes = ? WHERE id = ?;", [user_includes, user_excludes, id], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    disableUserScript: function (id, statementCallback, obj) {

        _sC = statementCallback || function () { console.log("User script disabled."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableUserScriptsMetadata+" SET disabled = 1 WHERE id = ?;", [id], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    enableUserScript: function (id, statementCallback, obj) {

        _sC = statementCallback || function () { console.log("User script enabled."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableUserScriptsMetadata+" SET disabled = 0 WHERE id = ?;", [id], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    /**
     *  ==============
     *  Global Exclude
     *  ==============
     */
    insertGlobalExclude: function (url, statementCallback, obj) {

        _sC = statementCallback || function () { console.log("Global exclude inserted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "INSERT INTO "+this._dbTableGlobalExcludes+" (url) VALUES (?);", [url], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    updateGlobalExclude: function (id, url, statementCallback, obj) {

        _sC = statementCallback || function () { console.log("Data updated."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableGlobalExcludes+" SET url = ? WHERE id = ?;", [url, id], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    fetchGlobalExclude: function (id, statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "SELECT * FROM "+this._dbTableGlobalExcludes+" WHERE id = ?;", [id], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    fetchAllGlobalExcludes: function (offset, limit, statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "SELECT * FROM "+this._dbTableGlobalExcludes+" LIMIT ?, ?;", [offset, limit], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    deleteGlobalExclude: function (id, statementCallback, obj) {

        _sC = statementCallback || function () { console.log("Data deleted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "DELETE FROM "+this._dbTableGlobalExcludes+" WHERE id = ?;", [id], _sC, SFH_killTransaction);

        this.transact(sqlArray);
    },
    /**
     *  ========================
     *  Enable/Disable KitScript
     *  ========================
     */
    isKitScriptEnabled: function (statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "SELECT enabled FROM "+this._dbTableKitScript+" WHERE id = 1;", [], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    setKitScriptEnabled: function (statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableKitScript+" SET enabled = 1 WHERE id = 1;", [], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    setKitScriptDisabled: function (statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableKitScript+" SET enabled = 0 WHERE id = 1;", [], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    }
});

/**
 *  ============================================
 *  KSSHF_* (KitScript Storage Helper Functions)
 *  ============================================
 */

function KSSHF_blobize(str) {

    var _blob = "";

    /*
    for (var i=0; i<str.length; i++) {

        var _uc = str.charCodeAt(i).toString(16).toUpperCase();

        while (_uc.length < 4) {
            _uc = '0'+_uc;
        }

        _blob = _blob.concat('0x',_uc);
    }
    */

    _blob = encode64(str);

    return _blob;
}

function KSSHF_unblobize(blob) {

    var _str;

    /*
    for (var i=0; i<blob.length; i+=6) {

        var _uc = blob.substr(0+i,6);

        _str = _str.concat(String.fromCharCode(_uc));
    }
    */

    _str = decode64(blob);

    return _str;
}<commit_msg>Localizing variables<commit_after>/**
 *  KitScript - A User Script Manager For Safari
 *
 *  KitScriptStorage.js - Javascript file containing the main storage class
 *  (by Prototype.js) used globally in the extension.
 *
 *  @author Seraf Dos Santos <webmaster@cyb3r.ca>
 *  @copyright 2011-2012 Seraf Dos Santos - All rights reserved.
 *  @license MIT License
 *  @version 0.1
 */

//"use strict";

/**
*  KSStorage (KitScript Storage Class)
*/
var KSStorage = Class.create(Storage, {

    initialize: function ($super) {

        this._dbName = 'KitScript';
        this._dbVersion = '1.0';
        this._dbDisplayName = 'KitScript Database';
        this._dbSize = 10 * 1024 * 1024; // 10 MB in bytes

        $super(this._dbName, this._dbVersion, this._dbDisplayName, this._dbSize);

        this._isDbExistant = false;

        this._dbTableUserScriptFiles = "UserScriptFiles";
        this._dbTableUserScriptsMetadata = "UserScriptsMetadata";
        this._dbTableGlobalExcludes = "GlobalExcludes";
        this._dbTableKitScript = "KitScript";
    },
    connect: function ($super) {

        try {

            _db = $super();
        } catch (e) {

            throw new StorageException(e.getMessage());
        }

        //this.verifyDb();

        return _db;
    },
    isDbExistant: function () {

        return this._isDbExistant;
    },
    verifyDb: function () {

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "SELECT enabled FROM "+this._dbTableKitScript+";", [], this._dbq_onQueryAnyTable, SFH_errorHandler);

        this.transact(sqlArray);
    },
    _dbq_onQueryAnyTable: function (transact, resultSet) {

        var _this = transact.objInstance;

        if (resultSet.rows.length > 0)
            _this._isDbExistant = true;
        else {
            _this.createTables();
            _this.insertInitData();
        }

    },
    createTables: function (doDrop) {

        if (doDrop === true) {

            var _sC = function () { console.log("Table dropped."); };

            sqlArray = new SQLStatementsArray();

            sqlArray.push(this, 'DROP TABLE '+this._dbTableUserScriptFiles+';', [], _sC, SFH_errorHandler);
            sqlArray.push(this, 'DROP TABLE '+this._dbTableUserScriptsMetadata+';', [], _sC, SFH_errorHandler);
            sqlArray.push(this, 'DROP TABLE '+this._dbTableGlobalExcludes+';', [], _sC, SFH_errorHandler);
            sqlArray.push(this, 'DROP TABLE '+this._dbTableKitScript+';', [], _sC, SFH_errorHandler);

            this.transact(sqlArray);
        }

        _sC1 = function () { console.log("Table created."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, 'CREATE TABLE IF NOT EXISTS '+this._dbTableUserScriptFiles+' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, userscript BLOB NOT NULL);', [], _sC1, SFH_errorHandler);
        sqlArray.push(this, 'CREATE TABLE IF NOT EXISTS '+this._dbTableUserScriptsMetadata+' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, namespace TEXT NOT NULL, description TEXT NOT NULL, includes TEXT NOT NULL, excludes TEXT NOT NULL, userscript_id INT NOT NULL, disabled INT NOT NULL DEFAULT 0, user_includes TEXT NULL, user_excludes TEXT NULL);', [], _sC1, SFH_errorHandler);
        sqlArray.push(this, 'CREATE TABLE IF NOT EXISTS '+this._dbTableGlobalExcludes+' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL);', [], _sC1, SFH_errorHandler);
        sqlArray.push(this, 'CREATE TABLE IF NOT EXISTS '+this._dbTableKitScript+' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, enabled INT NOT NULL DEFAULT 1);', [], _sC1, SFH_errorHandler);

        this.transact(sqlArray);

        this._isDbExistant = true;
    },
    insertInitData:function () {

        _sC2 = function () { console.log("Data inserted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push(this, "INSERT INTO "+this._dbTableKitScript+" (enabled) VALUES (1);", [], _sC2, SFH_errorHandler);

        this.transact(sqlArray);
    },
    /**
     *  ================
     *  User Script File
     *  ================
     */
    insertUserScriptFile: function (blob, statementCallback, obj) {

        var _sC = statementCallback || function () { console.log("User script inserted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "INSERT INTO "+this._dbTableUserScriptFiles+" (userscript) VALUES (?);", [blob], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    updateUserScriptFile: function (id, blob, statementCallback, obj) {

        var _sC = statementCallback || function () { console.log("User script updated."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableUserScriptFiles+" SET userscript = ? WHERE id = ?;", [blob, id], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    fetchUserScriptFile: function (id, statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "SELECT * FROM "+this._dbTableUserScriptFiles+" WHERE id = ?;", [id], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    deleteUserScriptFile: function (id, statementCallback, obj) {

        var _sC = statementCallback || function () { console.log("User script deleted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "DELETE FROM "+this._dbTableUserScriptFiles+" WHERE id = ?;", [id], _sC, SFH_killTransaction);

        this.transact(sqlArray);
    },
    /**
     *  ====================
     *  User Script Metadata
     *  ====================
     */
    insertUserScriptMetadata: function (name, space, desc, includes, excludes, usid, disabled, user_includes, user_excludes, statementCallback, obj) {

        var _sC = statementCallback || function () { console.log("User script metadata inserted.") };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "INSERT INTO "+this._dbTableUserScriptsMetadata+" (name, namespace, description, includes, excludes, userscript_id, disabled, user_includes, user_excludes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);", [name, space, desc, includes, excludes, usid, disabled, user_includes, user_excludes], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    updateUserScriptMetadata: function (id, name, space, desc, includes, excludes, disabled, user_includes, user_excludes, statementCallback, obj) {

        var _sC = statementCallback || function () { console.log("User script metadata updated."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableUserScriptsMetadata+" SET name = ?, namespace = ?, description = ?, includes = ?, excludes = ?, disabled = ?, user_includes = ?, user_excludes = ? WHERE id = ?;", [name, space, desc, includes, excludes, disabled, user_includes, user_excludes, id], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    fetchUserScriptMetadata: function (id, statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "SELECT * FROM "+this._dbTableUserScriptsMetadata+" WHERE id = ?;", [id], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    fetchAllUserScriptsMetadata: function (offset, limit, statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "SELECT * FROM "+this._dbTableUserScriptsMetadata+" LIMIT ?, ?;", [offset, limit], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    deleteUserScriptMetadata: function (id, statementCallback, obj) {

        var _sC = statementCallback || function () { console.log("User script metadata deleted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "DELETE FROM "+this._dbTableUserScriptsMetadata+" WHERE id = ?;", [id], _sC, SFH_killTransaction);

        this.transact(sqlArray);
    },
    updateUserScriptUserSettings: function (id, user_includes, user_excludes, statementCallback, obj) {

        var _sC = statementCallback || function () { console.log("User script (user settings) updated."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableUserScriptsMetadata+" SET user_includes = ?, user_excludes = ? WHERE id = ?;", [user_includes, user_excludes, id], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    disableUserScript: function (id, statementCallback, obj) {

        var _sC = statementCallback || function () { console.log("User script disabled."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableUserScriptsMetadata+" SET disabled = 1 WHERE id = ?;", [id], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    enableUserScript: function (id, statementCallback, obj) {

        var _sC = statementCallback || function () { console.log("User script enabled."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableUserScriptsMetadata+" SET disabled = 0 WHERE id = ?;", [id], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    /**
     *  ==============
     *  Global Exclude
     *  ==============
     */
    insertGlobalExclude: function (url, statementCallback, obj) {

        var _sC = statementCallback || function () { console.log("Global exclude inserted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "INSERT INTO "+this._dbTableGlobalExcludes+" (url) VALUES (?);", [url], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    updateGlobalExclude: function (id, url, statementCallback, obj) {

        var _sC = statementCallback || function () { console.log("Data updated."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableGlobalExcludes+" SET url = ? WHERE id = ?;", [url, id], _sC, SFH_errorHandler);

        this.transact(sqlArray);
    },
    fetchGlobalExclude: function (id, statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "SELECT * FROM "+this._dbTableGlobalExcludes+" WHERE id = ?;", [id], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    fetchAllGlobalExcludes: function (offset, limit, statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "SELECT * FROM "+this._dbTableGlobalExcludes+" LIMIT ?, ?;", [offset, limit], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    deleteGlobalExclude: function (id, statementCallback, obj) {

        var _sC = statementCallback || function () { console.log("Data deleted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "DELETE FROM "+this._dbTableGlobalExcludes+" WHERE id = ?;", [id], _sC, SFH_killTransaction);

        this.transact(sqlArray);
    },
    /**
     *  ========================
     *  Enable/Disable KitScript
     *  ========================
     */
    isKitScriptEnabled: function (statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "SELECT enabled FROM "+this._dbTableKitScript+" WHERE id = 1;", [], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    setKitScriptEnabled: function (statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableKitScript+" SET enabled = 1 WHERE id = 1;", [], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    },
    setKitScriptDisabled: function (statementCallback, obj) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push((obj||this), "UPDATE "+this._dbTableKitScript+" SET enabled = 0 WHERE id = 1;", [], statementCallback, SFH_errorHandler);

        this.transact(sqlArray);
    }
});

/**
 *  ============================================
 *  KSSHF_* (KitScript Storage Helper Functions)
 *  ============================================
 */

function KSSHF_blobize(str) {

    var _blob = "";

    /*
    for (var i=0; i<str.length; i++) {

        var _uc = str.charCodeAt(i).toString(16).toUpperCase();

        while (_uc.length < 4) {
            _uc = '0'+_uc;
        }

        _blob = _blob.concat('0x',_uc);
    }
    */

    _blob = encode64(str);

    return _blob;
}

function KSSHF_unblobize(blob) {

    var _str;

    /*
    for (var i=0; i<blob.length; i+=6) {

        var _uc = blob.substr(0+i,6);

        _str = _str.concat(String.fromCharCode(_uc));
    }
    */

    _str = decode64(blob);

    return _str;
}<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow
 */

'use strict';

const invariant = require('invariant');
const warnOnce = require('../Utilities/warnOnce');

// Export React, plus some native additions.
module.exports = {
  // Components
  get AccessibilityInfo() {
    return require('../Components/AccessibilityInfo/AccessibilityInfo');
  },
  get ActivityIndicator() {
    return require('../Components/ActivityIndicator/ActivityIndicator');
  },
  get ART() {
    return require('../ART/ReactNativeART');
  },
  get Button() {
    return require('../Components/Button');
  },
  get CheckBox() {
    warnOnce(
      'checkBox-moved',
      'CheckBox has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/checkbox' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-checkbox',
    );
    return require('../Components/CheckBox/CheckBox');
  },
  get DatePickerIOS() {
    return require('../Components/DatePicker/DatePickerIOS');
  },
  get DrawerLayoutAndroid() {
    return require('../Components/DrawerAndroid/DrawerLayoutAndroid');
  },
  get FlatList() {
    return require('../Lists/FlatList');
  },
  get Image() {
    return require('../Image/Image');
  },
  get ImageBackground() {
    return require('../Image/ImageBackground');
  },
  get ImageEditor() {
    warnOnce(
      'image-editor-moved',
      'Image Editor has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/image-editor' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-image-editor',
    );
    return require('../Image/ImageEditor');
  },
  get ImageStore() {
    warnOnce(
      'imagestore-deprecation',
      'ImageStore is deprecated and will be removed in a future release. ' +
        'To get a base64-encoded string from a local image use either of the following third-party libraries:' +
        "* expo-file-system: `readAsStringAsync(filepath, 'base64')`" +
        "* react-native-fs: `readFile(filepath, 'base64')`",
    );
    return require('../Image/ImageStore');
  },
  get InputAccessoryView() {
    return require('../Components/TextInput/InputAccessoryView');
  },
  get KeyboardAvoidingView() {
    return require('../Components/Keyboard/KeyboardAvoidingView');
  },
  get MaskedViewIOS() {
    warnOnce(
      'maskedviewios-moved',
      'MaskedViewIOS has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/masked-view' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-masked-view',
    );
    return require('../Components/MaskedView/MaskedViewIOS');
  },
  get Modal() {
    return require('../Modal/Modal');
  },
  get Picker() {
    return require('../Components/Picker/Picker');
  },
  get PickerIOS() {
    return require('../Components/Picker/PickerIOS');
  },
  get ProgressBarAndroid() {
    return require('../Components/ProgressBarAndroid/ProgressBarAndroid');
  },
  get ProgressViewIOS() {
    return require('../Components/ProgressViewIOS/ProgressViewIOS');
  },
  get SafeAreaView() {
    return require('../Components/SafeAreaView/SafeAreaView');
  },
  get ScrollView() {
    return require('../Components/ScrollView/ScrollView');
  },
  get SectionList() {
    return require('../Lists/SectionList');
  },
  get SegmentedControlIOS() {
    return require('../Components/SegmentedControlIOS/SegmentedControlIOS');
  },
  get Slider() {
    warnOnce(
      'slider-moved',
      'Slider has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/slider' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-slider',
    );
    return require('../Components/Slider/Slider');
  },
  get Switch() {
    return require('../Components/Switch/Switch');
  },
  get RefreshControl() {
    return require('../Components/RefreshControl/RefreshControl');
  },
  get StatusBar() {
    return require('../Components/StatusBar/StatusBar');
  },
  get Text() {
    return require('../Text/Text');
  },
  get TextInput() {
    return require('../Components/TextInput/TextInput');
  },
  get Touchable() {
    return require('../Components/Touchable/Touchable');
  },
  get TouchableHighlight() {
    return require('../Components/Touchable/TouchableHighlight');
  },
  get TouchableNativeFeedback() {
    return require('../Components/Touchable/TouchableNativeFeedback');
  },
  get TouchableOpacity() {
    return require('../Components/Touchable/TouchableOpacity');
  },
  get TouchableWithoutFeedback() {
    return require('../Components/Touchable/TouchableWithoutFeedback');
  },
  get View() {
    return require('../Components/View/View');
  },
  get ViewPagerAndroid() {
    warnOnce(
      'viewpager-moved',
      'ViewPagerAndroid has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/viewpager' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-viewpager',
    );
    return require('../Components/ViewPager/ViewPagerAndroid');
  },
  get VirtualizedList() {
    return require('../Lists/VirtualizedList');
  },
  get VirtualizedSectionList() {
    return require('../Lists/VirtualizedSectionList');
  },

  // APIs
  get ActionSheetIOS() {
    return require('../ActionSheetIOS/ActionSheetIOS');
  },
  get Alert() {
    return require('../Alert/Alert');
  },
  get Animated() {
    return require('../Animated/src/Animated');
  },
  get AppRegistry() {
    return require('../ReactNative/AppRegistry');
  },
  get AppState() {
    return require('../AppState/AppState');
  },
  get AsyncStorage() {
    warnOnce(
      'async-storage-moved',
      'Async Storage has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/async-storage' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-async-storage',
    );
    return require('../Storage/AsyncStorage');
  },
  get BackHandler() {
    return require('../Utilities/BackHandler');
  },
  get Clipboard() {
    return require('../Components/Clipboard/Clipboard');
  },
  get DatePickerAndroid() {
    return require('../Components/DatePickerAndroid/DatePickerAndroid');
  },
  get DeviceInfo() {
    return require('../Utilities/DeviceInfo');
  },
  get Dimensions() {
    return require('../Utilities/Dimensions');
  },
  get Easing() {
    return require('../Animated/src/Easing');
  },
  get findNodeHandle() {
    return require('../Renderer/shims/ReactNative').findNodeHandle;
  },
  get I18nManager() {
    return require('../ReactNative/I18nManager');
  },
  get ImagePickerIOS() {
    warnOnce(
      'imagePickerIOS-moved',
      'ImagePickerIOS has been extracted from react-native core and will be removed in a future release. ' +
        "Please upgrade to use either '@react-native-community/react-native-image-picker' or 'expo-image-picker'. " +
        "If you cannot upgrade to a different library, please install the deprecated '@react-native-community/image-picker-ios' package. " +
        'See https://github.com/react-native-community/react-native-image-picker-ios',
    );
    return require('../Image/ImagePickerIOS');
  },
  get InteractionManager() {
    return require('../Interaction/InteractionManager');
  },
  get Keyboard() {
    return require('../Components/Keyboard/Keyboard');
  },
  get LayoutAnimation() {
    return require('../LayoutAnimation/LayoutAnimation');
  },
  get Linking() {
    return require('../Linking/Linking');
  },
  get NativeDialogManagerAndroid() {
    return require('../NativeModules/specs/NativeDialogManagerAndroid').default;
  },
  get NativeEventEmitter() {
    return require('../EventEmitter/NativeEventEmitter');
  },
  get PanResponder() {
    return require('../Interaction/PanResponder');
  },
  get PermissionsAndroid() {
    return require('../PermissionsAndroid/PermissionsAndroid');
  },
  get PixelRatio() {
    return require('../Utilities/PixelRatio');
  },
  get PushNotificationIOS() {
    warnOnce(
      'pushNotificationIOS-moved',
      'PushNotificationIOS has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/push-notification-ios' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-push-notification-ios',
    );
    return require('../PushNotificationIOS/PushNotificationIOS');
  },
  get Settings() {
    return require('../Settings/Settings');
  },
  get Share() {
    return require('../Share/Share');
  },
  get StatusBarIOS() {
    return require('../Components/StatusBar/StatusBarIOS');
  },
  get StyleSheet() {
    return require('../StyleSheet/StyleSheet');
  },
  get Systrace() {
    return require('../Performance/Systrace');
  },
  get TimePickerAndroid() {
    return require('../Components/TimePickerAndroid/TimePickerAndroid');
  },
  get ToastAndroid() {
    return require('../Components/ToastAndroid/ToastAndroid');
  },
  get TurboModuleRegistry() {
    return require('../TurboModule/TurboModuleRegistry');
  },
  get TVEventHandler() {
    return require('../Components/AppleTV/TVEventHandler');
  },
  get UIManager() {
    return require('../ReactNative/UIManager');
  },
  get unstable_batchedUpdates() {
    return require('../Renderer/shims/ReactNative').unstable_batchedUpdates;
  },
  get UTFSequence() {
    return require('../UTFSequence');
  },
  get Vibration() {
    return require('../Vibration/Vibration');
  },
  get YellowBox() {
    return require('../YellowBox/YellowBox');
  },

  // Plugins
  get DeviceEventEmitter() {
    return require('../EventEmitter/RCTDeviceEventEmitter');
  },
  get NativeAppEventEmitter() {
    return require('../EventEmitter/RCTNativeAppEventEmitter');
  },
  get NativeModules() {
    return require('../BatchedBridge/NativeModules');
  },
  get Platform() {
    return require('../Utilities/Platform');
  },
  get processColor() {
    return require('../StyleSheet/processColor');
  },
  get requireNativeComponent() {
    return require('../ReactNative/requireNativeComponent');
  },

  // Prop Types
  get ColorPropType() {
    return require('../DeprecatedPropTypes/DeprecatedColorPropType');
  },
  get EdgeInsetsPropType() {
    return require('../DeprecatedPropTypes/DeprecatedEdgeInsetsPropType');
  },
  get PointPropType() {
    return require('../DeprecatedPropTypes/DeprecatedPointPropType');
  },
  get ViewPropTypes() {
    return require('../DeprecatedPropTypes/DeprecatedViewPropTypes');
  },
};

if (__DEV__) {
  // $FlowFixMe This is intentional: Flow will error when attempting to access ListView.
  Object.defineProperty(module.exports, 'ListView', {
    configurable: true,
    get() {
      invariant(
        false,
        'ListView has been removed from React Native. ' +
          'See https://fb.me/nolistview for more information or use ' +
          '`deprecated-react-native-listview`.',
      );
    },
  });

  // $FlowFixMe This is intentional: Flow will error when attempting to access SwipeableListView.
  Object.defineProperty(module.exports, 'SwipeableListView', {
    configurable: true,
    get() {
      invariant(
        false,
        'SwipeableListView has been removed from React Native. ' +
          'See https://fb.me/nolistview for more information or use ' +
          '`deprecated-react-native-swipeable-listview`.',
      );
    },
  });

  // $FlowFixMe This is intentional: Flow will error when attempting to access WebView.
  Object.defineProperty(module.exports, 'WebView', {
    configurable: true,
    get() {
      invariant(
        false,
        'WebView has been removed from React Native. ' +
          "It can now be installed and imported from 'react-native-webview' instead of 'react-native'. " +
          'See https://github.com/react-native-community/react-native-webview',
      );
    },
  });

  // $FlowFixMe This is intentional: Flow will error when attempting to access NetInfo.
  Object.defineProperty(module.exports, 'NetInfo', {
    configurable: true,
    get() {
      invariant(
        false,
        'NetInfo has been removed from React Native. ' +
          "It can now be installed and imported from 'react-native-netinfo' instead of 'react-native'. " +
          'See https://github.com/react-native-community/react-native-netinfo',
      );
    },
  });

  // $FlowFixMe This is intentional: Flow will error when attempting to access CameraRoll.
  Object.defineProperty(module.exports, 'CameraRoll', {
    configurable: true,
    get() {
      invariant(
        false,
        'CameraRoll has been removed from React Native. ' +
          "It can now be installed and imported from 'react-native-cameraroll' instead of 'react-native'. " +
          'See https://github.com/react-native-community/react-native-cameraroll',
      );
    },
  });
}
<commit_msg>Backout D15554658<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow
 */

'use strict';

const invariant = require('invariant');
const warnOnce = require('../Utilities/warnOnce');

// Export React, plus some native additions.
module.exports = {
  // Components
  get AccessibilityInfo() {
    return require('../Components/AccessibilityInfo/AccessibilityInfo');
  },
  get ActivityIndicator() {
    return require('../Components/ActivityIndicator/ActivityIndicator');
  },
  get ART() {
    return require('../ART/ReactNativeART');
  },
  get Button() {
    return require('../Components/Button');
  },
  get CheckBox() {
    warnOnce(
      'checkBox-moved',
      'CheckBox has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/checkbox' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-checkbox',
    );
    return require('../Components/CheckBox/CheckBox');
  },
  get DatePickerIOS() {
    return require('../Components/DatePicker/DatePickerIOS');
  },
  get DrawerLayoutAndroid() {
    return require('../Components/DrawerAndroid/DrawerLayoutAndroid');
  },
  get FlatList() {
    return require('../Lists/FlatList');
  },
  get Image() {
    return require('../Image/Image');
  },
  get ImageBackground() {
    return require('../Image/ImageBackground');
  },
  get ImageEditor() {
    warnOnce(
      'image-editor-moved',
      'Image Editor has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/image-editor' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-image-editor',
    );
    return require('../Image/ImageEditor');
  },
  get ImageStore() {
    warnOnce(
      'imagestore-deprecation',
      'ImageStore is deprecated and will be removed in a future release. ' +
        'To get a base64-encoded string from a local image use either of the following third-party libraries:' +
        "* expo-file-system: `readAsStringAsync(filepath, 'base64')`" +
        "* react-native-fs: `readFile(filepath, 'base64')`",
    );
    return require('../Image/ImageStore');
  },
  get InputAccessoryView() {
    return require('../Components/TextInput/InputAccessoryView');
  },
  get KeyboardAvoidingView() {
    return require('../Components/Keyboard/KeyboardAvoidingView');
  },
  get MaskedViewIOS() {
    warnOnce(
      'maskedviewios-moved',
      'MaskedViewIOS has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/masked-view' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-masked-view',
    );
    return require('../Components/MaskedView/MaskedViewIOS');
  },
  get Modal() {
    return require('../Modal/Modal');
  },
  get Picker() {
    return require('../Components/Picker/Picker');
  },
  get PickerIOS() {
    return require('../Components/Picker/PickerIOS');
  },
  get ProgressBarAndroid() {
    return require('../Components/ProgressBarAndroid/ProgressBarAndroid');
  },
  get ProgressViewIOS() {
    return require('../Components/ProgressViewIOS/ProgressViewIOS');
  },
  get SafeAreaView() {
    return require('../Components/SafeAreaView/SafeAreaView');
  },
  get ScrollView() {
    return require('../Components/ScrollView/ScrollView');
  },
  get SectionList() {
    return require('../Lists/SectionList');
  },
  get SegmentedControlIOS() {
    return require('../Components/SegmentedControlIOS/SegmentedControlIOS');
  },
  get Slider() {
    warnOnce(
      'slider-moved',
      'Slider has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/slider' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-slider',
    );
    return require('../Components/Slider/Slider');
  },
  get Switch() {
    return require('../Components/Switch/Switch');
  },
  get RefreshControl() {
    return require('../Components/RefreshControl/RefreshControl');
  },
  get StatusBar() {
    return require('../Components/StatusBar/StatusBar');
  },
  get Text() {
    return require('../Text/Text');
  },
  get TextInput() {
    return require('../Components/TextInput/TextInput');
  },
  get Touchable() {
    return require('../Components/Touchable/Touchable');
  },
  get TouchableHighlight() {
    return require('../Components/Touchable/TouchableHighlight');
  },
  get TouchableNativeFeedback() {
    return require('../Components/Touchable/TouchableNativeFeedback');
  },
  get TouchableOpacity() {
    return require('../Components/Touchable/TouchableOpacity');
  },
  get TouchableWithoutFeedback() {
    return require('../Components/Touchable/TouchableWithoutFeedback');
  },
  get View() {
    return require('../Components/View/View');
  },
  get ViewPagerAndroid() {
    warnOnce(
      'viewpager-moved',
      'ViewPagerAndroid has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/viewpager' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-viewpager',
    );
    return require('../Components/ViewPager/ViewPagerAndroid');
  },
  get VirtualizedList() {
    return require('../Lists/VirtualizedList');
  },
  get VirtualizedSectionList() {
    return require('../Lists/VirtualizedSectionList');
  },

  // APIs
  get ActionSheetIOS() {
    return require('../ActionSheetIOS/ActionSheetIOS');
  },
  get Alert() {
    return require('../Alert/Alert');
  },
  get Animated() {
    return require('../Animated/src/Animated');
  },
  get AppRegistry() {
    return require('../ReactNative/AppRegistry');
  },
  get AppState() {
    return require('../AppState/AppState');
  },
  get AsyncStorage() {
    warnOnce(
      'async-storage-moved',
      'Async Storage has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/async-storage' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-async-storage',
    );
    return require('../Storage/AsyncStorage');
  },
  get BackHandler() {
    return require('../Utilities/BackHandler');
  },
  get Clipboard() {
    return require('../Components/Clipboard/Clipboard');
  },
  get DatePickerAndroid() {
    return require('../Components/DatePickerAndroid/DatePickerAndroid');
  },
  get DeviceInfo() {
    return require('../Utilities/DeviceInfo');
  },
  get Dimensions() {
    return require('../Utilities/Dimensions');
  },
  get Easing() {
    return require('../Animated/src/Easing');
  },
  get findNodeHandle() {
    return require('../Renderer/shims/ReactNative').findNodeHandle;
  },
  get I18nManager() {
    return require('../ReactNative/I18nManager');
  },
  get ImagePickerIOS() {
    warnOnce(
      'imagePickerIOS-moved',
      'ImagePickerIOS has been extracted from react-native core and will be removed in a future release. ' +
        "Please upgrade to use either '@react-native-community/react-native-image-picker' or 'expo-image-picker'. " +
        "If you cannot upgrade to a different library, please install the deprecated '@react-native-community/image-picker-ios' package. " +
        'See https://github.com/react-native-community/react-native-image-picker-ios',
    );
    return require('../Image/ImagePickerIOS');
  },
  get InteractionManager() {
    return require('../Interaction/InteractionManager');
  },
  get Keyboard() {
    return require('../Components/Keyboard/Keyboard');
  },
  get LayoutAnimation() {
    return require('../LayoutAnimation/LayoutAnimation');
  },
  get Linking() {
    return require('../Linking/Linking');
  },
  get NativeDialogManagerAndroid() {
    return require('../NativeModules/specs/NativeDialogManagerAndroid').default;
  },
  get NativeEventEmitter() {
    return require('../EventEmitter/NativeEventEmitter');
  },
  get PanResponder() {
    return require('../Interaction/PanResponder');
  },
  get PermissionsAndroid() {
    return require('../PermissionsAndroid/PermissionsAndroid');
  },
  get PixelRatio() {
    return require('../Utilities/PixelRatio');
  },
  get PushNotificationIOS() {
    warnOnce(
      'pushNotificationIOS-moved',
      'PushNotificationIOS has been extracted from react-native core and will be removed in a future release. ' +
        "It can now be installed and imported from '@react-native-community/push-notification-ios' instead of 'react-native'. " +
        'See https://github.com/react-native-community/react-native-push-notification-ios',
    );
    return require('../PushNotificationIOS/PushNotificationIOS');
  },
  get Settings() {
    return require('../Settings/Settings');
  },
  get Share() {
    return require('../Share/Share');
  },
  get StatusBarIOS() {
    return require('../Components/StatusBar/StatusBarIOS');
  },
  get StyleSheet() {
    return require('../StyleSheet/StyleSheet');
  },
  get Systrace() {
    return require('../Performance/Systrace');
  },
  get TimePickerAndroid() {
    return require('../Components/TimePickerAndroid/TimePickerAndroid');
  },
  get ToastAndroid() {
    return require('../Components/ToastAndroid/ToastAndroid');
  },
  get TurboModuleRegistry() {
    return require('../TurboModule/TurboModuleRegistry');
  },
  get TVEventHandler() {
    return require('../Components/AppleTV/TVEventHandler');
  },
  get UIManager() {
    return require('../ReactNative/UIManager');
  },
  get unstable_batchedUpdates() {
    return require('../Renderer/shims/ReactNative').unstable_batchedUpdates;
  },
  get UTFSequence() {
    return require('../UTFSequence');
  },
  get Vibration() {
    return require('../Vibration/Vibration');
  },
  get YellowBox() {
    return require('../YellowBox/YellowBox');
  },

  // Plugins
  get DeviceEventEmitter() {
    return require('../EventEmitter/RCTDeviceEventEmitter');
  },
  get NativeAppEventEmitter() {
    return require('../EventEmitter/RCTNativeAppEventEmitter');
  },
  get NativeModules() {
    return require('../BatchedBridge/NativeModules');
  },
  get Platform() {
    return require('../Utilities/Platform');
  },
  get processColor() {
    return require('../StyleSheet/processColor');
  },
  get requireNativeComponent() {
    return require('../ReactNative/requireNativeComponent');
  },

  // Prop Types
  get ColorPropType() {
    return require('../DeprecatedPropTypes/DeprecatedColorPropType');
  },
  get EdgeInsetsPropType() {
    return require('../DeprecatedPropTypes/DeprecatedEdgeInsetsPropType');
  },
  get PointPropType() {
    return require('../DeprecatedPropTypes/DeprecatedPointPropType');
  },
  get ViewPropTypes() {
    return require('../DeprecatedPropTypes/DeprecatedViewPropTypes');
  },
  // TODO(cpojer): Temporary fix for missing Toolbar
  get ToolbarAndroid() {
    return require('UnimplementedView');
  },
};

if (__DEV__) {
  // $FlowFixMe This is intentional: Flow will error when attempting to access ListView.
  Object.defineProperty(module.exports, 'ListView', {
    configurable: true,
    get() {
      invariant(
        false,
        'ListView has been removed from React Native. ' +
          'See https://fb.me/nolistview for more information or use ' +
          '`deprecated-react-native-listview`.',
      );
    },
  });

  // $FlowFixMe This is intentional: Flow will error when attempting to access SwipeableListView.
  Object.defineProperty(module.exports, 'SwipeableListView', {
    configurable: true,
    get() {
      invariant(
        false,
        'SwipeableListView has been removed from React Native. ' +
          'See https://fb.me/nolistview for more information or use ' +
          '`deprecated-react-native-swipeable-listview`.',
      );
    },
  });

  // $FlowFixMe This is intentional: Flow will error when attempting to access WebView.
  Object.defineProperty(module.exports, 'WebView', {
    configurable: true,
    get() {
      invariant(
        false,
        'WebView has been removed from React Native. ' +
          "It can now be installed and imported from 'react-native-webview' instead of 'react-native'. " +
          'See https://github.com/react-native-community/react-native-webview',
      );
    },
  });

  // $FlowFixMe This is intentional: Flow will error when attempting to access NetInfo.
  Object.defineProperty(module.exports, 'NetInfo', {
    configurable: true,
    get() {
      invariant(
        false,
        'NetInfo has been removed from React Native. ' +
          "It can now be installed and imported from 'react-native-netinfo' instead of 'react-native'. " +
          'See https://github.com/react-native-community/react-native-netinfo',
      );
    },
  });

  // $FlowFixMe This is intentional: Flow will error when attempting to access CameraRoll.
  Object.defineProperty(module.exports, 'CameraRoll', {
    configurable: true,
    get() {
      invariant(
        false,
        'CameraRoll has been removed from React Native. ' +
          "It can now be installed and imported from 'react-native-cameraroll' instead of 'react-native'. " +
          'See https://github.com/react-native-community/react-native-cameraroll',
      );
    },
  });
}
<|endoftext|>


<commit_before><commit_msg>删除了M2.JS<commit_after><|endoftext|>


<commit_before>function log(message){
    console.log(message);
//    var linebreak = document.createElement('br');
//    logs.appendChild(linebreak);
//    var content = document.createTextNode(message);
//    logs.appendChild(content);
}

function logProperties(characteristic){
    log('> UUID:                 ' + characteristic.uuid);
    log('> Broadcast:            ' + characteristic.properties.broadcast);
    log('> Read:                 ' + characteristic.properties.read);
    log('> Write w/o response:   ' +
      characteristic.properties.writeWithoutResponse);
    log('> Write:                ' + characteristic.properties.write);
    log('> Notify:               ' + characteristic.properties.notify);
    log('> Indicate:             ' + characteristic.properties.indicate);
    log('> Signed Write:         ' +
      characteristic.properties.authenticatedSignedWrites);
    log('> Queued Write:         ' + characteristic.properties.reliableWrite);
    log('> Writable Auxiliaries: ' +
      characteristic.properties.writableAuxiliaries);
    log('> Value (cached):       ' + characteristic.value);
    log(' ');
}

function logRawHexValues(event){
      let value = event.target.value;
      let a = [];
      // Convert raw data bytes to hex values just for the sake of showing something.
      // In the "real" world, you'd use data.getUint8, data.getUint16 or even
      // TextDecoder to process raw data bytes.
      for (let i = 0; i < value.byteLength; i++) {
        a.push('0x' + ('00' + value.getUint8(i).toString(16)).slice(-2));
      }
      log('> ' + a.join(' ') + ' (raw data)');
      document.getElementById("display-raw-data").innerHTML = a.join(' ');
      a.reverse();
      log('> ' + a.join(' ') + ' (bytewise reversed)');
      document.getElementById("display-reversed-data").innerHTML = a.join(' ');
}<commit_msg>changed formatting of raw hex values to line up<commit_after>function log(message){
    console.log(message);
//    var linebreak = document.createElement('br');
//    logs.appendChild(linebreak);
//    var content = document.createTextNode(message);
//    logs.appendChild(content);
}

function logProperties(characteristic){
    log('> UUID:                 ' + characteristic.uuid);
    log('> Broadcast:            ' + characteristic.properties.broadcast);
    log('> Read:                 ' + characteristic.properties.read);
    log('> Write w/o response:   ' +
      characteristic.properties.writeWithoutResponse);
    log('> Write:                ' + characteristic.properties.write);
    log('> Notify:               ' + characteristic.properties.notify);
    log('> Indicate:             ' + characteristic.properties.indicate);
    log('> Signed Write:         ' +
      characteristic.properties.authenticatedSignedWrites);
    log('> Queued Write:         ' + characteristic.properties.reliableWrite);
    log('> Writable Auxiliaries: ' +
      characteristic.properties.writableAuxiliaries);
    log('> Value (cached):       ' + characteristic.value);
    log(' ');
}

function logRawHexValues(event){
      let value = event.target.value;
      let a = [];
      // Convert raw data bytes to hex values just for the sake of showing something.
      // In the "real" world, you'd use data.getUint8, data.getUint16 or even
      // TextDecoder to process raw data bytes.
      for (let i = 0; i < value.byteLength; i++) {
        a.push('0x' + ('00' + value.getUint8(i).toString(16)).slice(-2));
      }
      log('> ' + a.join(' ') + '    (raw data)');
      document.getElementById("display-raw-data").innerHTML = a.join(' ');
      a.reverse();
      log('> ' + a.join(' ') + '    (little endian)');
      document.getElementById("display-reversed-data").innerHTML = ' ' + a.join(' ');
}<|endoftext|>


<commit_before>var _ = require('underscore');
var express = require('express');
var request = require('request');
var hbs = require('hbs');
var keys = require(__dirname + '/index.js');
var sendgrid = require('sendgrid')('mnaughto', 'Green26');
var Firebase = require('firebase');
var FirebaseTokenGenerator = require('firebase-token-generator');
var fb_root = new Firebase('https://feedlisten.firebaseio.com/');
var tokenGenerator = new FirebaseTokenGenerator('nkn6OpQUq6gILOZq2vlrcH21P7aFtVCjgVLwQTYt');

var adminToken = tokenGenerator.createToken({}, {
	admin: true,
	debug: false,
	expires: 1577836800
});

fb_root.auth(adminToken);

var app = express();

app.configure('development', function() {
	app.use(express.bodyParser());
	app.use(express.errorHandler());
	app.locals.pretty = true;
});

app.get('/callback', function(req, res){
	var token = 'flashing7';
	if(req.query['hub.mode'] && req.query['hub.challenge'] && req.query['hub.verify_token']){
		if(req.query['hub.verify_token'] == token){
			res.type('txt');
			res.send(req.query['hub.challenge']);
		}
	}
});

app.post('/callback', function(req, res){
	if(req.body && req.body.entry){
		_.each(req.body.entry, function(entryItem){
			fb_root.child(entryItem.id).once('value', function(entrySnap){
				if(entrySnap.val()){
					var entryData = entrySnap.val();
					//get post id to view text of post
					var post_id;
					var token = entryData.token;
					try {
						post_id = entryItem.changes[0].value.post_id;
					} catch(ex){
						console.log(ex);
						return;
					}
					console.log('got post_id');
					//get the post from facebook
					request({json: true, url:'https://graph.facebook.com/' + entryItem.id + '_' + post_id, qs: {'access_token':token}}, function(error, response, body){
						if(!error && response.statusCode == 200){
							console.log('got the post');
							if(body.message){
								console.log('got the message');
								var bodyData = 'apikey=' + '2094dd01fd7cbceb7e1bb916840e40e81f25d16f' + '&text=' + encodeURIComponent(body.message) + '&outputMode=json';
								request({method: 'post', url:'http://access.alchemyapi.com/calls/text/TextGetTextSentiment', body:bodyData}, function(error, response, body){
									console.log('came back from alchemyapi');
									if(!error && response.statusCode == 200){
										console.log('alchemyapi success');
										body = JSON.parse(body);
										if(body.docSentiment){
											var sentiment = {
												type: body.docSentiment.type,
												value: body.docSentiment.score
											};
											console.log(sentiment);
											console.log(entryData);
											if((entryData.type == 'either') || (entryData.type == sentiment.type)){
												//send an email
												console.log('send an email');
												sendgrid.send({
													to: entryData.email,
													subject: 'Feedback report',
													text: 'Your page has received' + (entryData.type == 'either') ? 'important': entryData.type + 'feedback',
													from: 'noreply@feedlisten.com',
													replyto: 'michael.d.naughton@gmail.com'});
												console.log(entryData);
											}
										} else {
											console.log(body);
											console.log(bodyData);
											res.send(500, 'Could not get a sentiment');
										}
									} else {
										console.log(body);
										console.log(bodyData);
										res.send(500, 'Could not get a sentiment');
									}
								});
							}
						} else {
							console.log('main error');
							console.log(body);
							console.log(token);
							console.log(post_id);
							console.log(entryItem.id);
							console.log(error);
						}
					});
					//send the post message to alchemy
					//once alchemy returns, detect the sentiment.
					//if the sentiment is beyond the threshold in the right direction,
					//send an email to the destination
				}
			});
		});
	}
});

exports.app = app;<commit_msg>order of operations<commit_after>var _ = require('underscore');
var express = require('express');
var request = require('request');
var hbs = require('hbs');
var keys = require(__dirname + '/index.js');
var sendgrid = require('sendgrid')('mnaughto', 'Green26');
var Firebase = require('firebase');
var FirebaseTokenGenerator = require('firebase-token-generator');
var fb_root = new Firebase('https://feedlisten.firebaseio.com/');
var tokenGenerator = new FirebaseTokenGenerator('nkn6OpQUq6gILOZq2vlrcH21P7aFtVCjgVLwQTYt');

var adminToken = tokenGenerator.createToken({}, {
	admin: true,
	debug: false,
	expires: 1577836800
});

fb_root.auth(adminToken);

var app = express();

app.configure('development', function() {
	app.use(express.bodyParser());
	app.use(express.errorHandler());
	app.locals.pretty = true;
});

app.get('/callback', function(req, res){
	var token = 'flashing7';
	if(req.query['hub.mode'] && req.query['hub.challenge'] && req.query['hub.verify_token']){
		if(req.query['hub.verify_token'] == token){
			res.type('txt');
			res.send(req.query['hub.challenge']);
		}
	}
});

app.post('/callback', function(req, res){
	if(req.body && req.body.entry){
		_.each(req.body.entry, function(entryItem){
			fb_root.child(entryItem.id).once('value', function(entrySnap){
				if(entrySnap.val()){
					var entryData = entrySnap.val();
					//get post id to view text of post
					var post_id;
					var token = entryData.token;
					try {
						post_id = entryItem.changes[0].value.post_id;
					} catch(ex){
						console.log(ex);
						return;
					}
					console.log('got post_id');
					//get the post from facebook
					request({json: true, url:'https://graph.facebook.com/' + entryItem.id + '_' + post_id, qs: {'access_token':token}}, function(error, response, body){
						if(!error && response.statusCode == 200){
							console.log('got the post');
							if(body.message){
								console.log('got the message');
								var bodyData = 'apikey=' + '2094dd01fd7cbceb7e1bb916840e40e81f25d16f' + '&text=' + encodeURIComponent(body.message) + '&outputMode=json';
								request({method: 'post', url:'http://access.alchemyapi.com/calls/text/TextGetTextSentiment', body:bodyData}, function(error, response, body){
									console.log('came back from alchemyapi');
									if(!error && response.statusCode == 200){
										console.log('alchemyapi success');
										body = JSON.parse(body);
										if(body.docSentiment){
											var sentiment = {
												type: body.docSentiment.type,
												value: body.docSentiment.score
											};
											console.log(sentiment);
											console.log(entryData);
											if((entryData.type == 'either') || (entryData.type == sentiment.type)){
												//send an email
												console.log('send an email');
												sendgrid.send({
													to: entryData.email,
													subject: 'Feedback report',
													text: 'Your page has received' + ((entryData.type == 'either') ? 'important': entryData.type + 'feedback'),
													from: 'noreply@feedlisten.com',
													replyto: 'michael.d.naughton@gmail.com'});
												console.log(entryData);
											}
										} else {
											console.log(body);
											console.log(bodyData);
											res.send(500, 'Could not get a sentiment');
										}
									} else {
										console.log(body);
										console.log(bodyData);
										res.send(500, 'Could not get a sentiment');
									}
								});
							}
						} else {
							console.log('main error');
							console.log(body);
							console.log(token);
							console.log(post_id);
							console.log(entryItem.id);
							console.log(error);
						}
					});
					//send the post message to alchemy
					//once alchemy returns, detect the sentiment.
					//if the sentiment is beyond the threshold in the right direction,
					//send an email to the destination
				}
			});
		});
	}
});

exports.app = app;<|endoftext|>


<commit_before>export function createContextProxyHandler() {
  const cache = new Map();

  const getParameterHandler = {
    apply(target, gl, args) {
      if (cache.has(args[0])) {
        return cache.get(args[0]);
      }
      return target.apply(gl, args);
    },
  };

  // only supports single-value setters
  function cachedSetterHandler(key) {
    return {
      apply(target, gl, args) {
        cache.set(key, args[0]);
        return target.apply(gl, args);
      },
    };
  }

  // When a property is accessed on the webgl context proxy,
  // it's accessed is intercepted. If the property name matches
  // any of the keys of `propHandlers`, then that handler is called
  // with the following arguments: (gl, prop, receiver, propValue)
  // - gl (WebGL2RenderingContext): the underlying webgl context
  // - propName (string): the property name
  // - receiver (Proxy): the webgl context proxy
  // - propValue (unknown): the value of `gl[propName]`

  const propHandlers = Object.create(null);

  // Sets getParameter(property) as a cached getter proxy.
  // propValue.bind(gl) is to avoid Illegal Invocation errors.
  propHandlers.getParameter = (gl, prop, receiver, propValue) =>
    new Proxy(propValue.bind(gl), getParameterHandler);

  // Sets depthMask(flag) as a cached setter proxy.
  propHandlers.depthMask = (gl, prop, receiver, propValue) =>
    new Proxy(propValue.bind(gl), cachedSetterHandler(gl.DEPTH_WRITEMASK));

  return {
    get(gl, prop, receiver) {
      let value = Reflect.get(gl, prop, receiver);
      if (value instanceof Function) {
        // prevents Illegal Invocation errors
        value = value.bind(gl);
      }

      const propHandler = propHandlers[prop];
      if (propHandler) {
        return propHandler(gl, prop, receiver, value);
      }

      return value;
    },
  };
}

export default { createContextProxyHandler };
<commit_msg>fix(RenderWindow): use gl as receiver directly<commit_after>export function createContextProxyHandler() {
  const cache = new Map();

  const getParameterHandler = {
    apply(target, gl, args) {
      if (cache.has(args[0])) {
        return cache.get(args[0]);
      }
      return target.apply(gl, args);
    },
  };

  // only supports single-value setters
  function cachedSetterHandler(key) {
    return {
      apply(target, gl, args) {
        cache.set(key, args[0]);
        return target.apply(gl, args);
      },
    };
  }

  // When a property is accessed on the webgl context proxy,
  // it's accessed is intercepted. If the property name matches
  // any of the keys of `propHandlers`, then that handler is called
  // with the following arguments: (gl, prop, receiver, propValue)
  // - gl (WebGL2RenderingContext): the underlying webgl context
  // - propName (string): the property name
  // - receiver (Proxy): the webgl context proxy
  // - propValue (unknown): the value of `gl[propName]`

  const propHandlers = Object.create(null);

  // Sets getParameter(property) as a cached getter proxy.
  // propValue.bind(gl) is to avoid Illegal Invocation errors.
  propHandlers.getParameter = (gl, prop, receiver, propValue) =>
    new Proxy(propValue.bind(gl), getParameterHandler);

  // Sets depthMask(flag) as a cached setter proxy.
  propHandlers.depthMask = (gl, prop, receiver, propValue) =>
    new Proxy(propValue.bind(gl), cachedSetterHandler(gl.DEPTH_WRITEMASK));

  return {
    get(gl, prop, receiver) {
      let value = Reflect.get(gl, prop, gl);
      if (value instanceof Function) {
        // prevents Illegal Invocation errors
        value = value.bind(gl);
      }

      const propHandler = propHandlers[prop];
      if (propHandler) {
        return propHandler(gl, prop, receiver, value);
      }

      return value;
    },
  };
}

export default { createContextProxyHandler };
<|endoftext|>


<commit_before>if (!RedactorPlugins) var RedactorPlugins = {};

(function ($) {
  RedactorPlugins.fontFamily = function () {
    var arrows = [37, 38, 39, 40];

    return {
      init: function () {
        var fonts = ['Arial', 'Helvetica', 'Georgia', 'Times New Roman', 'Monospace'];
        var dropdown = {};

        options = this.opts.fontFamily || { defaultFont: 'Arial' };

        $.each(fonts, function (i, s) {
          dropdown['s' + i] = {
            title: s,
            func: function (e) {
              this.fontFamily.onSelect(s);
            }
          };
        });

        var button = this.button.add('fontList', "Font");
        button[0].innerHTML = options.defaultFont;
        $(this.button.get('fontList')[0]).css('font-family', options.defaultFont);
        this.core.getElement()[0].style.fontFamily = options.defaultFont;
        this.button.addDropdown(button, dropdown);

        this.opts.clickCallback = function () {
          this.fontFamily.caretChanged(this);
        };

        this.opts.keyupCallback = function (e) {
          var key = e.keyCode || e.which;
          if (arrows.indexOf(key) === -1) return;

          this.fontFamily.caretChanged(this);
        };
      },
      onSelect: function (font) {
        this.button.get('fontList')[0].innerHTML = font;
        $(this.button.get('fontList')[0]).css('font-family', font);
        this.inline.format('span', 'style', 'font-family:' + font + ';');

      },
      caretChanged: function (t) {
        var node = t.sel.focusNode.parentElement;
        var font = window.getComputedStyle(node, null).getPropertyValue('font-family');

        font = font.replace(/['"]+/g, '');

        this.button.get('fontList')[0].innerHTML = font;
        $(this.button.get('fontList')[0]).css('font-family', font);
      }
    }
  };
})(jQuery);
<commit_msg>adds styling of list entries<commit_after>if (!RedactorPlugins) var RedactorPlugins = {};

(function ($) {
  RedactorPlugins.fontFamily = function () {
    var arrows = [37, 38, 39, 40];

    return {
      init: function () {
        var fonts = ['Arial', 'Helvetica', 'Georgia', 'Times New Roman', 'Monospace'];
        var dropdown = {};

        options = this.opts.fontFamily || { defaultFont: 'Arial' };

        $.each(fonts, function (i, s) {
          dropdown['s' + i] = {
            title: s,
            func: function (e) {
              this.fontFamily.onSelect(s);
            }
          };
        });

        var button = this.button.add('fontList', "Font");
        button[0].innerHTML = options.defaultFont;
        $(this.button.get('fontList')[0]).css('font-family', options.defaultFont);
        this.core.getElement()[0].style.fontFamily = options.defaultFont;
        this.button.addDropdown(button, dropdown);

        this.opts.dropdownShowCallback = function(dropdown, key, button)
			  {
				  if(dropdown.key === "fontList") {
					  $(".redactor-dropdown-box-fontList").children().each(function (index, value) {
						  $(value).css("font-family", value.text);
					  });
				  }
			  }

        this.opts.clickCallback = function () {
          this.fontFamily.caretChanged(this);
        };

        this.opts.keyupCallback = function (e) {
          var key = e.keyCode || e.which;
          if (arrows.indexOf(key) === -1) return;

          this.fontFamily.caretChanged(this);
        };
      },
      onSelect: function (font) {
        this.button.get('fontList')[0].innerHTML = font;
        $(this.button.get('fontList')[0]).css('font-family', font);
        this.inline.format('span', 'style', 'font-family:' + font + ';');

      },
      caretChanged: function (t) {
        var node = t.sel.focusNode.parentElement;
        var font = window.getComputedStyle(node, null).getPropertyValue('font-family');

        font = font.replace(/['"]+/g, '');

        this.button.get('fontList')[0].innerHTML = font;
        $(this.button.get('fontList')[0]).css('font-family', font);
      }
    }
  };
})(jQuery);
<|endoftext|>


<commit_before>
/**
 * Monolyth data binder.
 */
;(function($, Monolyth) {

Monolyth.extend('binder', function() {

var bound = {};

this.create = function(type, element, model) {
    bound[type] = bound[type] || [];
    var b = {
        element: element,
        model: model
    };
    b.template = $(
        '[data-binder-template="' + type + '"]',
        b.element
    ).first();
    bound[type].push(b);
};

this.update = function(type, element, data) {
    if (!(type in bound)) {
        return;
    }
    for (var i = 0, b; i < bound[type].length; i++) {
        if (bound[type][i].element.get(0) === element.get(0)) {
            b = bound[type][i];
            break;
        }
    }
    if (!b) {
        return;
    }
    if (typeof data == 'string') {
        data = [data];
    }
    var e = b.template.siblings('[data-binder-id]').detach();
    var u;
    for (var name in b.model) {
        u = name;
        break;
    }
    if (data.length) {
        b.element.find('[data-binder-placeholder]').remove();
    }
    for (var i = 0; i < data.length; i++) {
        var s = b.template.clone(),
            c = e.filter('[data-binder-id=' + data[i][u] + ']');
        if (c.length) {
            s = c.first().detach();
        }
        s.removeAttr('data-binder-template');
        for (var prop in data[i]) {
            if (!(prop in b.model)) {
                continue;
            }
            var h = b.model[prop];
            if (h == null) {
                continue;
            }
            if (typeof h == 'string') {
                h = [h];
            }
            for (var j = 0; j < h.length; j++) {
                var p = h[j].match(/\[(\w+?)(=.*?)?\]$/),
                    obj = h[j].substring(0, 1) == '&' ?
                        s :
                        s.find(h[j]);
                if (p && p.length) {
                    obj.attr(p[1], data[i][prop]);
                } else {
                    obj.html(data[i][prop]);
                }
            }
        }
        s.attr('data-binder-id', data[i][u]);
        if (b.template.attr('data-binder-append') != undefined) {
            b.template.after(s);
        } else {
            b.template.before(s);
        }
    }
    if (b.template.attr('data-binder-append') != undefined) {
        b.template.after(e);
    } else {
        b.template.before(e);
    }

    this.init();
};

this.init = function() {
    bound = {};
    cnt = 0;
    $('[data-binder]').each(function() {
        var $this = $(this), binders = $.parseJSON($this.attr('data-binder'));
        for (var name in binders) {
            Monolyth.binder.create(
                name,
                $this,
                binders[name]
            );
        }
    });
};

});

$(document).ready(Monolyth.binder.init);

})(window.jQuery, window.Monolyth);

<commit_msg>Conflicts: 	output/js/jquery/binder.js<commit_after>
/**
 * Monolyth data binder.
 */
;(function($, Monolyth) {

Monolyth.extend('binder', function() {

var bound = {};

this.create = function(type, element, model) {
    bound[type] = bound[type] || [];
    var b = {
        element: element,
        model: model
    };
    b.template = $(
        '[data-binder-template="' + type + '"]',
        b.element
    ).first();
    bound[type].push(b);
};

this.update = function(type, element, data) {
    if (!(type in bound)) {
        return;
    }
    for (var i = 0, b; i < bound[type].length; i++) {
        if (bound[type][i].element.get(0) === element.get(0)) {
            b = bound[type][i];
            break;
        }
    }
    if (!b) {
        return;
    }
    if (typeof data == 'string') {
        data = [data];
    }
    if (b.template.attr('data-binder-append') == undefined) {
        var e = b.template.siblings('[data-binder-id]').detach();
    } else {
        var e = b.template.siblings('[data-binder-id]');
    }
    var u;
    for (var name in b.model) {
        u = name;
        break;
    }
    if (data.length) {
        b.element.find('[data-binder-placeholder]').remove();
    }
    for (var i = 0; i < data.length; i++) {
        var s = b.template.clone(),
            c = e.filter('[data-binder-id=' + data[i][u] + ']');
        if (c.length) {
            s = c.first().detach();
        }
        s.removeAttr('data-binder-template');
        for (var prop in data[i]) {
            if (!(prop in b.model)) {
                continue;
            }
            var h = b.model[prop];
            if (h == null) {
                continue;
            }
            if (typeof h == 'string') {
                h = [h];
            }
            for (var j = 0; j < h.length; j++) {
                var p = h[j].match(/\[(\w+?)(=.*?)?\]$/),
                    obj = h[j].substring(0, 1) == '&' ?
                        s :
                        s.find(h[j]);
                if (p && p.length) {
                    obj.attr(p[1], data[i][prop]);
                } else {
                    obj.html(data[i][prop]);
                }
            }
        }
        s.attr('data-binder-id', data[i][u]);
        if (b.template.attr('data-binder-append') != undefined) {
            b.template.after(s);
        } else {
            b.template.before(s);
        }
    }
    if (b.template.attr('data-binder-append') == undefined) {
        b.template.before(e);
    }

    this.init();
};

this.init = function() {
    bound = {};
    cnt = 0;
    $('[data-binder]').each(function() {
        var $this = $(this), binders = $.parseJSON($this.attr('data-binder'));
        for (var name in binders) {
            Monolyth.binder.create(
                name,
                $this,
                binders[name]
            );
        }
    });
};

});

$(document).ready(Monolyth.binder.init);

})(window.jQuery, window.Monolyth);

<|endoftext|>


<commit_before>/*!

   MPEG-DASH engine plugin for Flowplayer HTML5 version 5.x

   Copyright 2015 Flowplayer Oy

   Released under the MIT License:
   http://www.opensource.org/licenses/mit-license.php

   Includes dash.all.js:
   Copyright (c) 2015, Dash Industry Forum. **All rights reserved.
   https://github.com/Dash-Industry-Forum/dash.js/blob/development/LICENSE.md

   requires:
   - Flowplayer HTML5 version 5.x
   - dash.js https://github.com/Dash-Industry-Forum/dash.js

*/

(function ($) {
  if (!flowplayer.support.video ||
      !window.MediaSource ||
      !window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.640029, mp4a.40.5"')) {
    return;
  }

  flowplayer.engine.mpegdash = function(player, root) {
    var mediaPlayer,
    videoTag,
    dashstop = false,
    context = new Dash.di.DashContext();

    // see seek implementation below
    player.bind("stop", function (e) {
      if (!dashstop) {
        e.preventDefault();
      }
      dashstop = !dashstop;
    });

    return {
      pick: function(sources) {
        var i;

        for (i = 0; i < sources.length; i++) {
          if (sources[i].type === "application/dash+xml") {
            return sources[i];
          }
        }
      },
      load: function(video) {
        root.find('video').remove();
        videoTag = $("<video/>")[0],
        $(videoTag).on('play', function() {
          root.trigger('resume', [player]);
        });
        $(videoTag).on('pause', function() {
          root.trigger('pause', [player]);
        });
        $(videoTag).on('timeupdate', function() {
          root.trigger('progress', [player, videoTag.currentTime]);
        });
        $(videoTag).on('loadeddata', function() {
          video.duration = video.seekable = videoTag.duration;
          root.trigger('ready', [player, video]);
        });
        $(videoTag).on('seeked', function() {
          root.trigger('seek', [player, videoTag.currentTime]);
        });
        $(videoTag).on('progress', function(e) {
          try {
            var buffered = videoTag.buffered,
                buffer = buffered.end(0), // first loaded buffer
                ct = videoTag.currentTime,
                buffend = 0,
                i;

            // buffered.end(null) will not always return the current buffer
            // so we cycle through the time ranges to obtain it
            if (ct) {
              for (i = 1; i < buffered.length; i++) {
                buffend = buffered.end(i);

                if (buffend >= ct && buffered.start(i) <= ct) {
                  buffer = buffend;
                }
              }
            }
            video.buffer = buffer;
          } catch (ignored) {}
          root.trigger('buffer', [player, e]);
        });
        $(videoTag).on('ended', function() {
          root.trigger('finish', [player]);
        });
        $(videoTag).on('volumechange', function() {
          root.trigger('volume', [player, videoTag.volume]);
        });

        videoTag.className = 'fp-engine dash-engine';
        root.prepend(videoTag);

        mediaPlayer = new MediaPlayer(context);
        mediaPlayer.setScheduleWhilePaused(true);
        mediaPlayer.setAutoPlay(player.conf.autoplay || player.conf.splash);
        mediaPlayer.startup();
        mediaPlayer.attachView(videoTag);
        mediaPlayer.attachSource(video.src);
      },
      resume: function() {
        if (player.finished) {
          videoTag.currentTime = 0;
        }
        videoTag.play();
      },
      pause: function() {
        videoTag.pause();
      },
      seek: function(time) {
        if (videoTag.paused) {
          // dash.js always resumes playback after seek
          $(videoTag).one("seeked.dashpaused", function () {
            setTimeout(function () {
              videoTag.pause()
              // stop seeks to 0 causing dash.js to resume
              // see stop handle above
              if (dashstop) {
                player.trigger('stop', [player]);
              }
            }, 0);
          });
        }
        videoTag.currentTime = time;
      },
      volume: function(level) {
        if (videoTag) {
          videoTag.volume = level;
        }
      },
      speed: function(val) {
        videoTag.playbackRate = val;
        root.trigger('speed', [player, val]);
      },
      unload: function() {
        if (mediaPlayer) {
          mediaPlayer.reset();
        }
        $(videoTag).remove();
        root.trigger("unload", [player]);
      }

    };

  };

  $(function () {
    // hack: globally force dash engine, but allow other global config
    flowplayer.conf.engine = "mpegdash";
  });

}(jQuery));
<commit_msg>v5: white-space change<commit_after>/*!

   MPEG-DASH engine plugin for Flowplayer HTML5 version 5.x

   Copyright 2015 Flowplayer Oy

   Released under the MIT License:
   http://www.opensource.org/licenses/mit-license.php

   Includes dash.all.js:
   Copyright (c) 2015, Dash Industry Forum. **All rights reserved.
   https://github.com/Dash-Industry-Forum/dash.js/blob/development/LICENSE.md

   requires:
   - Flowplayer HTML5 version 5.x
   - dash.js https://github.com/Dash-Industry-Forum/dash.js

*/

(function ($) {
    if (!flowplayer.support.video ||
            !window.MediaSource ||
            !window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.640029, mp4a.40.5"')) {
        return;
    }

    flowplayer.engine.mpegdash = function (player, root) {
        var mediaPlayer,
            videoTag,
            dashstop = false,
            context = new Dash.di.DashContext();

        // see seek implementation below
        player.bind("stop", function (e) {
            if (!dashstop) {
                e.preventDefault();
            }
            dashstop = !dashstop;
        });

        return {
            pick: function (sources) {
                var i;

                for (i = 0; i < sources.length; i++) {
                    if (sources[i].type === "application/dash+xml") {
                        return sources[i];
                    }
                }
            },
            load: function (video) {
                root.find('video').remove();
                videoTag = $("<video/>")[0];
                $(videoTag).on('play', function () {
                    root.trigger('resume', [player]);
                });
                $(videoTag).on('pause', function () {
                    root.trigger('pause', [player]);
                });
                $(videoTag).on('timeupdate', function () {
                    root.trigger('progress', [player, videoTag.currentTime]);
                });
                $(videoTag).on('loadeddata', function () {
                    video.duration = video.seekable = videoTag.duration;
                    root.trigger('ready', [player, video]);
                });
                $(videoTag).on('seeked', function () {
                    root.trigger('seek', [player, videoTag.currentTime]);
                });
                $(videoTag).on('progress', function (e) {
                    try {
                        var buffered = videoTag.buffered,
                                buffer = buffered.end(0), // first loaded buffer
                                ct = videoTag.currentTime,
                                buffend = 0,
                                i;

                        // buffered.end(null) will not always return the current buffer
                        // so we cycle through the time ranges to obtain it
                        if (ct) {
                            for (i = 1; i < buffered.length; i++) {
                                buffend = buffered.end(i);

                                if (buffend >= ct && buffered.start(i) <= ct) {
                                    buffer = buffend;
                                }
                            }
                        }
                        video.buffer = buffer;
                    } catch (ignored) {}
                    root.trigger('buffer', [player, e]);
                });
                $(videoTag).on('ended', function () {
                    root.trigger('finish', [player]);
                });
                $(videoTag).on('volumechange', function () {
                    root.trigger('volume', [player, videoTag.volume]);
                });

                videoTag.className = 'fp-engine dash-engine';
                root.prepend(videoTag);

                mediaPlayer = new MediaPlayer(context);
                mediaPlayer.setScheduleWhilePaused(true);
                mediaPlayer.setAutoPlay(player.conf.autoplay || player.conf.splash);
                mediaPlayer.startup();
                mediaPlayer.attachView(videoTag);
                mediaPlayer.attachSource(video.src);
            },
            resume: function () {
                if (player.finished) {
                    videoTag.currentTime = 0;
                }
                videoTag.play();
            },
            pause: function () {
                videoTag.pause();
            },
            seek: function (time) {
                if (videoTag.paused) {
                    // dash.js always resumes playback after seek
                    $(videoTag).one("seeked.dashpaused", function () {
                        setTimeout(function () {
                            videoTag.pause()
                            // stop seeks to 0 causing dash.js to resume
                            // see stop handle above
                            if (dashstop) {
                                player.trigger('stop', [player]);
                            }
                        }, 0);
                    });
                }
                videoTag.currentTime = time;
            },
            volume: function (level) {
                if (videoTag) {
                    videoTag.volume = level;
                }
            },
            speed: function (val) {
                videoTag.playbackRate = val;
                root.trigger('speed', [player, val]);
            },
            unload: function () {
                if (mediaPlayer) {
                    mediaPlayer.reset();
                }
                $(videoTag).remove();
                root.trigger("unload", [player]);
            }

        };

    };

    $(function () {
        // hack: globally force dash engine, but allow other global config
        flowplayer.conf.engine = "mpegdash";
    });

}(jQuery));
<|endoftext|>