<commit_before>(function($) {
  function GridManager() {
    var gridElementPrefix = "#grid_",
    gridElementSuffix = " .grid",
    pagerElementSuffix = " .pager",

    grids = [],

    defaultOptions = {
      explicitInitialization: true,
      enableAddRow: false,
      enableCellNavigation: true,
      asyncEditorLoading: false,
      autoEdit: false,
      cellFlashingCssClass: "master_flashing",
      rowHeight: 25
    };

    function init() {
    }

    function getEditorForType(type){
      switch(type.toLowerCase()){
        case "string":
        return Slick.Editors.Text;
        case "text":
        return Slick.Editors.LongText;
        case "datetime":
        return DateTimeCellEditor;
        case "time":
        return TimeCellEditor;
        case "date":
        return Slick.Editors.Date;
        case "integer":
        return Slick.Editors.Integer;
        case "boolean":
        return YesNoCheckboxCellEditor;
        case "belongs_to":
        return BelongsToEditor;
        case "has_one":
        return BelongsToEditor;
        case "has_and_belongs_to_many":
        return BelongsToEditor;
        case "has_many":
        return HasManyEditor;
        default:
        return Slick.Editors.Text;
      }
    }

    function appendEditor(columns){
      var i, type_str;
      for(i=0; i<columns.length; i++){
        type_str = columns[i].type.toLowerCase();
        // 1. append editor
        if (columns[i].editor) {
          columns[i].editor = eval(columns[i].editor);
        } else if (columns[i].distinct) {
          columns[i].editor = DistinctEditor;
        } else {
          columns[i].editor = getEditorForType(columns[i].type);
        }
        // 2. append cssClass
        if(type_str == "boolean") {
          columns[i].cssClass = 'cell-effort-driven';
        }

        if(type_str == "date") {
          columns[i].formatter = StandardDateCellFormatter;
          columns[i].DateShowFormat = "yy-mm-dd";
        } else if (type_str == "boolean") {
          if(!columns[i].formatter) {
            columns[i].formatter = GraphicBoolCellFormatter;
          }
        } else if(type_str == "belongs_to" || type_str == "has_and_belongs_to_many") {
          columns[i].formatter = BelongsToFormatter;
        } else if (type_str == "has_many") {
          columns[i].formatter = HasManyFormatter;
        } else if(type_str == 'has_one' ) {
          columns[i].formatter = HasOneFormatter;
        }

        if (columns[i].simple_date) {
          columns[i].editor = Slick.Editors.Text;
          columns[i].formatter = SimpleDateFormatter;
        } else if (columns[i].simple_time) {
          columns[i].editor = columns[i].editor || Slick.Editors.Text;
          columns[i].formatter = SimpleTimeFormatter;
        }

        // 3. append formatter
        if (columns[i].formatter) {
          columns[i].formatter = eval(columns[i].formatter);
          continue;
        }
      }
    }

    function createNewGrid(name, model, screen, path, filters, columns, states, actions, behaviors, extend_options) {
      var gridElement, options, loader, grid, pagerElement, pager, gridAttrs, originColumns;

      originColumns = deep_clone(columns);

      options = $.extend({}, defaultOptions, extend_options);

      gridElement = $(gridElementPrefix + name + gridElementSuffix);

      // Append editor attribute to columns
      appendEditor(columns);

      // Apply current filters
      filters = GridStatesManager.applyFilters(filters, states["filter"]);
      pathWithoutQuery = path.split(".json")[0];
      query = path.split(".json")[1];

      // Set Loader
      loader = new WulinMaster.Data.RemoteModel(path, filters, columns);

      // Set Pager
      pagerElement = $(gridElementPrefix + name + pagerElementSuffix);
      // pager = new Slick.Controls.Pager(loader, grid, pagerElement);
      pager = new WulinMaster.Pager(loader, grid, pagerElement);

      // Restore the order states to columns
      columns = GridStatesManager.restoreOrderStates(columns, states["order"]);
      // Restore the visibility states to columns
      GridStatesManager.restoreVisibilityStates(columns, states["visibility"]);
      // Restore the width states to columns
      GridStatesManager.restoreWidthStates(columns, states["width"]);

      // ------------------------- Create Grid ------------------------------------
      grid = new WulinMaster.Grid(gridElement, loader.data, columns, options);

      // Append necessary attributes to the grid
      gridAttrs = {
        name: name,
        model: model,
        screen: screen,
        loader: loader,
        path: pathWithoutQuery,
        columns: columns,
        originColumns: originColumns,
        query: query,
        container: gridElement.parent(),
        pager: pager,
        states: states,
        actions: actions,
        behaviors: behaviors,
        options: options
      };
      for(var attr in gridAttrs) {
        grid[attr] = gridAttrs[attr];
      }

      // Set selection model
      grid.setSelectionModel(new Slick.RowSelectionModel());

      // Set ColumnPicker
      var columnpicker = new Slick.Controls.ColumnPicker(columns, grid, options);

      // Load data into grid
      loader.setGrid(grid);

      // Create loading indicator on the activity panel, if not eager loading, hide the indicator
      var isHide = (grid.options.eagerLoading === false);
      loader.setLoadingIndicator(createLoadingIndicator(gridElement, isHide));

      // Restore the sorting states to grid
      GridStatesManager.restoreSortingStates(grid, loader, states["sort"]);

      // Dispatch actions
      WulinMaster.ActionManager.dispatchActions(grid, actions);
      // Dispatch behaviors, should come first than grid.resizeCanvas, otherwise some event like onRendered can't be triggered
      WulinMaster.BehaviorManager.dispatchBehaviors(grid, behaviors);

      // Set grid body height after rendering
      setGridBodyHeight(gridElement);
      grid.init();

      // Load the first page
      grid.onViewportChanged.notify();

      // Delete old grid if exsisting, then add grid
      for(var i in grids){
        if(grid.name == grids[i].name){
          grids.splice(i, 1);
        }
      }
      grids.push(grid);

      // ------------------------------ Register callbacks for handling grid states ------------------------
      if(states)
        GridStatesManager.onStateEvents(grid);

      // ------------------------------ Install some plugins -----------------------------------
      grid.registerPlugin(new Slick.AutoTooltips());
    } // createNewGrid

    function createLoadingIndicator(gridElement, isHide) {
      var truncateThreshold = 35,
      parent = gridElement.parent(".grid_container"),
      id = parent.attr("id"),
      title = $.trim(parent.find(".grid-header h2").text()),

      indicators = $("#activity #indicators"),
      indicator;

      if (title.length > truncateThreshold) {
        title = title.substring(0, truncateThreshold-2) + "...";
      }

      // Remove init indicator if it exists.
      indicators.find("#init_menu_indicator").remove();
      indicator = indicators.find(".loading_indicator#" + id);

      if (indicator.length === 0) {
        indicator = $(buildIndicatorHtml(id, title, isHide)).appendTo(indicators);
        // Init counter
        indicator.data("requestCount", 0);
      }

      return indicator;
    }

    function buildIndicatorHtml(id, title, isHide){
      return "

"+ title +"

";
    }

    function getGrid(name) {
      var theGrid = null;

      $.each(grids, function() {
        if (this.name == name)
        theGrid = this;
      });

      return theGrid;
    }

    function setGridBodyHeight(gridElement) {
      var container = gridElement.parent(".grid_container"),
      ch = container.height(),
      hh = container.find(".grid-header").height(),
      ph = container.find(".pager").height(),
      gh = ch - hh - ph;

      gridElement.css("height", gh - 1);
    }

    function resizeGrids() {
      var gridElement;
      $.each(grids, function() {
        gridElement = $(gridElementPrefix + this.name + gridElementSuffix);
        setGridBodyHeight(gridElement);
        this.resizeCanvas();
      });
    }

    init();

    return {
      // properties
      "grids": grids,

      // methods
      "createNewGrid": createNewGrid,
      "getGrid": getGrid,
      "resizeGrids": resizeGrids,
      "buildIndicatorHtml": buildIndicatorHtml
    };
  }

  $.extend(true, window, { GridManager: GridManager});
  })(jQuery);

  var gridManager = new GridManager();

  $(window).resize(function() { gridManager.resizeGrids(); });
<commit_msg>FEATURE #58796 - Upgrade SlickGrid<commit_after>(function($) {
  function GridManager() {
    var gridElementPrefix = "#grid_",
    gridElementSuffix = " .grid",
    pagerElementSuffix = " .pager",

    grids = [],

    defaultOptions = {
      explicitInitialization: true,
      enableAddRow: false,
      enableCellNavigation: true,
      asyncEditorLoading: false,
      autoEdit: false,
      cellFlashingCssClass: "master_flashing",
      rowHeight: 25
    };

    function init() {
    }

    function getEditorForType(type){
      switch(type.toLowerCase()){
        case "string":
        return Slick.Editors.Text;
        case "text":
        return Slick.Editors.LongText;
        case "datetime":
        return DateTimeCellEditor;
        case "time":
        return TimeCellEditor;
        case "date":
        return Slick.Editors.Date;
        case "integer":
        return Slick.Editors.Integer;
        case "boolean":
        return YesNoCheckboxCellEditor;
        case "belongs_to":
        return BelongsToEditor;
        case "has_one":
        return BelongsToEditor;
        case "has_and_belongs_to_many":
        return BelongsToEditor;
        case "has_many":
        return HasManyEditor;
        default:
        return Slick.Editors.Text;
      }
    }

    function appendEditor(columns){
      var i, type_str;
      for(i=0; i<columns.length; i++){
        type_str = columns[i].type.toLowerCase();
        // 1. append editor
        if (columns[i].editor) {
          columns[i].editor = eval(columns[i].editor);
        } else if (columns[i].distinct) {
          columns[i].editor = DistinctEditor;
        } else {
          columns[i].editor = getEditorForType(columns[i].type);
        }
        // 2. append cssClass
        if(type_str == "boolean") {
          columns[i].cssClass = 'cell-effort-driven';
        }

        if(type_str == "date") {
          columns[i].formatter = StandardDateCellFormatter;
          columns[i].DateShowFormat = "yy-mm-dd";
        } else if (type_str == "boolean") {
          if(!columns[i].formatter) {
            columns[i].formatter = GraphicBoolCellFormatter;
          }
        } else if(type_str == "belongs_to" || type_str == "has_and_belongs_to_many") {
          columns[i].formatter = BelongsToFormatter;
        } else if (type_str == "has_many") {
          columns[i].formatter = HasManyFormatter;
        } else if(type_str == 'has_one' ) {
          columns[i].formatter = HasOneFormatter;
        }

        if (columns[i].simple_date) {
          columns[i].editor = Slick.Editors.Text;
          columns[i].formatter = SimpleDateFormatter;
        } else if (columns[i].simple_time) {
          columns[i].editor = columns[i].editor || Slick.Editors.Text;
          columns[i].formatter = SimpleTimeFormatter;
        }

        // 3. append formatter
        if (columns[i].formatter) {
          columns[i].formatter = eval(columns[i].formatter);
          continue;
        }
      }
    }

    function createNewGrid(name, model, screen, path, filters, columns, states, actions, behaviors, extend_options) {
      var gridElement, options, loader, grid, pagerElement, pager, gridAttrs, originColumns;

      originColumns = deep_clone(columns);

      options = $.extend({}, defaultOptions, extend_options);

      gridElement = $(gridElementPrefix + name + gridElementSuffix);

      // Append editor attribute to columns
      appendEditor(columns);

      // Apply current filters
      filters = GridStatesManager.applyFilters(filters, states["filter"]);
      pathWithoutQuery = path.split(".json")[0];
      query = path.split(".json")[1];

      // Set Loader
      loader = new WulinMaster.Data.RemoteModel(path, filters, columns);

      // Set Pager
      pagerElement = $(gridElementPrefix + name + pagerElementSuffix);
      pager = new WulinMaster.Pager(loader, grid, pagerElement);

      // Restore the order states to columns
      columns = GridStatesManager.restoreOrderStates(columns, states["order"]);
      // Restore the visibility states to columns
      GridStatesManager.restoreVisibilityStates(columns, states["visibility"]);
      // Restore the width states to columns
      GridStatesManager.restoreWidthStates(columns, states["width"]);

      // ------------------------- Create Grid ------------------------------------
      grid = new WulinMaster.Grid(gridElement, loader.data, columns, options);

      // Append necessary attributes to the grid
      gridAttrs = {
        name: name,
        model: model,
        screen: screen,
        loader: loader,
        path: pathWithoutQuery,
        columns: columns,
        originColumns: originColumns,
        query: query,
        container: gridElement.parent(),
        pager: pager,
        states: states,
        actions: actions,
        behaviors: behaviors,
        options: options
      };
      for(var attr in gridAttrs) {
        grid[attr] = gridAttrs[attr];
      }

      // Set selection model
      grid.setSelectionModel(new Slick.RowSelectionModel());

      // Set ColumnPicker
      var columnpicker = new Slick.Controls.ColumnPicker(columns, grid, options);

      // Load data into grid
      loader.setGrid(grid);

      // Create loading indicator on the activity panel, if not eager loading, hide the indicator
      var isHide = (grid.options.eagerLoading === false);
      loader.setLoadingIndicator(createLoadingIndicator(gridElement, isHide));

      // Restore the sorting states to grid
      GridStatesManager.restoreSortingStates(grid, loader, states["sort"]);

      // Dispatch actions
      WulinMaster.ActionManager.dispatchActions(grid, actions);
      // Dispatch behaviors, should come first than grid.resizeCanvas, otherwise some event like onRendered can't be triggered
      WulinMaster.BehaviorManager.dispatchBehaviors(grid, behaviors);

      // Set grid body height after rendering
      setGridBodyHeight(gridElement);
      grid.init();

      // Load the first page
      grid.onViewportChanged.notify();

      // Delete old grid if exsisting, then add grid
      for(var i in grids){
        if(grid.name == grids[i].name){
          grids.splice(i, 1);
        }
      }
      grids.push(grid);

      // ------------------------------ Register callbacks for handling grid states ------------------------
      if(states)
        GridStatesManager.onStateEvents(grid);

      // ------------------------------ Install some plugins -----------------------------------
      grid.registerPlugin(new Slick.AutoTooltips());
    } // createNewGrid

    function createLoadingIndicator(gridElement, isHide) {
      var truncateThreshold = 35,
      parent = gridElement.parent(".grid_container"),
      id = parent.attr("id"),
      title = $.trim(parent.find(".grid-header h2").text()),

      indicators = $("#activity #indicators"),
      indicator;

      if (title.length > truncateThreshold) {
        title = title.substring(0, truncateThreshold-2) + "...";
      }

      // Remove init indicator if it exists.
      indicators.find("#init_menu_indicator").remove();
      indicator = indicators.find(".loading_indicator#" + id);

      if (indicator.length === 0) {
        indicator = $(buildIndicatorHtml(id, title, isHide)).appendTo(indicators);
        // Init counter
        indicator.data("requestCount", 0);
      }

      return indicator;
    }

    function buildIndicatorHtml(id, title, isHide){
      return "

"+ title +"

";
    }

    function getGrid(name) {
      var theGrid = null;

      $.each(grids, function() {
        if (this.name == name)
        theGrid = this;
      });

      return theGrid;
    }

    function setGridBodyHeight(gridElement) {
      var container = gridElement.parent(".grid_container"),
      ch = container.height(),
      hh = container.find(".grid-header").height(),
      ph = container.find(".pager").height(),
      gh = ch - hh - ph;

      gridElement.css("height", gh - 1);
    }

    function resizeGrids() {
      var gridElement;
      $.each(grids, function() {
        gridElement = $(gridElementPrefix + this.name + gridElementSuffix);
        setGridBodyHeight(gridElement);
        this.resizeCanvas();
      });
    }

    init();

    return {
      // properties
      "grids": grids,

      // methods
      "createNewGrid": createNewGrid,
      "getGrid": getGrid,
      "resizeGrids": resizeGrids,
      "buildIndicatorHtml": buildIndicatorHtml
    };
  }

  $.extend(true, window, { GridManager: GridManager});
  })(jQuery);

  var gridManager = new GridManager();

  $(window).resize(function() { gridManager.resizeGrids(); });
<|endoftext|>


<commit_before>var command = {
  command: 'init',
  description: 'Initialize new Ethereum project with example contracts and tests',
  builder: {},
  run: function (options, done) {
    var Config = require("truffle-config");
    var Init = require("truffle-init");
    var OS = require("os");

    var config = Config.default().with({
      logger: console
    });

    var example_name = "default";

    if (options._ && options._.length > 0) {
      example_name = options._[0];
    }

    Init.fromGithub(config, example_name, config.working_directory).then(function(project_config) {
      var docs_url = project_config.docs_url || "https://github.com/trufflesuite/truffle-init-" + example_name;

      config.logger.log("Project initialized." +
        OS.EOL +
        OS.EOL +
        "  Documentation: " + docs_url +
        OS.EOL
      );

      project_config.commands = project_config.commands || {};

      var longest_command_length = 0;
      var command_names = Object.keys(project_config.commands);

      command_names.forEach(function(key) {
        if (key.length > longest_command_length) {
          longest_command_length = key.length;
        }
      });

      if (command_names.length > 0) {
        config.logger.log("Commands:" + OS.EOL);
      }

      command_names.forEach(function(key) {
        var spacing = "";

        while (key.length + spacing.length < longest_command_length) {
          spacing += " ";
        }

        config.logger.log("  " + key + ": " + spacing + project_config.commands[key]);
      });

      if (project_config.epilogue) {
        console.log(OS.EOL + project_config.epilogue.replace("\n", OS.EOL));
      }

      config.logger.log("");
    }).catch(done);
  }
}

module.exports = command;
<commit_msg>Add deprecation notice for truffle init<commit_after>var command = {
  command: 'init',
  description: 'Initialize new Ethereum project with example contracts and tests',
  builder: {},
  run: function (options, done) {
    var Config = require("truffle-config");
    var Init = require("truffle-init");
    var OS = require("os");

    var config = Config.default().with({
      logger: console
    });

    var example_name = "default";

    if (options._ && options._.length > 0) {
      example_name = options._[0];
      config.logger.log(
        "Using `truffle init` with a specific template is deprecated. " +
          "Please use `truffle unbox` instead."
      );
    }

    Init.fromGithub(config, example_name, config.working_directory).then(function(project_config) {
      var docs_url = project_config.docs_url || "https://github.com/trufflesuite/truffle-init-" + example_name;

      config.logger.log("Project initialized." +
        OS.EOL +
        OS.EOL +
        "  Documentation: " + docs_url +
        OS.EOL
      );

      project_config.commands = project_config.commands || {};

      var longest_command_length = 0;
      var command_names = Object.keys(project_config.commands);

      command_names.forEach(function(key) {
        if (key.length > longest_command_length) {
          longest_command_length = key.length;
        }
      });

      if (command_names.length > 0) {
        config.logger.log("Commands:" + OS.EOL);
      }

      command_names.forEach(function(key) {
        var spacing = "";

        while (key.length + spacing.length < longest_command_length) {
          spacing += " ";
        }

        config.logger.log("  " + key + ": " + spacing + project_config.commands[key]);
      });

      if (project_config.epilogue) {
        console.log(OS.EOL + project_config.epilogue.replace("\n", OS.EOL));
      }

      config.logger.log("");
    }).catch(done);
  }
}

module.exports = command;
<|endoftext|>


<commit_before>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');
// var d       = require('./twitterData.js');
var d = {
  getData: function (req, res, spec) {
    var Twitter = require("twitter");

    var client = new Twitter({
      consumer_key: process.env.TWITTER_CONSUMER_KEY,
      consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
      access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
      access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
    });

    var lat   = spec.lat ? spec.lat : '40.7207919',
    lon     = spec.lon ? spec.lon : '-74.0007582',
    r       = spec.radius ? spec.radius : '0.5km',
    geocode = [lat, lon, r].join(',');

    console.log(spec);
    console.log("geocode: " + geocode);

    var options = {
      geocode: geocode,
      count: 100,
      result_type: 'recent'
    };

    client.get('search/tweets', options, function(error, params, response){
      var rawTweet, newTweet,
      tweetList = [],
      results;

      if (error) {
        console.log("error");
        console.log(JSON.stringify(error));
        throw error;
      }

      if (params && params.hasOwnProperty("statuses")) {
        results = params.statuses;

        console.log(results.length);
        for (var i = 0, l = results.length; i < l; i++) {
          twt = results[i];

          newTweet = {
            id          : twt.id_str,
            lat         : twt.geo.coordinates[0],
            lon         : twt.geo.coordinates[1],
            text        : twt.text,
            datetime    : twt.created_at,
            screen_name : twt.user.screen_name
          };

          tweetList[i] = newTweet;
        }

        res.setHeader('Content-Type', 'text/html');
        res.send("test");
        // console.log(tweetList);

      } else {
        res.setHeader('Content-Type', 'text/html');
        res.send("fail");
      }
      // console.log(JSON.stringify(response));  // Raw response object.
    });
  }
};

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        }
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
            self.zcache = { 'varWeb.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
        self.zcache['varWeb.html'] = fs.readFileSync('./varWeb.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";
            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };

        self.routes['/varWeb'] = function(req, res) {
          console.log(req);
          res.setHeader('Content-Type', 'text/html');
          res.send(self.cache_get('varWeb.html') );
        };

        self.routes['/test'] = function(req, res) {
          // d.getTest(req, res);
          res.setHeader('Content-Type', 'text/html');
          res.send("tweetList");

        };

    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express.createServer();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();
<commit_msg>trying to request with twitterData locally<commit_after>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');
// var d       = require('./twitterData.js');
var d = {
  getData: function (req, res, spec) {
    var Twitter = require("twitter");

    var client = new Twitter({
      consumer_key: process.env.TWITTER_CONSUMER_KEY,
      consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
      access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
      access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
    });

    var lat   = spec.lat ? spec.lat : '40.7207919',
    lon     = spec.lon ? spec.lon : '-74.0007582',
    r       = spec.radius ? spec.radius : '0.5km',
    geocode = [lat, lon, r].join(',');

    console.log(spec);
    console.log("geocode: " + geocode);

    var options = {
      geocode: geocode,
      count: 100,
      result_type: 'recent'
    };

    client.get('search/tweets', options, function(error, params, response){
      var rawTweet, newTweet,
      tweetList = [],
      results;

      if (error) {
        console.log("error");
        console.log(JSON.stringify(error));
        throw error;
      }

      if (params && params.hasOwnProperty("statuses")) {
        results = params.statuses;

        console.log(results.length);
        for (var i = 0, l = results.length; i < l; i++) {
          twt = results[i];

          newTweet = {
            id          : twt.id_str,
            lat         : twt.geo.coordinates[0],
            lon         : twt.geo.coordinates[1],
            text        : twt.text,
            datetime    : twt.created_at,
            screen_name : twt.user.screen_name
          };

          tweetList[i] = newTweet;
        }

        res.setHeader('Content-Type', 'text/html');
        res.send(JSON.stringify(tweetList));
        // console.log(tweetList);

      } else {
        res.setHeader('Content-Type', 'text/html');
        res.send("fail");
      }
      // console.log(JSON.stringify(response));  // Raw response object.
    });
  }
};

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        }
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
            self.zcache = { 'varWeb.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
        self.zcache['varWeb.html'] = fs.readFileSync('./varWeb.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";
            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };

        self.routes['/varWeb'] = function(req, res) {
          console.log(req);
          res.setHeader('Content-Type', 'text/html');
          res.send(self.cache_get('varWeb.html') );
        };

        self.routes['/test'] = function(req, res) {
          d.getTest(req, res);
          // res.setHeader('Content-Type', 'text/html');
          // res.send("tweetList");

        };

    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express.createServer();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule Image
 * @flow
 */
'use strict';

const EdgeInsetsPropType = require('EdgeInsetsPropType');
const ImageResizeMode = require('ImageResizeMode');
const ImageSourcePropType = require('ImageSourcePropType');
const ImageStylePropTypes = require('ImageStylePropTypes');
const NativeMethodsMixin = require('NativeMethodsMixin');
const NativeModules = require('NativeModules');
const React = require('React');
const PropTypes = require('prop-types');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const StyleSheet = require('StyleSheet');
const StyleSheetPropType = require('StyleSheetPropType');

const flattenStyle = require('flattenStyle');
const requireNativeComponent = require('requireNativeComponent');
const resolveAssetSource = require('resolveAssetSource');

const ImageViewManager = NativeModules.ImageViewManager;

/**
 * A React component for displaying different types of images,
 * including network images, static resources, temporary local images, and
 * images from local disk, such as the camera roll.
 *
 * This example shows both fetching and displaying an image from local
 * storage as well as one from network.
 *
 * ```ReactNativeWebPlayer
 * import React, { Component } from 'react';
 * import { AppRegistry, View, Image } from 'react-native';
 *
 * class DisplayAnImage extends Component {
 *   render() {
 *     return (
 *       <View>
 *         <Image
 *           source={require('./img/favicon.png')}
 *         />
 *         <Image
 *           style={{width: 50, height: 50}}
 *           source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}
 *         />
 *       </View>
 *     );
 *   }
 * }
 *
 * // App registration and rendering
 * AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage);
 * ```
 *
 * You can also add `style` to an image:
 *
 * ```ReactNativeWebPlayer
 * import React, { Component } from 'react';
 * import { AppRegistry, View, Image, StyleSheet } from 'react-native';
 *
 * const styles = StyleSheet.create({
 *   stretch: {
 *     width: 50,
 *     height: 200
 *   }
 * });
 *
 * class DisplayAnImageWithStyle extends Component {
 *   render() {
 *     return (
 *       <View>
 *         <Image
 *           style={styles.stretch}
 *           source={require('./img/favicon.png')}
 *         />
 *       </View>
 *     );
 *   }
 * }
 *
 * // App registration and rendering
 * AppRegistry.registerComponent(
 *   'DisplayAnImageWithStyle',
 *   () => DisplayAnImageWithStyle
 * );
 * ```
 *
 * ### GIF and WebP support on Android
 *
 * By default, GIF and WebP are not supported on Android.
 *
 * You will need to add some optional modules in `android/app/build.gradle`, depending on the needs of your app.
 *
 * ```
 * dependencies {
 *   // If your app supports Android versions before Ice Cream Sandwich (API level 14)
 *   compile 'com.facebook.fresco:animated-base-support:0.11.0'
 *
 *   // For animated GIF support
 *   compile 'com.facebook.fresco:animated-gif:0.11.0'
 *
 *   // For WebP support, including animated WebP
 *   compile 'com.facebook.fresco:animated-webp:0.11.0'
 *   compile 'com.facebook.fresco:webpsupport:0.11.0'
 *
 *   // For WebP support, without animations
 *   compile 'com.facebook.fresco:webpsupport:0.11.0'
 * }
 * ```
 *
 * Also, if you use GIF with ProGuard, you will need to add this rule in `proguard-rules.pro` :
 * ```
 * -keep class com.facebook.imagepipeline.animated.factory.AnimatedFactoryImpl {
 *   public AnimatedFactoryImpl(com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory, com.facebook.imagepipeline.core.ExecutorSupplier);
 * }
 * ```
 *
 */
// $FlowFixMe(>=0.41.0)
const Image = React.createClass({
  propTypes: {
    /**
     * > `ImageResizeMode` is an `Enum` for different image resizing modes, set via the
     * > `resizeMode` style property on `Image` components. The values are `contain`, `cover`,
     * > `stretch`, `center`, `repeat`.
     */
    style: StyleSheetPropType(ImageStylePropTypes),
    /**
     * The image source (either a remote URL or a local file resource).
     *
     * This prop can also contain several remote URLs, specified together with
     * their width and height and potentially with scale/other URI arguments.
     * The native side will then choose the best `uri` to display based on the
     * measured size of the image container. A `cache` property can be added to
     * control how networked request interacts with the local cache.
     */
    source: ImageSourcePropType,
    /**
     * A static image to display while loading the image source.
     *
     * - `uri` - a string representing the resource identifier for the image, which
     * should be either a local file path or the name of a static image resource
     * (which should be wrapped in the `require('./path/to/image.png')` function).
     * - `width`, `height` - can be specified if known at build time, in which case
     * these will be used to set the default `<Image/>` component dimensions.
     * - `scale` - used to indicate the scale factor of the image. Defaults to 1.0 if
     * unspecified, meaning that one image pixel equates to one display point / DIP.
     * - `number` - Opaque type returned by something like `require('./image.jpg')`.
     *
     * @platform ios
     */
    defaultSource: PropTypes.oneOfType([
      // TODO: Tooling to support documenting these directly and having them display in the docs.
      PropTypes.shape({
        uri: PropTypes.string,
        width: PropTypes.number,
        height: PropTypes.number,
        scale: PropTypes.number,
      }),
      PropTypes.number,
    ]),
    /**
     * When true, indicates the image is an accessibility element.
     * @platform ios
     */
    accessible: PropTypes.bool,
    /**
     * The text that's read by the screen reader when the user interacts with
     * the image.
     * @platform ios
     */
    accessibilityLabel: PropTypes.node,
    /**
    * blurRadius: the blur radius of the blur filter added to the image
    * @platform ios
    */
    blurRadius: PropTypes.number,
    /**
     * When the image is resized, the corners of the size specified
     * by `capInsets` will stay a fixed size, but the center content and borders
     * of the image will be stretched.  This is useful for creating resizable
     * rounded buttons, shadows, and other resizable assets.  More info in the
     * [official Apple documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets).
     *
     * @platform ios
     */
    capInsets: EdgeInsetsPropType,
    /**
     * The mechanism that should be used to resize the image when the image's dimensions
     * differ from the image view's dimensions. Defaults to `auto`.
     *
     * - `auto`: Use heuristics to pick between `resize` and `scale`.
     *
     * - `resize`: A software operation which changes the encoded image in memory before it
     * gets decoded. This should be used instead of `scale` when the image is much larger
     * than the view.
     *
     * - `scale`: The image gets drawn downscaled or upscaled. Compared to `resize`, `scale` is
     * faster (usually hardware accelerated) and produces higher quality images. This
     * should be used if the image is smaller than the view. It should also be used if the
     * image is slightly bigger than the view.
     *
     * More details about `resize` and `scale` can be found at http://frescolib.org/docs/resizing-rotating.html.
     *
     * @platform android
     */
    resizeMethod: PropTypes.oneOf(['auto', 'resize', 'scale']),
    /**
     * Determines how to resize the image when the frame doesn't match the raw
     * image dimensions.
     *
     * - `cover`: Scale the image uniformly (maintain the image's aspect ratio)
     * so that both dimensions (width and height) of the image will be equal
     * to or larger than the corresponding dimension of the view (minus padding).
     *
     * - `contain`: Scale the image uniformly (maintain the image's aspect ratio)
     * so that both dimensions (width and height) of the image will be equal to
     * or less than the corresponding dimension of the view (minus padding).
     *
     * - `stretch`: Scale width and height independently, This may change the
     * aspect ratio of the src.
     *
     * - `repeat`: Repeat the image to cover the frame of the view. The
     * image will keep it's size and aspect ratio. (iOS only)
     */
    resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch', 'repeat', 'center']),
    /**
     * A unique identifier for this element to be used in UI Automation
     * testing scripts.
     */
    testID: PropTypes.string,
    /**
     * Invoked on mount and layout changes with
     * `{nativeEvent: {layout: {x, y, width, height}}}`.
     */
    onLayout: PropTypes.func,
    /**
     * Invoked on load start.
     *
     * e.g., `onLoadStart={(e) => this.setState({loading: true})}`
     */
    onLoadStart: PropTypes.func,
    /**
     * Invoked on download progress with `{nativeEvent: {loaded, total}}`.
     * @platform ios
     */
    onProgress: PropTypes.func,
    /**
     * Invoked on load error with `{nativeEvent: {error}}`.
     */
    onError: PropTypes.func,
    /**
     * Invoked when a partial load of the image is complete. The definition of
     * what constitutes a "partial load" is loader specific though this is meant
     * for progressive JPEG loads.
     * @platform ios
     */
    onPartialLoad: PropTypes.func,
    /**
     * Invoked when load completes successfully.
     */
    onLoad: PropTypes.func,
    /**
     * Invoked when load either succeeds or fails.
     */
    onLoadEnd: PropTypes.func,
  },

  statics: {
    resizeMode: ImageResizeMode,
    /**
     * Retrieve the width and height (in pixels) of an image prior to displaying it.
     * This method can fail if the image cannot be found, or fails to download.
     *
     * In order to retrieve the image dimensions, the image may first need to be
     * loaded or downloaded, after which it will be cached. This means that in
     * principle you could use this method to preload images, however it is not
     * optimized for that purpose, and may in future be implemented in a way that
     * does not fully load/download the image data. A proper, supported way to
     * preload images will be provided as a separate API.
     *
     * Does not work for static image resources.
     *
     * @param uri The location of the image.
     * @param success The function that will be called if the image was successfully found and width
     * and height retrieved.
     * @param failure The function that will be called if there was an error, such as failing to
     * to retrieve the image.
     *
     * @returns void
     *
     * @platform ios
     */
    getSize: function(
      uri: string,
      success: (width: number, height: number) => void,
      failure?: (error: any) => void,
    ) {
      ImageViewManager.getSize(uri, success, failure || function() {
        console.warn('Failed to get size for image: ' + uri);
      });
    },
    /**
     * Prefetches a remote image for later use by downloading it to the disk
     * cache
     *
     * @param url The remote location of the image.
     *
     * @return The prefetched image.
     */
    prefetch(url: string) {
      return ImageViewManager.prefetchImage(url);
    },
    /**
     * Resolves an asset reference into an object which has the properties `uri`, `width`,
     * and `height`. The input may either be a number (opaque type returned by
     * require('./foo.png')) or an `ImageSource` like { uri: '<http location || file path>' }
     */
    resolveAssetSource: resolveAssetSource,
  },

  mixins: [NativeMethodsMixin],

  /**
   * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We
   * make `this` look like an actual native component class.
   */
  viewConfig: {
    uiViewClassName: 'UIView',
    validAttributes: ReactNativeViewAttributes.UIView
  },

  render: function() {
    const source = resolveAssetSource(this.props.source) || { uri: undefined, width: undefined, height: undefined };

    let sources;
    let style;
    if (Array.isArray(source)) {
      style = flattenStyle([styles.base, this.props.style]) || {};
      sources = source;
    } else {
      const {width, height, uri} = source;
      style = flattenStyle([{width, height}, styles.base, this.props.style]) || {};
      sources = [source];

      if (uri === '') {
        console.warn('source.uri should not be an empty string');
      }
    }

    const resizeMode = this.props.resizeMode || (style || {}).resizeMode || 'cover'; // Workaround for flow bug t7737108
    const tintColor = (style || {}).tintColor; // Workaround for flow bug t7737108

    if (this.props.src) {
      console.warn('The <Image> component requires a `source` property rather than `src`.');
    }

    return (
      <RCTImageView
        {...this.props}
        style={style}
        resizeMode={resizeMode}
        tintColor={tintColor}
        source={sources}
      />
    );
  },
});

const styles = StyleSheet.create({
  base: {
    overflow: 'hidden',
  },
});

const RCTImageView = requireNativeComponent('RCTImageView', Image);

module.exports = Image;
<commit_msg>Update documentation to use newer version of fresco - fixes #13345<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule Image
 * @flow
 */
'use strict';

const EdgeInsetsPropType = require('EdgeInsetsPropType');
const ImageResizeMode = require('ImageResizeMode');
const ImageSourcePropType = require('ImageSourcePropType');
const ImageStylePropTypes = require('ImageStylePropTypes');
const NativeMethodsMixin = require('NativeMethodsMixin');
const NativeModules = require('NativeModules');
const React = require('React');
const PropTypes = require('prop-types');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const StyleSheet = require('StyleSheet');
const StyleSheetPropType = require('StyleSheetPropType');

const flattenStyle = require('flattenStyle');
const requireNativeComponent = require('requireNativeComponent');
const resolveAssetSource = require('resolveAssetSource');

const ImageViewManager = NativeModules.ImageViewManager;

/**
 * A React component for displaying different types of images,
 * including network images, static resources, temporary local images, and
 * images from local disk, such as the camera roll.
 *
 * This example shows both fetching and displaying an image from local
 * storage as well as one from network.
 *
 * ```ReactNativeWebPlayer
 * import React, { Component } from 'react';
 * import { AppRegistry, View, Image } from 'react-native';
 *
 * class DisplayAnImage extends Component {
 *   render() {
 *     return (
 *       <View>
 *         <Image
 *           source={require('./img/favicon.png')}
 *         />
 *         <Image
 *           style={{width: 50, height: 50}}
 *           source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}
 *         />
 *       </View>
 *     );
 *   }
 * }
 *
 * // App registration and rendering
 * AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage);
 * ```
 *
 * You can also add `style` to an image:
 *
 * ```ReactNativeWebPlayer
 * import React, { Component } from 'react';
 * import { AppRegistry, View, Image, StyleSheet } from 'react-native';
 *
 * const styles = StyleSheet.create({
 *   stretch: {
 *     width: 50,
 *     height: 200
 *   }
 * });
 *
 * class DisplayAnImageWithStyle extends Component {
 *   render() {
 *     return (
 *       <View>
 *         <Image
 *           style={styles.stretch}
 *           source={require('./img/favicon.png')}
 *         />
 *       </View>
 *     );
 *   }
 * }
 *
 * // App registration and rendering
 * AppRegistry.registerComponent(
 *   'DisplayAnImageWithStyle',
 *   () => DisplayAnImageWithStyle
 * );
 * ```
 *
 * ### GIF and WebP support on Android
 *
 * By default, GIF and WebP are not supported on Android.
 *
 * You will need to add some optional modules in `android/app/build.gradle`, depending on the needs of your app.
 *
 * ```
 * dependencies {
 *   // If your app supports Android versions before Ice Cream Sandwich (API level 14)
 *   compile 'com.facebook.fresco:animated-base-support:1.0.1'
 *
 *   // For animated GIF support
 *   compile 'com.facebook.fresco:animated-gif:1.0.1'
 *
 *   // For WebP support, including animated WebP
 *   compile 'com.facebook.fresco:animated-webp:1.0.1'
 *   compile 'com.facebook.fresco:webpsupport:1.0.1'
 *
 *   // For WebP support, without animations
 *   compile 'com.facebook.fresco:webpsupport:1.0.1'
 * }
 * ```
 *
 * Also, if you use GIF with ProGuard, you will need to add this rule in `proguard-rules.pro` :
 * ```
 * -keep class com.facebook.imagepipeline.animated.factory.AnimatedFactoryImpl {
 *   public AnimatedFactoryImpl(com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory, com.facebook.imagepipeline.core.ExecutorSupplier);
 * }
 * ```
 *
 */
// $FlowFixMe(>=0.41.0)
const Image = React.createClass({
  propTypes: {
    /**
     * > `ImageResizeMode` is an `Enum` for different image resizing modes, set via the
     * > `resizeMode` style property on `Image` components. The values are `contain`, `cover`,
     * > `stretch`, `center`, `repeat`.
     */
    style: StyleSheetPropType(ImageStylePropTypes),
    /**
     * The image source (either a remote URL or a local file resource).
     *
     * This prop can also contain several remote URLs, specified together with
     * their width and height and potentially with scale/other URI arguments.
     * The native side will then choose the best `uri` to display based on the
     * measured size of the image container. A `cache` property can be added to
     * control how networked request interacts with the local cache.
     */
    source: ImageSourcePropType,
    /**
     * A static image to display while loading the image source.
     *
     * - `uri` - a string representing the resource identifier for the image, which
     * should be either a local file path or the name of a static image resource
     * (which should be wrapped in the `require('./path/to/image.png')` function).
     * - `width`, `height` - can be specified if known at build time, in which case
     * these will be used to set the default `<Image/>` component dimensions.
     * - `scale` - used to indicate the scale factor of the image. Defaults to 1.0 if
     * unspecified, meaning that one image pixel equates to one display point / DIP.
     * - `number` - Opaque type returned by something like `require('./image.jpg')`.
     *
     * @platform ios
     */
    defaultSource: PropTypes.oneOfType([
      // TODO: Tooling to support documenting these directly and having them display in the docs.
      PropTypes.shape({
        uri: PropTypes.string,
        width: PropTypes.number,
        height: PropTypes.number,
        scale: PropTypes.number,
      }),
      PropTypes.number,
    ]),
    /**
     * When true, indicates the image is an accessibility element.
     * @platform ios
     */
    accessible: PropTypes.bool,
    /**
     * The text that's read by the screen reader when the user interacts with
     * the image.
     * @platform ios
     */
    accessibilityLabel: PropTypes.node,
    /**
    * blurRadius: the blur radius of the blur filter added to the image
    * @platform ios
    */
    blurRadius: PropTypes.number,
    /**
     * When the image is resized, the corners of the size specified
     * by `capInsets` will stay a fixed size, but the center content and borders
     * of the image will be stretched.  This is useful for creating resizable
     * rounded buttons, shadows, and other resizable assets.  More info in the
     * [official Apple documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets).
     *
     * @platform ios
     */
    capInsets: EdgeInsetsPropType,
    /**
     * The mechanism that should be used to resize the image when the image's dimensions
     * differ from the image view's dimensions. Defaults to `auto`.
     *
     * - `auto`: Use heuristics to pick between `resize` and `scale`.
     *
     * - `resize`: A software operation which changes the encoded image in memory before it
     * gets decoded. This should be used instead of `scale` when the image is much larger
     * than the view.
     *
     * - `scale`: The image gets drawn downscaled or upscaled. Compared to `resize`, `scale` is
     * faster (usually hardware accelerated) and produces higher quality images. This
     * should be used if the image is smaller than the view. It should also be used if the
     * image is slightly bigger than the view.
     *
     * More details about `resize` and `scale` can be found at http://frescolib.org/docs/resizing-rotating.html.
     *
     * @platform android
     */
    resizeMethod: PropTypes.oneOf(['auto', 'resize', 'scale']),
    /**
     * Determines how to resize the image when the frame doesn't match the raw
     * image dimensions.
     *
     * - `cover`: Scale the image uniformly (maintain the image's aspect ratio)
     * so that both dimensions (width and height) of the image will be equal
     * to or larger than the corresponding dimension of the view (minus padding).
     *
     * - `contain`: Scale the image uniformly (maintain the image's aspect ratio)
     * so that both dimensions (width and height) of the image will be equal to
     * or less than the corresponding dimension of the view (minus padding).
     *
     * - `stretch`: Scale width and height independently, This may change the
     * aspect ratio of the src.
     *
     * - `repeat`: Repeat the image to cover the frame of the view. The
     * image will keep it's size and aspect ratio. (iOS only)
     */
    resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch', 'repeat', 'center']),
    /**
     * A unique identifier for this element to be used in UI Automation
     * testing scripts.
     */
    testID: PropTypes.string,
    /**
     * Invoked on mount and layout changes with
     * `{nativeEvent: {layout: {x, y, width, height}}}`.
     */
    onLayout: PropTypes.func,
    /**
     * Invoked on load start.
     *
     * e.g., `onLoadStart={(e) => this.setState({loading: true})}`
     */
    onLoadStart: PropTypes.func,
    /**
     * Invoked on download progress with `{nativeEvent: {loaded, total}}`.
     * @platform ios
     */
    onProgress: PropTypes.func,
    /**
     * Invoked on load error with `{nativeEvent: {error}}`.
     */
    onError: PropTypes.func,
    /**
     * Invoked when a partial load of the image is complete. The definition of
     * what constitutes a "partial load" is loader specific though this is meant
     * for progressive JPEG loads.
     * @platform ios
     */
    onPartialLoad: PropTypes.func,
    /**
     * Invoked when load completes successfully.
     */
    onLoad: PropTypes.func,
    /**
     * Invoked when load either succeeds or fails.
     */
    onLoadEnd: PropTypes.func,
  },

  statics: {
    resizeMode: ImageResizeMode,
    /**
     * Retrieve the width and height (in pixels) of an image prior to displaying it.
     * This method can fail if the image cannot be found, or fails to download.
     *
     * In order to retrieve the image dimensions, the image may first need to be
     * loaded or downloaded, after which it will be cached. This means that in
     * principle you could use this method to preload images, however it is not
     * optimized for that purpose, and may in future be implemented in a way that
     * does not fully load/download the image data. A proper, supported way to
     * preload images will be provided as a separate API.
     *
     * Does not work for static image resources.
     *
     * @param uri The location of the image.
     * @param success The function that will be called if the image was successfully found and width
     * and height retrieved.
     * @param failure The function that will be called if there was an error, such as failing to
     * to retrieve the image.
     *
     * @returns void
     *
     * @platform ios
     */
    getSize: function(
      uri: string,
      success: (width: number, height: number) => void,
      failure?: (error: any) => void,
    ) {
      ImageViewManager.getSize(uri, success, failure || function() {
        console.warn('Failed to get size for image: ' + uri);
      });
    },
    /**
     * Prefetches a remote image for later use by downloading it to the disk
     * cache
     *
     * @param url The remote location of the image.
     *
     * @return The prefetched image.
     */
    prefetch(url: string) {
      return ImageViewManager.prefetchImage(url);
    },
    /**
     * Resolves an asset reference into an object which has the properties `uri`, `width`,
     * and `height`. The input may either be a number (opaque type returned by
     * require('./foo.png')) or an `ImageSource` like { uri: '<http location || file path>' }
     */
    resolveAssetSource: resolveAssetSource,
  },

  mixins: [NativeMethodsMixin],

  /**
   * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We
   * make `this` look like an actual native component class.
   */
  viewConfig: {
    uiViewClassName: 'UIView',
    validAttributes: ReactNativeViewAttributes.UIView
  },

  render: function() {
    const source = resolveAssetSource(this.props.source) || { uri: undefined, width: undefined, height: undefined };

    let sources;
    let style;
    if (Array.isArray(source)) {
      style = flattenStyle([styles.base, this.props.style]) || {};
      sources = source;
    } else {
      const {width, height, uri} = source;
      style = flattenStyle([{width, height}, styles.base, this.props.style]) || {};
      sources = [source];

      if (uri === '') {
        console.warn('source.uri should not be an empty string');
      }
    }

    const resizeMode = this.props.resizeMode || (style || {}).resizeMode || 'cover'; // Workaround for flow bug t7737108
    const tintColor = (style || {}).tintColor; // Workaround for flow bug t7737108

    if (this.props.src) {
      console.warn('The <Image> component requires a `source` property rather than `src`.');
    }

    return (
      <RCTImageView
        {...this.props}
        style={style}
        resizeMode={resizeMode}
        tintColor={tintColor}
        source={sources}
      />
    );
  },
});

const styles = StyleSheet.create({
  base: {
    overflow: 'hidden',
  },
});

const RCTImageView = requireNativeComponent('RCTImageView', Image);

module.exports = Image;
<|endoftext|>


<commit_before>jQuery(function($) {

  // Debug flag
  var debugMode = false;

  // Default time delay before checking location
  var callBackTime = 100;

  // # px before tracking a reader
  var readerLocation = 150;

  // Set some flags for tracking & execution
  var timer = 0;
  var scroller = false;
  var endOpeningTimes = false;
  var endPatientsSay = false;
  var endSurgeryGPs = false;
  var endServices = false;
  var endParking = false;
  var didComplete = false;

  // Set some time variables to calculate reading time
  var startTime = new Date();
  var beginning = startTime.getTime();
  var totalTime = 0;

  // Get some information about the current page
  var pageTitle = document.title;

  // Track the aticle load
  if (!debugMode) {
      //ga('send', 'event', 'Reading', 'ArticleLoaded', '');

  } else {
      console.log('Start custom analytics');
  }

  // Check the location and track user
  function trackLocation() {
      bottom = $(window).height() + $(window).scrollTop();
      height = $(document).height();
      results = $('.reading-width .sr-only').attr('data-results');
      results_14 = Math.round(results / 4);
      results_12 = Math.round(results / 2);
      results_34 = Math.round(results_14 * 3);

      // If user starts to scroll send an event
      if (bottom > readerLocation && !scroller) {
          currentTime = new Date();
          scrollStart = currentTime.getTime();
          timeToScroll = Math.round((scrollStart - beginning) / 1000);
          if (!debugMode) {
              console.log('started reading ' + timeToScroll);
              ga('send', 'event', 'User started scrolling', timeToScroll+'s');
          } else {
              alert('User started scrolling (Time: ' + timeToScroll + 's)');
          }
          scroller = true;
      }

      if (bottom > $('h2.opening-times:contains("GP")').offset().top + $('h2.opening-times:contains("GP")').outerHeight() && !endOpeningTimes) {
          currentTime = new Date();
          openingTimesScrollEnd = currentTime.getTime();
          timeToOpeningTimesEnd = Math.round((openingTimesScrollEnd - scrollStart) / 1000);
          if (!debugMode) {
              ga('send', 'event', 'User reached the "GP Opening Times" section', timeToOpeningTimesEnd+'s');
          } else {
              alert('User reached the "GP Opening Times" section (Time: ' + timeToOpeningTimesEnd + 's)');
          }
          endOpeningTimes = true;
      }

      if (bottom > $('h2:contains("What patients say about this surgery")').offset().top + $('h2:contains("What patients say about this surgery")').outerHeight() && !endPatientsSay) {
          currentTime = new Date();
          patientsSayScrollEnd = currentTime.getTime();
          timeToPatientsSayEnd = Math.round((patientsSayScrollEnd - scrollStart) / 1000);
          if (!debugMode) {
              ga('send', 'event', 'User reached the "What patients say about this surgery" section', timeToPatientsSayEnd+'s');
          } else {
              alert('User reached the "What patients say about this surgery" section (Time: ' + timeToPatientsSayEnd + 's)');
          }
          endPatientsSay = true;
      }

      if (bottom > $('h2:contains("GPs at this surgery")').offset().top + $('h2:contains("GPs at this surgery")').outerHeight() && !endSurgeryGPs) {
          currentTime = new Date();
          surgeryGPsScrollEnd = currentTime.getTime();
          timeToSurgeryGPsEnd = Math.round((surgeryGPsScrollEnd - scrollStart) / 1000);
          if (!debugMode) {
              ga('send', 'event', 'User reached the "GPs at this surgery" section', timeToSurgeryGPsEnd+'s');
          } else {
              alert('User reached the "GPs at this surgery" section (Time: ' + timeToSurgeryGPsEnd + 's)');
          }
          endSurgeryGPs = true;
      }

      if (bottom > $('h2:contains("Services at this surgery")').offset().top + $('h2:contains("Services at this surgery")').outerHeight() && !endServices) {
          currentTime = new Date();
          servicesScrollEnd = currentTime.getTime();
          timeToServicesEnd = Math.round((servicesScrollEnd - scrollStart) / 1000);
          if (!debugMode) {
              ga('send', 'event', 'User reached the "Services at this surgery" section', timeToServicesEnd+'s');
          } else {
              alert('User reached the "Services at this surgery" section (Time: ' + timeToServicesEnd + 's)');
          }
          endServices = true;
      }

      if (bottom > $('h2:contains("Parking")').offset().top + $('h2:contains("Parking")').outerHeight() && !endParking) {
          currentTime = new Date();
          parkingScrollEnd = currentTime.getTime();
          timeToParkingEnd = Math.round((parkingScrollEnd - scrollStart) / 1000);
          if (!debugMode) {
              ga('send', 'event', 'User reached the "Parking and accessibility" section', timeToParkingEnd+'s');
          } else {
              alert('User reached the "Parking and accessibility" section (Time: ' + timeToParkingEnd + 's)');
          }
          endParking = true;
      }

      if (bottom > $('footer ul.link-list').offset().top + $('footer ul.link-list').outerHeight() && !didComplete) {
          currentTime = new Date();
          end = currentTime.getTime();
          totalTime = Math.round((end - scrollStart) / 1000);
          if (!debugMode) {
              if (totalTime < 20) {
                  _gaq.push(['_setCustomVar', 5, 'ReaderType', 'Scanner', 2]);
              } else {
                  _gaq.push(['_setCustomVar', 5, 'ReaderType', 'Reader', 2]);
              }
              ga('send', 'event', 'User reached the end of the page', totalTime+'s');
          } else {
              alert('User reached the end of the page (Time: ' + totalTime + 's)');
          }
          didComplete = true;
      }
  }

  // Track the scrolling and track location
  $(window).scroll(function() {
      if (timer) {
          clearTimeout(timer);
      }

      // Use a buffer so we don't call trackLocation too often.
      timer = setTimeout(trackLocation, callBackTime);
  });

});
<commit_msg>:yum: optimising custom analytics code<commit_after>jQuery(function($) {

  // Debug flag
  var debugMode = true;

  // Default time delay before checking location
  var callBackTime = 100;

  // # px before tracking a reader
  var readerLocation = 150;

  // Set some flags for tracking & execution
  var timer = 0;
  var scroller = false;
  var endOpeningTimes = false;
  var endPatientsSay = false;
  var endSurgeryGPs = false;
  var endServices = false;
  var endParking = false;
  var didComplete = false;

  // Set some time variables to calculate reading time
  var startTime = new Date();
  var beginning = startTime.getTime();
  var totalTime = 0;

  // Get some information about the current page
  var pageTitle = document.title;

  function scrolledSection(start, section) {
    currentTime = new Date();
    if (start) {
      scrollStart = currentTime.getTime();
      timeToScroll = Math.round((scrollStart - beginning) / 1000);
      if (!debugMode) {
          ga('send', 'event', section, timeToScroll+'s');
      } else {
          alert(section + ' (Time: ' + timeToScroll + 's)');
      }

    } else {
      scrollEnd = currentTime.getTime();
      timeToScroll = Math.round((scrollEnd - scrollStart) / 1000);
      if (!debugMode) {
          ga('send', 'event', 'User reached the "' + section +'" section', timeToScroll+'s');
      } else {
          alert('User reached the "' + section + '" section (Time: ' + timeToScroll + 's)');
      }
    }
    scroller = true;
  }

  // Check the location and track user
  function trackLocation() {
      bottom = $(window).height() + $(window).scrollTop();
      height = $(document).height();
      results = $('.reading-width .sr-only').attr('data-results');
      results_14 = Math.round(results / 4);
      results_12 = Math.round(results / 2);
      results_34 = Math.round(results_14 * 3);

      // If user starts to scroll send an event
      if (bottom > readerLocation && !scroller) {
        scrolledSection(true, 'User started scrolling');
        scroller = true;
      }

      if ($('h2.opening-times:contains("GP")').length && bottom > $('h2.opening-times:contains("GP")').offset().top + $('h2.opening-times:contains("GP")').outerHeight() && !endOpeningTimes) {
        scrolledSection(false, 'GP Opening Times');
        endOpeningTimes = true;
      }

      if ($('h2:contains("What patients say about this surgery")').length && bottom > $('h2:contains("What patients say about this surgery")').offset().top + $('h2:contains("What patients say about this surgery")').outerHeight() && !endPatientsSay) {
        scrolledSection(false, 'What patients say about this surgery');
        endPatientsSay = true;
      }

      if ($('h2:contains("GPs at this surgery")').length && bottom > $('h2:contains("GPs at this surgery")').offset().top + $('h2:contains("GPs at this surgery")').outerHeight() && !endSurgeryGPs) {
        scrolledSection(false, 'GPs at this surgery');
        endSurgeryGPs = true;
      }

      if ($('h2:contains("Services at this surgery")').length && bottom > $('h2:contains("Services at this surgery")').offset().top + $('h2:contains("Services at this surgery")').outerHeight() && !endServices) {
        scrolledSection(false, 'Services at this surgery');
        endServices = true;
      }

      if ($('h2:contains("Parking")').length && bottom > $('h2:contains("Parking")').offset().top + $('h2:contains("Parking")').outerHeight() && !endParking) {
        scrolledSection(false, 'Parking and accessibility');
        endParking = true;
      }

      if (bottom > $('footer ul.link-list').offset().top + $('footer ul.link-list').outerHeight() && !didComplete) {
        scrolledSection(false, 'end of the page');
        didComplete = true;
      }
  }

  // Track the scrolling and track location
  $(window).scroll(function() {
      if (timer) {
          clearTimeout(timer);
      }

      // Use a buffer so we don't call trackLocation too often.
      timer = setTimeout(trackLocation, callBackTime);
  });

});
<|endoftext|>


<commit_before>// Copyright (C) 2010 Combodo SARL
//
//   This program is free software; you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation; version 3 of the License.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program; if not, write to the Free Software
//   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function ExtKeyWidget(id, sClass, sAttCode, sSuffix, bSelectMode, oWizHelper)
{
	this.id = id;
	this.sClass = sClass;
	this.sAttCode = sAttCode;
	this.sSuffix = sSuffix;
	this.emptyHtml = ''; // content to be displayed when the search results are empty (when opening the dialog)
	this.emptyOnClose = true; // Workaround for the JQuery dialog being very slow when opening and closing if the content contains many INPUT tags
	this.oWizardHelper = oWizHelper;
	this.ajax_request = null;
	this.bSelectMode = bSelectMode; // true if the edited field is a SELECT, false if it's an autocomplete
	var me = this;

	this.Init = function()
	{
		// make sure that the form is clean
		$('#'+this.id+'_btnRemove').attr('disabled','disabled');
		$('#'+this.id+'_linksToRemove').val('');
	}

	this.StopPendingRequest = function()
	{
		if (me.ajax_request)
		{
			me.ajax_request.Abort();
			me.ajax_request = null;
		}
	}

	this.Search = function()
	{
		$('#ac_dlg_'+me.id).dialog('open');
		this.UpdateSizes();
		this.UpdateButtons();
	}

	this.UpdateSizes = function()
	{
		var dlg = $('#ac_dlg_'+me.id);
		var searchForm = dlg.find('div.display_block:first'); // Top search form, enclosing display_block
		var results = $('#dr_'+me.id);
		padding_right = parseInt(dlg.css('padding-right').replace('px', ''));
		padding_left = parseInt(dlg.css('padding-left').replace('px', ''));
		padding_top = parseInt(dlg.css('padding-top').replace('px', ''));
		padding_bottom = parseInt(dlg.css('padding-bottom').replace('px', ''));
		width = dlg.innerWidth() - padding_right - padding_left - 22; // 5 (margin-left) + 5 (padding-left) + 5 (padding-right) + 5 (margin-right) + 2 for rounding !
		height = dlg.innerHeight() - padding_top - padding_bottom -22;
		form_height = searchForm.outerHeight();
		results.height(height - form_height - 40); // Leave some space for the buttons
	}

	this.UpdateButtons = function()
	{
		var okBtn = $('#btn_ok_'+me.id);
		if ($('#fr_'+me.id+' input[name=selectObject]:checked').length > 0)
		{
			okBtn.attr('disabled', '');
		}
		else
		{
			okBtn.attr('disabled', 'disabled');
		}
	}

	this.DoSearchObjects = function(id)
	{
		var theMap = { sAttCode: me.sAttCode,
					   iInputId: me.id,
					   sSuffix: me.sSuffix,
					 }

		// Gather the parameters from the search form
		$('#fs_'+me.id+' :input').each(
			function(i)
			{
				if (this.name != '')
				{
					theMap[this.name] = this.value;
				}
			}
		);

		me.oWizardHelper.UpdateWizard();
		theMap['json'] = me.oWizardHelper.ToJSON();

		theMap['sRemoteClass'] = theMap['class'];  // swap 'class' (defined in the form) and 'remoteClass'
		theMap['class'] = me.sClass;
		theMap.operation = 'searchObjectsToSelect'; // Override what is defined in the form itself

		sSearchAreaId = '#dr_'+me.id;
		//$(sSearchAreaId).html('

');
		$(sSearchAreaId).block();
		me.UpdateButtons();

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and display the results
		me.ajax_request = $.post( 'ajax.render.php', theMap,
			function(data)
			{
				$(sSearchAreaId).html(data);
				$(sSearchAreaId+' .listResults').tableHover();
				$(sSearchAreaId+' .listResults').tablesorter( { headers: {0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ); // sortable and zebra tables
				$('#fr_'+me.id+' input:radio').click(function() { me.UpdateButtons(); });
				me.UpdateButtons();
				me.ajax_request = null;
			},
			'html'
		);

		return false; // Don't submit the form, stay in the current page !
	}

	this.DoOk = function()
	{
		var iObjectId = $('#fr_'+me.id+' input[name=selectObject]:checked').val();
		$('#ac_dlg_'+this.id).dialog('close');
		$('#label_'+this.id).addClass('ac_loading');

		// Query the server again to get the display name of the selected object
		var theMap = { sAttCode: me.sAttCode,
				   iInputId: me.id,
				   iObjectId: iObjectId,
				   sSuffix: me.sSuffix,
				   'class': me.sClass,
				   operation: 'getObjectName'
				 }

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and get the result back directly in JSON
		me.ajax_request = $.post( 'ajax.render.php', theMap,
			function(data)
			{
				$('#label_'+me.id).val(data.name);
				$('#label_'+me.id).removeClass('ac_loading');
				$('#'+me.id).val(iObjectId);
				$('#'+me.id).trigger('validate');
				$('#label_'+me.id).focus();
				me.ajax_request = null;
			},
			'json'
		);

		return false; // Do NOT submit the form in case we are called by OnSubmit...
	}

	// Workaround for a ui.jquery limitation: if the content of
	// the dialog contains many INPUTs, closing and opening the
	// dialog is very slow. So empty it each time.
	this.OnClose = function()
	{
		// called by the dialog, so in the context 'this' points to the jQueryObject
		if (me.emptyOnClose)
		{
			$('#dr_'+me.id).html(me.emptyHtml);
		}
		$('#label_'+me.id).focus();
	}

	this.CreateObject = function(oWizHelper)
	{
		// Query the server to get the form to create a target object
		$('#label_'+me.id).addClass('ac_loading');
		me.oWizardHelper.UpdateWizard();
		var theMap = { sAttCode: me.sAttCode,
				   iInputId: me.id,
				   sSuffix: me.sSuffix,
				   'class': me.sClass,
				   'json': me.oWizardHelper.ToJSON(),
				   operation: 'objectCreationForm'
				 }

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and get the result back directly in HTML
		me.ajax_request = $.post( 'ajax.render.php', theMap,
			function(data)
			{
				$('#ajax_'+me.id).html(data);
				$('#ac_create_'+me.id).dialog('open');
				$('#ac_create_'+me.id).dialog( "option", "close", me.OnCloseCreateObject );
				// Modify the action of the cancel button
				$('#ac_create_'+me.id+' button.cancel').unbind('click').click( me.CloseCreateObject );
				me.ajax_request = null;
			},
			'html'
		);
	}

	this.CloseCreateObject = function()
	{
		$('#ac_create_'+me.id).dialog( "close" );
	}

	this.OnCloseCreateObject = function()
	{
		$('#label_'+me.id).removeClass('ac_loading');
		$('#label_'+me.id).focus();
		$('#ac_create_'+me.id).dialog("destroy");
		$('#ac_create_'+me.id).remove();
		$('#ajax_'+me.id).html('');
	}

	this.DoCreateObject = function()
	{
		var sFormId = $('#dcr_'+me.id+' form').attr('id');
		if (CheckFields(sFormId, true))
		{
			$('#'+sFormId).block();
			var theMap = { sAttCode: me.sAttCode,
					   iInputId: me.id,
					   sSuffix: me.sSuffix,
					   'class': me.sClass,
					   'json': me.oWizardHelper.ToJSON()
					 }

			// Gather the values from the form
			// Gather the parameters from the search form
			$('#'+sFormId+' :input').each(
				function(i)
				{
					if (this.name != '')
					{
						theMap[this.name] = this.value;
					}
				}
			);
			// Override the 'operation' code
			theMap['operation'] = 'doCreateObject';
			theMap['class'] = me.sClass;

			$('#ac_create_'+me.id).dialog('close');

			// Make sure that we cancel any pending request before issuing another
			// since responses may arrive in arbitrary order
			me.StopPendingRequest();

			// Run the query and get the result back directly in JSON
			me.ajax_request = $.post( 'ajax.render.php', theMap,
				function(data)
				{
					if (me.bSelectMode)
					{
						// Add the newly created object to the drop-down list and select it
						$('<option/>', { value : data.id }).text(data.name).appendTo('#'+me.id);
						$('#'+me.id+' option[value="'+data.id+'"]').attr('selected', 'selected');
						$('#'+me.id).focus();
					}
					else
					{
						// Put the value corresponding to the newly created object in the autocomplete
						$('#label_'+me.id).val(data.name);
						$('#'+me.id).val(data.id);
						$('#label_'+me.id).removeClass('ac_loading');
						$('#label_'+me.id).focus();
					}
					$('#'+me.id).trigger('validate');
					me.ajax_request = null;
				},
				'json'
			);
		}
		return false; // do NOT submit the form
	}
}<commit_msg>- Provide some feedback while loading the "creation" dialog in case of a "SELECT".<commit_after>// Copyright (C) 2010 Combodo SARL
//
//   This program is free software; you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation; version 3 of the License.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program; if not, write to the Free Software
//   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function ExtKeyWidget(id, sClass, sAttCode, sSuffix, bSelectMode, oWizHelper)
{
	this.id = id;
	this.sClass = sClass;
	this.sAttCode = sAttCode;
	this.sSuffix = sSuffix;
	this.emptyHtml = ''; // content to be displayed when the search results are empty (when opening the dialog)
	this.emptyOnClose = true; // Workaround for the JQuery dialog being very slow when opening and closing if the content contains many INPUT tags
	this.oWizardHelper = oWizHelper;
	this.ajax_request = null;
	this.bSelectMode = bSelectMode; // true if the edited field is a SELECT, false if it's an autocomplete
	this.v_html = '';
	var me = this;

	this.Init = function()
	{
		// make sure that the form is clean
		$('#'+this.id+'_btnRemove').attr('disabled','disabled');
		$('#'+this.id+'_linksToRemove').val('');
	}

	this.StopPendingRequest = function()
	{
		if (me.ajax_request)
		{
			me.ajax_request.Abort();
			me.ajax_request = null;
		}
	}

	this.Search = function()
	{
		$('#ac_dlg_'+me.id).dialog('open');
		this.UpdateSizes();
		this.UpdateButtons();
	}

	this.UpdateSizes = function()
	{
		var dlg = $('#ac_dlg_'+me.id);
		var searchForm = dlg.find('div.display_block:first'); // Top search form, enclosing display_block
		var results = $('#dr_'+me.id);
		padding_right = parseInt(dlg.css('padding-right').replace('px', ''));
		padding_left = parseInt(dlg.css('padding-left').replace('px', ''));
		padding_top = parseInt(dlg.css('padding-top').replace('px', ''));
		padding_bottom = parseInt(dlg.css('padding-bottom').replace('px', ''));
		width = dlg.innerWidth() - padding_right - padding_left - 22; // 5 (margin-left) + 5 (padding-left) + 5 (padding-right) + 5 (margin-right) + 2 for rounding !
		height = dlg.innerHeight() - padding_top - padding_bottom -22;
		form_height = searchForm.outerHeight();
		results.height(height - form_height - 40); // Leave some space for the buttons
	}

	this.UpdateButtons = function()
	{
		var okBtn = $('#btn_ok_'+me.id);
		if ($('#fr_'+me.id+' input[name=selectObject]:checked').length > 0)
		{
			okBtn.attr('disabled', '');
		}
		else
		{
			okBtn.attr('disabled', 'disabled');
		}
	}

	this.DoSearchObjects = function(id)
	{
		var theMap = { sAttCode: me.sAttCode,
					   iInputId: me.id,
					   sSuffix: me.sSuffix,
					 }

		// Gather the parameters from the search form
		$('#fs_'+me.id+' :input').each(
			function(i)
			{
				if (this.name != '')
				{
					theMap[this.name] = this.value;
				}
			}
		);

		me.oWizardHelper.UpdateWizard();
		theMap['json'] = me.oWizardHelper.ToJSON();

		theMap['sRemoteClass'] = theMap['class'];  // swap 'class' (defined in the form) and 'remoteClass'
		theMap['class'] = me.sClass;
		theMap.operation = 'searchObjectsToSelect'; // Override what is defined in the form itself

		sSearchAreaId = '#dr_'+me.id;
		//$(sSearchAreaId).html('

');
		$(sSearchAreaId).block();
		me.UpdateButtons();

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and display the results
		me.ajax_request = $.post( 'ajax.render.php', theMap,
			function(data)
			{
				$(sSearchAreaId).html(data);
				$(sSearchAreaId+' .listResults').tableHover();
				$(sSearchAreaId+' .listResults').tablesorter( { headers: {0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ); // sortable and zebra tables
				$('#fr_'+me.id+' input:radio').click(function() { me.UpdateButtons(); });
				me.UpdateButtons();
				me.ajax_request = null;
			},
			'html'
		);

		return false; // Don't submit the form, stay in the current page !
	}

	this.DoOk = function()
	{
		var iObjectId = $('#fr_'+me.id+' input[name=selectObject]:checked').val();
		$('#ac_dlg_'+this.id).dialog('close');
		$('#label_'+this.id).addClass('ac_loading');

		// Query the server again to get the display name of the selected object
		var theMap = { sAttCode: me.sAttCode,
				   iInputId: me.id,
				   iObjectId: iObjectId,
				   sSuffix: me.sSuffix,
				   'class': me.sClass,
				   operation: 'getObjectName'
				 }

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and get the result back directly in JSON
		me.ajax_request = $.post( 'ajax.render.php', theMap,
			function(data)
			{
				$('#label_'+me.id).val(data.name);
				$('#label_'+me.id).removeClass('ac_loading');
				$('#'+me.id).val(iObjectId);
				$('#'+me.id).trigger('validate');
				$('#label_'+me.id).focus();
				me.ajax_request = null;
			},
			'json'
		);

		return false; // Do NOT submit the form in case we are called by OnSubmit...
	}

	// Workaround for a ui.jquery limitation: if the content of
	// the dialog contains many INPUTs, closing and opening the
	// dialog is very slow. So empty it each time.
	this.OnClose = function()
	{
		// called by the dialog, so in the context 'this' points to the jQueryObject
		if (me.emptyOnClose)
		{
			$('#dr_'+me.id).html(me.emptyHtml);
		}
		$('#label_'+me.id).focus();
	}

	this.CreateObject = function(oWizHelper)
	{
		// Query the server to get the form to create a target object
		if (me.bSelectMode)
		{
			me.v_html = $('#v_'+me.id).html();
			$('#v_'+me.id).html('');
		}
		else
		{
			$('#label_'+me.id).addClass('ac_loading');
		}
		me.oWizardHelper.UpdateWizard();
		var theMap = { sAttCode: me.sAttCode,
				   iInputId: me.id,
				   sSuffix: me.sSuffix,
				   'class': me.sClass,
				   'json': me.oWizardHelper.ToJSON(),
				   operation: 'objectCreationForm'
				 }

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and get the result back directly in HTML
		me.ajax_request = $.post( 'ajax.render.php', theMap,
			function(data)
			{
				$('#ajax_'+me.id).html(data);
				$('#ac_create_'+me.id).dialog('open');
				$('#ac_create_'+me.id).dialog( "option", "close", me.OnCloseCreateObject );
				// Modify the action of the cancel button
				$('#ac_create_'+me.id+' button.cancel').unbind('click').click( me.CloseCreateObject );
				me.ajax_request = null;
			},
			'html'
		);
	}

	this.CloseCreateObject = function()
	{
		$('#ac_create_'+me.id).dialog( "close" );
	}

	this.OnCloseCreateObject = function()
	{
		if (me.bSelectMode)
		{
			$('#v_'+me.id).html(me.v_html);
		}
		else
		{
			$('#label_'+me.id).removeClass('ac_loading');
		}
		$('#label_'+me.id).focus();
		$('#ac_create_'+me.id).dialog("destroy");
		$('#ac_create_'+me.id).remove();
		$('#ajax_'+me.id).html('');
	}

	this.DoCreateObject = function()
	{
		var sFormId = $('#dcr_'+me.id+' form').attr('id');
		if (CheckFields(sFormId, true))
		{
			$('#'+sFormId).block();
			var theMap = { sAttCode: me.sAttCode,
					   iInputId: me.id,
					   sSuffix: me.sSuffix,
					   'class': me.sClass,
					   'json': me.oWizardHelper.ToJSON()
					 }

			// Gather the values from the form
			// Gather the parameters from the search form
			$('#'+sFormId+' :input').each(
				function(i)
				{
					if (this.name != '')
					{
						theMap[this.name] = this.value;
					}
				}
			);
			// Override the 'operation' code
			theMap['operation'] = 'doCreateObject';
			theMap['class'] = me.sClass;

			$('#ac_create_'+me.id).dialog('close');

			// Make sure that we cancel any pending request before issuing another
			// since responses may arrive in arbitrary order
			me.StopPendingRequest();

			// Run the query and get the result back directly in JSON
			me.ajax_request = $.post( 'ajax.render.php', theMap,
				function(data)
				{
					if (me.bSelectMode)
					{
						// Add the newly created object to the drop-down list and select it
						$('<option/>', { value : data.id }).text(data.name).appendTo('#'+me.id);
						$('#'+me.id+' option[value="'+data.id+'"]').attr('selected', 'selected');
						$('#'+me.id).focus();
					}
					else
					{
						// Put the value corresponding to the newly created object in the autocomplete
						$('#label_'+me.id).val(data.name);
						$('#'+me.id).val(data.id);
						$('#label_'+me.id).removeClass('ac_loading');
						$('#label_'+me.id).focus();
					}
					$('#'+me.id).trigger('validate');
					me.ajax_request = null;
				},
				'json'
			);
		}
		return false; // do NOT submit the form
	}
}<|endoftext|>


<commit_before>// Open the database and create schema (if needed)
var db = Ti.Database.open('todo.sqlite');

db.execute('CREATE TABLE IF NOT EXISTS TODO_ITEMS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, IS_COMPLETE INTEGER)');

// User interface (UI) construction
var win = Ti.UI.createWindow({
	backgroundColor: '#ffffff',
	title: 'To Do List'
});

var headerView = Ti.UI.createView({
	height: '50dp',
	width: '100%',
	backgroundColor: '#885511',
	layout: 'horizontal',
	top: 0
});

var txtTaskName = Ti.UI.createTextField({
	left: 15,
	width: '75%',
	height: Ti.UI.FILL,
	hintText: 'Enter New Task Name',
	borderColor: '#000000',
	backgroundColor: '#ffffff'
});
headerView.add(txtTaskName);

var btnAdd = Ti.UI.createButton({
	backgroundImage: 'add_button.png',
	left: 15,
	height: '45dp',
	width: '45dp'
});

btnAdd.addEventListener('click', function(e) {
	addTask(txtTaskName.value);
});

txtTaskName.addEventListener('return', function() {
	btnAdd.fireEvent('click');
});

headerView.add(btnAdd);
win.add(headerView);

var taskView = Ti.UI.createView({
	top: '50dp',
	width: '100%',
	backgroundColor: '#eeeeee'
});

var taskList = Ti.UI.createTableView({
	width: Ti.UI.FILL,
	height: Ti.UI.FILL,
	separatorColor: '#bb8888'
});

taskList.addEventListener('click', function(e) {
	var todoItem = e.rowData;

	db.execute('UPDATE TODO_ITEMS SET IS_COMPLETE = ? WHERE ID = ?',
				(todoItem.hasCheck ? 0 : 1), todoItem.id);
	refreshTaskList();
});

taskView.add(taskList);
win.add(taskView);

var buttonBar = Ti.UI.createView({
	height: '50dp',
	width: '100%',
	backgroundColor: '#885511',
	bottom: 0
});

var basicSwitch;

if (Ti.Platform.name === ' iPhone OS') {
    basicSwitch = Ti.UI.iOS.createTabbedBar({
    	labels: ['All', 'Active'],
    	left: 5,
    	backgroundColor: buttonBar.backgroundColor,
    	style: Titanium.UI.iPhone.SystemButtonStyle.BAR,
    	index: 0
    });

    basicSwitch.addEventListener('click', function(e) {
   		toggleAllTasks(e.index === 0);
    });
} else {
    basicSwitch = Ti.UI.createSwitch({
    	value: true,
    	left: 5,
    	titleOn: 'All',
    	titleOff: 'Active'
    });

    basicSwitch.addEventListener('change', function(e) {
        toggleAllTasks(e.value === true);
    });
}

buttonBar.add(basicSwitch);

var btnClearComplete = Ti.UI.createButton({
	title: 'Clear Complete',
	right: 5
});

btnClearComplete.addEventListener('click', function(e) {
	db.execute('DELETE FROM TODO_ITEMS WHERE IS_COMPLETE = 1;');
	refreshTaskList();
});

buttonBar.add(btnClearComplete);

win.add(buttonBar);

// Make sure the dababase is closed when the app exits
win.addEventListener('close', function() {
	db.close();
});

refreshTaskList();
win.open();

function addTask(name) {
    db.execute('INSERT INTO TODO_ITEMS (NAME, IS_COMPLETE) VALUES (?, 0)', name);

    txtTaskName.value = '';
    txtTaskName.blur();
    refreshTaskList();
}

function refreshTaskList() {
	var rows = db.execute('SELECT * FROM TODO_ITEMS');
	var data = [];

	while (rows.isValidRow()) {
		var isComplete = rows.fieldByName('IS_COMPLETE');

		data.push({
			title: '' + rows.fieldByName('NAME') + '',
			hasCheck: (isComplete===1) ? true : false,
			id: rows.fieldByName('ID'),
			color: '#bbaaaa',
			className: 'task'
		});

		rows.next();
	};

	taskList.setData(data);
}

function toggleAllTasks(showAll) {
    if (showAll) {
        refreshTaskList();
    } else {
        var section = taskList.data[0];

        for (var i = 0; i < section.rowCount; i++) {
            var row = section.rows[i];

            if (row.hasCheck) {
                taskList.deleteRow(i);
            }
        }
    }
}<commit_msg>Removed extra space<commit_after>// Open the database and create schema (if needed)
var db = Ti.Database.open('todo.sqlite');

db.execute('CREATE TABLE IF NOT EXISTS TODO_ITEMS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, IS_COMPLETE INTEGER)');

// User interface (UI) construction
var win = Ti.UI.createWindow({
	backgroundColor: '#ffffff',
	title: 'To Do List'
});

var headerView = Ti.UI.createView({
	height: '50dp',
	width: '100%',
	backgroundColor: '#885511',
	layout: 'horizontal',
	top: 0
});

var txtTaskName = Ti.UI.createTextField({
	left: 15,
	width: '75%',
	height: Ti.UI.FILL,
	hintText: 'Enter New Task Name',
	borderColor: '#000000',
	backgroundColor: '#ffffff'
});
headerView.add(txtTaskName);

var btnAdd = Ti.UI.createButton({
	backgroundImage: 'add_button.png',
	left: 15,
	height: '45dp',
	width: '45dp'
});

btnAdd.addEventListener('click', function(e) {
	addTask(txtTaskName.value);
});

txtTaskName.addEventListener('return', function() {
	btnAdd.fireEvent('click');
});

headerView.add(btnAdd);
win.add(headerView);

var taskView = Ti.UI.createView({
	top: '50dp',
	width: '100%',
	backgroundColor: '#eeeeee'
});

var taskList = Ti.UI.createTableView({
	width: Ti.UI.FILL,
	height: Ti.UI.FILL,
	separatorColor: '#bb8888'
});

taskList.addEventListener('click', function(e) {
	var todoItem = e.rowData;

	db.execute('UPDATE TODO_ITEMS SET IS_COMPLETE = ? WHERE ID = ?',
				(todoItem.hasCheck ? 0 : 1), todoItem.id);
	refreshTaskList();
});

taskView.add(taskList);
win.add(taskView);

var buttonBar = Ti.UI.createView({
	height: '50dp',
	width: '100%',
	backgroundColor: '#885511',
	bottom: 0
});

var basicSwitch;

if (Ti.Platform.name === 'iPhone OS') {
    basicSwitch = Ti.UI.iOS.createTabbedBar({
    	labels: ['All', 'Active'],
    	left: 5,
    	backgroundColor: buttonBar.backgroundColor,
    	style: Titanium.UI.iPhone.SystemButtonStyle.BAR,
    	index: 0
    });

    basicSwitch.addEventListener('click', function(e) {
   		toggleAllTasks(e.index === 0);
    });
} else {
    basicSwitch = Ti.UI.createSwitch({
    	value: true,
    	left: 5,
    	titleOn: 'All',
    	titleOff: 'Active'
    });

    basicSwitch.addEventListener('change', function(e) {
        toggleAllTasks(e.value === true);
    });
}

buttonBar.add(basicSwitch);

var btnClearComplete = Ti.UI.createButton({
	title: 'Clear Complete',
	right: 5
});

btnClearComplete.addEventListener('click', function(e) {
	db.execute('DELETE FROM TODO_ITEMS WHERE IS_COMPLETE = 1;');
	refreshTaskList();
});

buttonBar.add(btnClearComplete);

win.add(buttonBar);

// Make sure the dababase is closed when the app exits
win.addEventListener('close', function() {
	db.close();
});

refreshTaskList();
win.open();

function addTask(name) {
    db.execute('INSERT INTO TODO_ITEMS (NAME, IS_COMPLETE) VALUES (?, 0)', name);

    txtTaskName.value = '';
    txtTaskName.blur();
    refreshTaskList();
}

function refreshTaskList() {
	var rows = db.execute('SELECT * FROM TODO_ITEMS');
	var data = [];

	while (rows.isValidRow()) {
		var isComplete = rows.fieldByName('IS_COMPLETE');

		data.push({
			title: '' + rows.fieldByName('NAME') + '',
			hasCheck: (isComplete===1) ? true : false,
			id: rows.fieldByName('ID'),
			color: '#bbaaaa',
			className: 'task'
		});

		rows.next();
	};

	taskList.setData(data);
}

function toggleAllTasks(showAll) {
    if (showAll) {
        refreshTaskList();
    } else {
        var section = taskList.data[0];

        for (var i = 0; i < section.rowCount; i++) {
            var row = section.rows[i];

            if (row.hasCheck) {
                taskList.deleteRow(i);
            }
        }
    }
}<|endoftext|>