<commit_before>(function($) {
  "use strict";
  var compareFunction = function(a, b) {
    return a - b;
  };
  var inittree = function(binheap) {
    var size = binheap.size(),
      bt = binheap._tree,
      nodes = [];
    var donode = function(node, pos) {
      if (pos === 1) {
        node.value(binheap.value(pos - 1));
      }
      node.element.attr("data-jsav-heap-index", pos);
      nodes[pos - 1] = node;
      var lpos = pos * 2,
          rpos = lpos + 1;
      if (lpos <= size) {
        if (!node.left()) {
          node.left(binheap.value(lpos - 1));
        } else {
          node.left().value(binheap.value(lpos - 1));
        }
        donode(node.left(), lpos);
      }
      if (rpos <= size) {
        if (!node.right()) {
          node.right(binheap.value(rpos - 1));
        } else {
          node.right().value(binheap.value(rpos - 1));
        }
        donode(node.right(), rpos);
      }
    };
    binheap._treenodes = nodes;
    donode(bt.root(), 1);
  };

  var BinaryHeap = function(jsav, element, options) {
    this.jsav = jsav;
    this.options = options;
    if ($.isArray(element)) {
      var arrsize = element.length;
      if ('size' in options) {
        element.length = options.size;
      }
      this.initialize(element);
      this.element.attr("data-jsav-heap-size", arrsize);
    } else {
      if (element) { // assume it's a DOM element
        this.element = $(element);
      } else {
        this.element = $("<ol/>");
        $(this.jsav.container).append(this.element).addClass("jsavbinaryheap");
      }
      var size = 0;
      $.each(this.element.find("li"), function(index) {
        if (this.value(index) !== "") {
          size++;
        }
      });
      this.element.attr("data-jsav-heap-size", size.length);

      this.initializeFromElement();
    }
    var oldfx = $.fx.off || false;
    $.fx.off = true;

    if (options.stats) {
      this.stats = {"swaps": 0, "leftswaps": 0, "rightswaps": 0,
                    "recursiveswaps": 0, "partlyrecursiveswaps": 0};
    }
    if (options.tree) {
      this._tree = jsav.ds.bintree(options);
      inittree(this);
      this._tree.layout();
    }
    if (options.heapify) {
      for (var i = Math.floor(this.heapsize()/2); i > 0; i--) {
        this.heapify(i);
      }
    }
    $.fx.off = oldfx;
  };
  var bhproto = BinaryHeap.prototype;
  $.extend(bhproto, JSAV._types.ds.AVArray.prototype);
  bhproto.arrayswap = bhproto.swap;
  bhproto.arraycss = bhproto.css;
  bhproto.arrayclear = bhproto.clear;
  bhproto.arrayvalue = bhproto.value;

  bhproto.value = function(index, newValue) {
    if (typeof newValue === "undefined") {
      return this.arrayvalue(index);
    }
    this.arrayvalue(index, newValue);
    if (index >= this.heapsize()) {
      this.element.attr("data-jsav-heap-size", index + 1);
    }
    if (this.options.tree) {
      inittree(this);
      this._treenodes[index].value(newValue);
      this._tree.layout();
    }
  };

  bhproto.css = function(index, cssprop) {
    var val = this.arraycss(index, cssprop);
    if (this.options.tree && typeof index === "number") {
      this._treenodes[index].css(cssprop);
    } else if (this.options.tree && $.isArray(index)) {
      for (var i = index.length; i--; ) {
        this._treenodes[index[i]].css(cssprop);
      }
    }
    return val;
  };

  bhproto.clear = function() {
    this.arrayclear();
    if (this.options.tree) {
      this._tree.clear();
    }
  };
  bhproto._setsize = JSAV.anim(function(newsize) {
    var oldsize = this.element.attr("data-jsav-heap-size");
    this.element.attr("data-jsav-heap-size", newsize);
    return [oldsize];
  });
  bhproto.heapsize = function(newsize) {
    if (typeof newsize !== "undefined") {
      return this._setsize(newsize);
    } else {
      return parseInt(this.element.attr("data-jsav-heap-size"), 10);
    }
  };

  bhproto.heapify = function(pos) {
    var size = this.heapsize(),
      lpos = pos * 2,
      rpos = pos * 2 + 1,
      smallest = pos,
      comp = this.options.compare;
    if (lpos <= size && comp(this.value(lpos - 1), this.value(pos - 1)) < 0) {
      smallest = lpos;
    }
    if (rpos <= size && comp(this.value(rpos - 1), this.value(smallest - 1)) < 0) {
      smallest = rpos;
    }
    if (smallest !== pos) {
      if (this.options.stats) {
        this.stats.swaps++;
        if (smallest === lpos) { this.stats.leftswaps++; }
        else { this.stats.rightswaps++; }
      }
      this.swap(smallest - 1, pos - 1);
      this.jsav.step();
      if (this.heapify(smallest) && this.options.stats) {
        this.stats.recursiveswaps++;
      } else if (this.options.stats) {
        this.stats.partlyrecursiveswaps++;
      }
      return true;
    } else if (this.options.stats) {
      this.stats.interrupted = true;
    }
    return false;
  };
  bhproto.swap = function(index1, index2, options) {
    this.arrayswap(index1, index2, options);
    if (this.options.tree) {
      // wrap the swap in a function..
      var treeswap = function(index1, index2) {
        this.jsav.effects.swap(this._treenodes[index1].element, this._treenodes[index2].element, true);
      };
      // .. and make it an animatable operation
      // TODO: move this wrapping to interaction.swap as an option
      JSAV.anim(treeswap, treeswap).call(this, index1, index2);
    }
  };
  bhproto.insert = function(val) {
    var i = this.heapsize() + 1,
      parent = Math.floor(i / 2),
      comp = this.options.compare,
      step = this.options.steps ? this.jsav.step : function() {};
    this.value(i - 1, val);
    if (this.options.tree) {
      inittree(this);
      this._tree.layout();
    }
    step.apply(this.jsav);
    while (i > 1 && comp(this.value(parent - 1), val) > 0) {
      if (this.options.stats) {
        this.stats.swaps += 1;
      }
      this.swap(i - 1, parent - 1);
      step.apply(this.jsav);
      i = parent;
      parent = Math.floor(i / 2);
    }
    if (comp(this.value(parent -1), val) === 0 && this.options.stats) {
      this.stats.collision = true;
    }
    return this;
  };

  JSAV.ext.ds.binheap = function(element, options) {
    return new BinaryHeap(this, element, $.extend(true, {'compare': compareFunction, "stats": false,
                                                         'steps': true, 'tree': true,
                                                         'heapify': true, 'center': true}, options));
  };
}(jQuery));<commit_msg>Minor fix to binaryheap insert<commit_after>(function($) {
  "use strict";
  var compareFunction = function(a, b) {
    return a - b;
  };
  var inittree = function(binheap) {
    var size = binheap.size(),
      bt = binheap._tree,
      nodes = [];
    var donode = function(node, pos) {
      if (pos === 1) {
        node.value(binheap.value(pos - 1));
      }
      node.element.attr("data-jsav-heap-index", pos);
      nodes[pos - 1] = node;
      var lpos = pos * 2,
          rpos = lpos + 1;
      if (lpos <= size) {
        if (!node.left()) {
          node.left(binheap.value(lpos - 1));
        } else {
          node.left().value(binheap.value(lpos - 1));
        }
        donode(node.left(), lpos);
      }
      if (rpos <= size) {
        if (!node.right()) {
          node.right(binheap.value(rpos - 1));
        } else {
          node.right().value(binheap.value(rpos - 1));
        }
        donode(node.right(), rpos);
      }
    };
    binheap._treenodes = nodes;
    donode(bt.root(), 1);
  };

  var BinaryHeap = function(jsav, element, options) {
    this.jsav = jsav;
    this.options = options;
    if ($.isArray(element)) {
      var arrsize = element.length;
      if ('size' in options) {
        element.length = options.size;
      }
      this.initialize(element);
      this.element.attr("data-jsav-heap-size", arrsize);
    } else {
      if (element) { // assume it's a DOM element
        this.element = $(element);
      } else {
        this.element = $("<ol/>");
        $(this.jsav.container).append(this.element).addClass("jsavbinaryheap");
      }
      var size = 0;
      $.each(this.element.find("li"), function(index) {
        if (this.value(index) !== "") {
          size++;
        }
      });
      this.element.attr("data-jsav-heap-size", size.length);

      this.initializeFromElement();
    }
    var oldfx = $.fx.off || false;
    $.fx.off = true;

    if (options.stats) {
      this.stats = {"swaps": 0, "leftswaps": 0, "rightswaps": 0,
                    "recursiveswaps": 0, "partlyrecursiveswaps": 0};
    }
    if (options.tree) {
      this._tree = jsav.ds.bintree(options);
      inittree(this);
      this._tree.layout();
    }
    if (options.heapify) {
      for (var i = Math.floor(this.heapsize()/2); i > 0; i--) {
        this.heapify(i);
      }
    }
    $.fx.off = oldfx;
  };
  var bhproto = BinaryHeap.prototype;
  $.extend(bhproto, JSAV._types.ds.AVArray.prototype);
  bhproto.arrayswap = bhproto.swap;
  bhproto.arraycss = bhproto.css;
  bhproto.arrayclear = bhproto.clear;
  bhproto.arrayvalue = bhproto.value;

  bhproto.value = function(index, newValue) {
    if (typeof newValue === "undefined") {
      return this.arrayvalue(index);
    }
    this.arrayvalue(index, newValue);
    if (index >= this.heapsize()) {
      this.element.attr("data-jsav-heap-size", index + 1);
    }
    if (this.options.tree) {
      inittree(this);
      this._treenodes[index].value(newValue);
      this._tree.layout();
    }
  };

  bhproto.css = function(index, cssprop) {
    var val = this.arraycss(index, cssprop);
    if (this.options.tree && typeof index === "number") {
      this._treenodes[index].css(cssprop);
    } else if (this.options.tree && $.isArray(index)) {
      for (var i = index.length; i--; ) {
        this._treenodes[index[i]].css(cssprop);
      }
    }
    return val;
  };

  bhproto.clear = function() {
    this.arrayclear();
    if (this.options.tree) {
      this._tree.clear();
    }
  };
  bhproto._setsize = JSAV.anim(function(newsize) {
    var oldsize = this.element.attr("data-jsav-heap-size");
    this.element.attr("data-jsav-heap-size", newsize);
    return [oldsize];
  });
  bhproto.heapsize = function(newsize) {
    if (typeof newsize !== "undefined") {
      return this._setsize(newsize);
    } else {
      return parseInt(this.element.attr("data-jsav-heap-size"), 10);
    }
  };

  bhproto.heapify = function(pos) {
    var size = this.heapsize(),
      lpos = pos * 2,
      rpos = pos * 2 + 1,
      smallest = pos,
      comp = this.options.compare;
    if (lpos <= size && comp(this.value(lpos - 1), this.value(pos - 1)) < 0) {
      smallest = lpos;
    }
    if (rpos <= size && comp(this.value(rpos - 1), this.value(smallest - 1)) < 0) {
      smallest = rpos;
    }
    if (smallest !== pos) {
      if (this.options.stats) {
        this.stats.swaps++;
        if (smallest === lpos) { this.stats.leftswaps++; }
        else { this.stats.rightswaps++; }
      }
      this.swap(smallest - 1, pos - 1);
      this.jsav.step();
      if (this.heapify(smallest) && this.options.stats) {
        this.stats.recursiveswaps++;
      } else if (this.options.stats) {
        this.stats.partlyrecursiveswaps++;
      }
      return true;
    } else if (this.options.stats) {
      this.stats.interrupted = true;
    }
    return false;
  };
  bhproto.swap = function(index1, index2, options) {
    this.arrayswap(index1, index2, options);
    if (this.options.tree) {
      // wrap the swap in a function..
      var treeswap = function(index1, index2) {
        this.jsav.effects.swap(this._treenodes[index1].element, this._treenodes[index2].element, true);
      };
      // .. and make it an animatable operation
      // TODO: move this wrapping to interaction.swap as an option
      JSAV.anim(treeswap, treeswap).call(this, index1, index2);
    }
  };
  bhproto.insert = function(val) {
    var i = this.heapsize() + 1,
      parent = Math.floor(i / 2),
      comp = this.options.compare,
      step = this.options.steps ? this.jsav.step : function() {};
    this.value(i - 1, val);
    if (this.options.tree) {
      inittree(this);
      this._tree.layout();
    }
    if (this.options.steps) { this.jsav.stepOption("grade", true); }
    step.apply(this.jsav);
    while (i > 1 && comp(this.value(parent - 1), val) > 0) {
      if (this.options.stats) {
        this.stats.swaps += 1;
      }
      this.swap(i - 1, parent - 1);
      step.apply(this.jsav);
      i = parent;
      parent = Math.floor(i / 2);
    }
    if (comp(this.value(parent -1), val) === 0 && this.options.stats) {
      this.stats.collision = true;
    }
    return this;
  };

  JSAV.ext.ds.binheap = function(element, options) {
    return new BinaryHeap(this, element, $.extend(true, {'compare': compareFunction, "stats": false,
                                                         'steps': true, 'tree': true,
                                                         'heapify': true, 'center': true}, options));
  };
}(jQuery));<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

function onRequest(context) {
    var log = new Log("operation.js");
    var operationModule = require("/app/modules/business-controllers/operation.js")["operationModule"];
    var device = context.unit.params.device;
    var autoCompleteParams = context.unit.params.autoCompleteParams;
    var encodedFeaturePayloads=context.unit.params.encodedFeaturePayloads;
    var controlOperations = operationModule.getControlOperations(device.type);
    var queryParams = [];
    var formParams = [];
    var pathParams = [];
    for (var i = 0; i < controlOperations.length; i++) {
        var currentParamList = controlOperations[i]["params"];
        for (var j = 0; j < currentParamList.length; j++) {
            var currentParam = currentParamList[j];
            currentParamList[j]["formParams"] = processParams(currentParam["formParams"], autoCompleteParams);
            currentParamList[j]["queryParams"] = processParams(currentParam["queryParams"], autoCompleteParams);
            currentParamList[j]["pathParams"] = processParams(currentParam["pathParams"], autoCompleteParams);
        }
        controlOperations[i]["params"] = currentParamList;
        if (encodedFeaturePayloads) {
            controlOperations[i]["payload"] = getPayload(encodedFeaturePayloads, controlOperations[i]["operation"]);
        }
    }
    return {"control_operations": controlOperations, "device": device};
}

function processParams(paramsList, autoCompleteParams) {
    var log = new Log();
    log.info("-- Params : "+paramsList.length);
    log.info("-- Auto Params : "+autoCompleteParams);
    for (var i = 0; i < paramsList.length; i++) {
        var paramName = paramsList[i];
        var paramValue = "";
        var paramType = "text";
        for (var k = 0; k < autoCompleteParams.length; k++) {
            if (paramName == autoCompleteParams[k].name) {
                paramValue = autoCompleteParams[k].value;
                paramType = "hidden";
            }
        }
        paramsList[i] = {"name": paramName, "value": paramValue, "type": paramType};
    }
    return paramsList;
}

function getPayload(featuresPayload, featureCode){
    var featuresJSONPayloads = JSON.parse(featuresPayload);
    return featuresJSONPayloads[featureCode];
}<commit_msg>removed unnecessary logs<commit_after>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

function onRequest(context) {
    var log = new Log("operation.js");
    var operationModule = require("/app/modules/business-controllers/operation.js")["operationModule"];
    var device = context.unit.params.device;
    var autoCompleteParams = context.unit.params.autoCompleteParams;
    var encodedFeaturePayloads=context.unit.params.encodedFeaturePayloads;
    var controlOperations = operationModule.getControlOperations(device.type);
    var queryParams = [];
    var formParams = [];
    var pathParams = [];
    for (var i = 0; i < controlOperations.length; i++) {
        var currentParamList = controlOperations[i]["params"];
        for (var j = 0; j < currentParamList.length; j++) {
            var currentParam = currentParamList[j];
            currentParamList[j]["formParams"] = processParams(currentParam["formParams"], autoCompleteParams);
            currentParamList[j]["queryParams"] = processParams(currentParam["queryParams"], autoCompleteParams);
            currentParamList[j]["pathParams"] = processParams(currentParam["pathParams"], autoCompleteParams);
        }
        controlOperations[i]["params"] = currentParamList;
        if (encodedFeaturePayloads) {
            controlOperations[i]["payload"] = getPayload(encodedFeaturePayloads, controlOperations[i]["operation"]);
        }
    }
    return {"control_operations": controlOperations, "device": device};
}

function processParams(paramsList, autoCompleteParams) {
    for (var i = 0; i < paramsList.length; i++) {
        var paramName = paramsList[i];
        var paramValue = "";
        var paramType = "text";
        for (var k = 0; k < autoCompleteParams.length; k++) {
            if (paramName == autoCompleteParams[k].name) {
                paramValue = autoCompleteParams[k].value;
                paramType = "hidden";
            }
        }
        paramsList[i] = {"name": paramName, "value": paramValue, "type": paramType};
    }
    return paramsList;
}

function getPayload(featuresPayload, featureCode){
    var featuresJSONPayloads = JSON.parse(featuresPayload);
    return featuresJSONPayloads[featureCode];
}<|endoftext|>


<commit_before><commit_msg>refactor(kff.require): require should not fallback to global object evaluation<commit_after><|endoftext|>


<commit_before><commit_msg>Add enconding options and copy db method<commit_after><|endoftext|>


<commit_before>var http = require('http');
var io = require('socket.io');
var url = require('url');
var path = require('path');
var fs = require('fs');
var jQuery = require('jquery');
var redis = require('redis');

server = http.createServer(function(request, response){
    var uri = url.parse(request.url).pathname;
    if (uri === '/') {
        var filename = path.join(process.cwd(), 'index.html');
    } else {
        var filename = path.join(process.cwd(), uri);
    }
    path.exists(filename, function(exists) {
        if (!exists) {
            response.writeHead(404, {"Content-Type": "text/plain"});
            response.write("404 Not Found\n");
            response.end();
            return;
        }

        fs.readFile(filename, "binary", function(err, file) {
            if (err) {
                response.writeHead(500, {"Content-Type": "text/plain"});
                response.write(err + "\n");
                response.end();
                return;
            }

            response.writeHead(200);
            response.write(file, "binary");
            response.end();
        });
    });
});
server.listen(8002);

// REDIS
var redisClient = redis.createClient();

redisClient.on('error', function (err) {
    console.log('Redis error ' + err);
});

// socket.io
var socket = io.listen(server);

var socketClients = [];

socket.on('connection', function(client) {
    client.identifier = socketClients.length;
    socketClients.push(client);
    console.log("New client " + client.identifier + " connected, client list is now", socketClients.length);

    // Send current data from Redis
    redisClient.hkeys('anon-ontologies', function(err, ontologies) {
        ontologies.forEach(function(ontology, i) {
            redisClient.lrange('anon-' + ontology, 0, -1, function(err, anonItems) {
                anonItems.forEach(function(anonItem, i) {
                    console.log(anonItem);
                    client.send(JSON.parse(anonItem));
                });
            });
        });
    });
    redisClient.hkeys('ontologies', function(err, ontologies) {
        ontologies.forEach(function(ontology, i) {
            redisClient.hkeys(ontology, function(err, itemIdentifiers) {
                itemIdentifiers.forEach(function(itemIdentifier, i) {
                    redisClient.hget(ontology, itemIdentifier, function(err, item) {
                        console.log(item);
                        client.send(JSON.parse(item));
                    });
                });
            });
        });
    });

    client.on('message', function(data) {
        console.log("Got message from client " + client.identifier, data);

        if (typeof data === 'object') {
            if (data['a'] !== undefined) {
                if (data['@'] !== '<undefined>') {
                    // Identified object, save to Redis hash based on type
                    redisClient.hset(data['a'], data['@'], JSON.stringify(data));
                    redisClient.hset('ontologies', data['a'], true);
                } else {
                    // Anonymous entity, save to Redis list based on type
                    redisClient.lpush('anon-' + data['a'], JSON.stringify(data));
                    redisClient.hset('anon-ontologies', data['a'], true);
                }
            }
        }

        jQuery.each(socketClients, function(index, socketClient) {
            if (socketClient == client) {
                return true;
            }
            console.log("Forwarding data to " + socketClient.identifier);

            socketClient.send(data);
        });
    });

    client.on('disconnect', function() {
        socketClients = jQuery.grep(socketClients, function(value) {
            return value != client;
        });

        console.log("Client " + client.identifier + " disconnected, client list is now", socketClients.length);
    })
});
<commit_msg>Store listed anonymous entries in correct order<commit_after>var http = require('http');
var io = require('socket.io');
var url = require('url');
var path = require('path');
var fs = require('fs');
var jQuery = require('jquery');
var redis = require('redis');

server = http.createServer(function(request, response){
    var uri = url.parse(request.url).pathname;
    if (uri === '/') {
        var filename = path.join(process.cwd(), 'index.html');
    } else {
        var filename = path.join(process.cwd(), uri);
    }
    path.exists(filename, function(exists) {
        if (!exists) {
            response.writeHead(404, {"Content-Type": "text/plain"});
            response.write("404 Not Found\n");
            response.end();
            return;
        }

        fs.readFile(filename, "binary", function(err, file) {
            if (err) {
                response.writeHead(500, {"Content-Type": "text/plain"});
                response.write(err + "\n");
                response.end();
                return;
            }

            response.writeHead(200);
            response.write(file, "binary");
            response.end();
        });
    });
});
server.listen(8002);

// REDIS
var redisClient = redis.createClient();

redisClient.on('error', function (err) {
    console.log('Redis error ' + err);
});

// socket.io
var socket = io.listen(server);

var socketClients = [];

socket.on('connection', function(client) {
    client.identifier = socketClients.length;
    socketClients.push(client);
    console.log("New client " + client.identifier + " connected, client list is now", socketClients.length);

    // Send current data from Redis
    redisClient.hkeys('anon-ontologies', function(err, ontologies) {
        ontologies.forEach(function(ontology, i) {
            redisClient.lrange('anon-' + ontology, 0, -1, function(err, anonItems) {
                anonItems.forEach(function(anonItem, i) {
                    console.log(anonItem);
                    client.send(JSON.parse(anonItem));
                });
            });
        });
    });
    redisClient.hkeys('ontologies', function(err, ontologies) {
        ontologies.forEach(function(ontology, i) {
            redisClient.hkeys(ontology, function(err, itemIdentifiers) {
                itemIdentifiers.forEach(function(itemIdentifier, i) {
                    redisClient.hget(ontology, itemIdentifier, function(err, item) {
                        console.log(item);
                        client.send(JSON.parse(item));
                    });
                });
            });
        });
    });

    client.on('message', function(data) {
        console.log("Got message from client " + client.identifier, data);

        if (typeof data === 'object') {
            if (data['a'] !== undefined) {
                if (data['@'] !== '<undefined>') {
                    // Identified object, save to Redis hash based on type
                    redisClient.hset(data['a'], data['@'], JSON.stringify(data));
                    redisClient.hset('ontologies', data['a'], true);
                } else {
                    // Anonymous entity, save to Redis list based on type
                    redisClient.rpush('anon-' + data['a'], JSON.stringify(data));
                    redisClient.hset('anon-ontologies', data['a'], true);
                }
            }
        }

        jQuery.each(socketClients, function(index, socketClient) {
            if (socketClient == client) {
                return true;
            }
            console.log("Forwarding data to " + socketClient.identifier);

            socketClient.send(data);
        });
    });

    client.on('disconnect', function() {
        socketClients = jQuery.grep(socketClients, function(value) {
            return value != client;
        });

        console.log("Client " + client.identifier + " disconnected, client list is now", socketClients.length);
    })
});
<|endoftext|>


<commit_before>// Benford's Law analyzer
$(function() {
    getCSVList();
    pickCSV();
    uploader();
    columnPicked();
    bindAnalyzeButton();
    initChart();
});

function bindAnalyzeButton() {

    $("#analyze-button").click(function () {

        // Get the file dataset and the columns
        var fileName  = $("#csv-list").find(":selected").text();
        var col_group = $("#column-group").find(":selected").val();
        var col_check = $("#column-check").find(":selected").val();

        // Call the analyzer and add to chart
        $.getJSON('/cgi-bin/csv-analyze.py?'
                + 'filename='      + fileName
                + '&column_group=' + col_group
                + '&column_check=' + col_check,
                function (result) {
                      if (result['rejected'].length > 0)
                          alert('rejected:\r\n' + result['rejected']);
                      addChartSeries(result['series']);
                  });

        return false; // Prevent form submission

    });
}

function initChart() {
    // Now draw chart
    $('#container').highcharts({
        title: {
            text: 'Porcentage de dígitos en datasets por columna de grupo',
            x: -20 //center
        },
        subtitle: {
            text: 'Comparados con la Ley de Benford',
            x: -20
        },
        xAxis: {
            categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9' ]
        },
        yAxis: {
            title: {
                text: 'Porcentaje de digitos'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            valueSuffix: '%'
        },
        legend: {
            layout:        'vertical',
            align:         'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
        series: [
            {
                name:    'Porcentajes esperados
(según Ley de Benford)',
                data:    [ 30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6 ]

            }, {
                name:    'Alumnos matriculados - Mendoza',
                data:    [24.7, 20.1, 13.0, 8.2, 8.5, 6.9, 6.6, 6.9, 5.0],
                visible: false

            }, {
                name:    'Alumnos matriculados - Ciudad de Bs. As.',
                data:    [29.4, 6.1, 6.6, 8.3, 11.1, 7.9, 9.2, 11.7, 9.8],
                visible: false

            }, {
                name:    'Pacientes camas - Salta',
                data:    [31.9, 17.6, 12.1, 13.2, 7.7, 7.7, 2.2, 3.3, 4.4],
                visible: false

            }, {
                name:    'Pacientes camas - La Rioja',
                data:    [19.2, 21.2, 9.6, 21.2, 9.6, 1.9, 5.8, 9.6, 1.9],
                visible: false

        }]
    }); // end highchart()
}

// Gets a dictionary of series
function addChartSeries(series) {

    var chart = $('#container').highcharts();

    // Remove old series, but keep the first one (Benford's)
    while(chart.series.length > 1) {
        chart.series[1].remove(true);
    }

    // Add all series, not visible by default
    for(var k in series) {

        var d = series[k];
        chart.addSeries({
                name:    k,
                data:    d,
                visible: false
        });
    }

}

function pickCSV() {

    $('#csv-list').change( function() {

        var fileName = $(this).find(":selected").text();
        getColumns(fileName); // Add columns of selected CSV file
    });
}

function getCSVList() {
    $.getJSON('/cgi-bin/csv-list.py',
            function (result) {
                  fillCSVList(result['csvFiles']);
              });
}

function fillCSVList(csvFiles) {

    var files = $('#csv-list');     // CSV files available

    for(var i in csvFiles) {
        var fileName = csvFiles[i];
        var option = '<option value="' + i + '">' + fileName + '</option>\r\n';
        files.append($(option)); // Add to grouping column select
    }
}

function csvAddOne(fileName) {

    var files    = $('#csv-list');     // CSV files available
    var filesLen = document.getElementById("csv-list").length;
    var option   = '<option value="' + filesLen + '" selected="selected">'
                   + fileName + '</option>\r\n';
    files.append($(option)); // Add to grouping column select
}

// Bind to an upload form,
function uploader() {

    fileInput = $("input:file[name=csv-file]");

    function fileValid() {
        var fileName = getFilenameInput('csv-file');
        return (/\.csv/.test(fileName));
    }

    // From http://stackoverflow.com/a/16086380
    fileInput.on("change", function (event) {

        if ( ! fileValid() ) {
            alert('El archivo debe tener extensión ".csv"');
            clearFileInput();
            $("input:submit").prop('disabled', true); // Invalid, disable
            return false;
        }

        if ($("input[type='checkbox']").is(":checked"))
            $("input:submit").prop("disabled", false); // Valid, enable submit

    });

    // Bind to terms acceptance, enabling/disabling upload and analyze
    $("input[type='checkbox']").change(function(e) {

        if ($(this).is(":checked")) {
            $("#button-upload").removeClass("disabled"); // Enable upload
            checkPick();
        } else {
            $("#button-upload").addClass("disabled");  // Enable upload
            $("#analyze-button").attr("disabled", "disabled");
        }
    });

    // Do AJAX submit
    // From http://stackoverflow.com/a/16086380
    $("form[name=csv-file-upload]").bind("submit", function (event) {

        var formData = new FormData($(this)[0]);

        $("#uploading").text("Uploading...");
        $.ajax({

            url:         $(this).attr("action"),
            type:        'POST',
            data:        formData,
            async:       false,
            success:     function (data) {

                        var fileName = getFilenameInput('csv-file');
                        $("#uploading").text("uploaded " + fileName + '!');
                        csvAddOne(fileName);  // Update file list, select
                        getColumns(fileName); // Get columns of new file
                        clearFileInput();     // Clear selected file

            },
            cache:       false,
            contentType: false,
            processData: false
        });

        return false;
    });

}

function fillColumns(columnNames) {

    var group = $('#column-group'); // Column to group by
    var check = $('#column-check'); // Column to analyze

    for(var i in columnNames) {
        var colName = columnNames[i];
        var option = '<option value="' + i + '">' + colName + '</option>\r\n';
        group.append($(option)); // Add to grouping column select
        check.append($(option)); // Add to check column select
    }
}

// Clear selected file while preserving bound methods
//     http://stackoverflow.com/a/1043969
function clearFileInput() {
    var fileInput = $("#csv-file");
    fileInput.replaceWith(fileInput = fileInput.clone(true));
}

function getColumns(fileName) {

    clearColumns();       // Remove all columns
    $.getJSON('/cgi-bin/csv-columns.py',
              { 'dataset' : fileName },
              function (result) {
                  fillColumns(result['columns']);
              });
}

function clearColumns() {
    // Remove all but first
    $("#column-group").find('option:gt(0)').remove().end();
    $("#column-check").find('option:gt(0)').remove().end();
}

// Hack to get filename from form input file element
//   from http://stackoverflow.com/a/857662
function getFilenameInput(inputName) {

    var fullPath = document.getElementById(inputName).value;

    if (fullPath) {
        var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
        var fileName = fullPath.substring(startIndex);
        if (fileName.indexOf('\\') === 0 || fileName.indexOf('/') === 0) {
            fileName = fileName.substring(1);
        }
    }
    return fileName;
}

// Checks if column picked are both valid
function checkPick() {

    var selCheck     = $("#column-check").find(":selected").val();
    var termsChecked = $("input[type='checkbox']").is(":checked");

    if (selCheck == "invalid" || ! termsChecked) {
        $("#analyze-button").attr("disabled", "disabled");
    } else {
        $("#analyze-button").removeAttr("disabled");
    }
}

function columnPicked() {
    // $('#column-group').change(checkPick);
    $('#column-check').change(checkPick);
}
<commit_msg>If only one series, make it visible by default<commit_after>// Benford's Law analyzer
$(function() {
    getCSVList();
    pickCSV();
    uploader();
    columnPicked();
    bindAnalyzeButton();
    initChart();
});

function bindAnalyzeButton() {

    $("#analyze-button").click(function () {

        // Get the file dataset and the columns
        var fileName  = $("#csv-list").find(":selected").text();
        var col_group = $("#column-group").find(":selected").val();
        var col_check = $("#column-check").find(":selected").val();

        // Call the analyzer and add to chart
        $.getJSON('/cgi-bin/csv-analyze.py?'
                + 'filename='      + fileName
                + '&column_group=' + col_group
                + '&column_check=' + col_check,
                function (result) {
                      if (result['rejected'].length > 0)
                          alert('rejected:\r\n' + result['rejected']);
                      addChartSeries(result['series']);
                  });

        return false; // Prevent form submission

    });
}

function initChart() {
    // Now draw chart
    $('#container').highcharts({
        title: {
            text: 'Porcentage de dígitos en datasets por columna de grupo',
            x: -20 //center
        },
        subtitle: {
            text: 'Comparados con la Ley de Benford',
            x: -20
        },
        xAxis: {
            categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9' ]
        },
        yAxis: {
            title: {
                text: 'Porcentaje de digitos'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            valueSuffix: '%'
        },
        legend: {
            layout:        'vertical',
            align:         'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
        series: [
            {
                name:    'Porcentajes esperados
(según Ley de Benford)',
                data:    [ 30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6 ]

            }, {
                name:    'Alumnos matriculados - Mendoza',
                data:    [24.7, 20.1, 13.0, 8.2, 8.5, 6.9, 6.6, 6.9, 5.0],
                visible: false

            }, {
                name:    'Alumnos matriculados - Ciudad de Bs. As.',
                data:    [29.4, 6.1, 6.6, 8.3, 11.1, 7.9, 9.2, 11.7, 9.8],
                visible: false

            }, {
                name:    'Pacientes camas - Salta',
                data:    [31.9, 17.6, 12.1, 13.2, 7.7, 7.7, 2.2, 3.3, 4.4],
                visible: false

            }, {
                name:    'Pacientes camas - La Rioja',
                data:    [19.2, 21.2, 9.6, 21.2, 9.6, 1.9, 5.8, 9.6, 1.9],
                visible: false

        }]
    }); // end highchart()
}

// Gets a dictionary of series
function addChartSeries(series) {

    var chart = $('#container').highcharts();

    // Remove old series, but keep the first one (Benford's)
    while(chart.series.length > 1) {
        chart.series[1].remove(true);
    }

    //
    // Add all series
    //
    var series_length = 0;     // How many series are in result
    for(var k in series) {
        series_length++;
    }

    var visibility = false;       // not visible by default
    if (series_length == 1)
        visibility = true;        // if only one series make it visible

    for(var k in series) {

        var d = series[k];
        chart.addSeries({
                name:    k,
                data:    d,
                visible: visibility
        });
    }

}

function pickCSV() {

    $('#csv-list').change( function() {

        var fileName = $(this).find(":selected").text();
        getColumns(fileName); // Add columns of selected CSV file
    });
}

function getCSVList() {
    $.getJSON('/cgi-bin/csv-list.py',
            function (result) {
                  fillCSVList(result['csvFiles']);
              });
}

function fillCSVList(csvFiles) {

    var files = $('#csv-list');     // CSV files available

    for(var i in csvFiles) {
        var fileName = csvFiles[i];
        var option = '<option value="' + i + '">' + fileName + '</option>\r\n';
        files.append($(option)); // Add to grouping column select
    }
}

function csvAddOne(fileName) {

    var files    = $('#csv-list');     // CSV files available
    var filesLen = document.getElementById("csv-list").length;
    var option   = '<option value="' + filesLen + '" selected="selected">'
                   + fileName + '</option>\r\n';
    files.append($(option)); // Add to grouping column select
}

// Bind to an upload form,
function uploader() {

    fileInput = $("input:file[name=csv-file]");

    function fileValid() {
        var fileName = getFilenameInput('csv-file');
        return (/\.csv/.test(fileName));
    }

    // From http://stackoverflow.com/a/16086380
    fileInput.on("change", function (event) {

        if ( ! fileValid() ) {
            alert('El archivo debe tener extensión ".csv"');
            clearFileInput();
            $("input:submit").prop('disabled', true); // Invalid, disable
            return false;
        }

        if ($("input[type='checkbox']").is(":checked"))
            $("input:submit").prop("disabled", false); // Valid, enable submit

    });

    // Bind to terms acceptance, enabling/disabling upload and analyze
    $("input[type='checkbox']").change(function(e) {

        if ($(this).is(":checked")) {
            $("#button-upload").removeClass("disabled"); // Enable upload
            checkPick();
        } else {
            $("#button-upload").addClass("disabled");  // Enable upload
            $("#analyze-button").attr("disabled", "disabled");
        }
    });

    // Do AJAX submit
    // From http://stackoverflow.com/a/16086380
    $("form[name=csv-file-upload]").bind("submit", function (event) {

        var formData = new FormData($(this)[0]);

        $("#uploading").text("Uploading...");
        $.ajax({

            url:         $(this).attr("action"),
            type:        'POST',
            data:        formData,
            async:       false,
            success:     function (data) {

                        var fileName = getFilenameInput('csv-file');
                        $("#uploading").text("uploaded " + fileName + '!');
                        csvAddOne(fileName);  // Update file list, select
                        getColumns(fileName); // Get columns of new file
                        clearFileInput();     // Clear selected file

            },
            cache:       false,
            contentType: false,
            processData: false
        });

        return false;
    });

}

function fillColumns(columnNames) {

    var group = $('#column-group'); // Column to group by
    var check = $('#column-check'); // Column to analyze

    for(var i in columnNames) {
        var colName = columnNames[i];
        var option = '<option value="' + i + '">' + colName + '</option>\r\n';
        group.append($(option)); // Add to grouping column select
        check.append($(option)); // Add to check column select
    }
}

// Clear selected file while preserving bound methods
//     http://stackoverflow.com/a/1043969
function clearFileInput() {
    var fileInput = $("#csv-file");
    fileInput.replaceWith(fileInput = fileInput.clone(true));
}

function getColumns(fileName) {

    clearColumns();       // Remove all columns
    $.getJSON('/cgi-bin/csv-columns.py',
              { 'dataset' : fileName },
              function (result) {
                  fillColumns(result['columns']);
              });
}

function clearColumns() {
    // Remove all but first
    $("#column-group").find('option:gt(0)').remove().end();
    $("#column-check").find('option:gt(0)').remove().end();
}

// Hack to get filename from form input file element
//   from http://stackoverflow.com/a/857662
function getFilenameInput(inputName) {

    var fullPath = document.getElementById(inputName).value;

    if (fullPath) {
        var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
        var fileName = fullPath.substring(startIndex);
        if (fileName.indexOf('\\') === 0 || fileName.indexOf('/') === 0) {
            fileName = fileName.substring(1);
        }
    }
    return fileName;
}

// Checks if column picked are both valid
function checkPick() {

    var selCheck     = $("#column-check").find(":selected").val();
    var termsChecked = $("input[type='checkbox']").is(":checked");

    if (selCheck == "invalid" || ! termsChecked) {
        $("#analyze-button").attr("disabled", "disabled");
    } else {
        $("#analyze-button").removeAttr("disabled");
    }
}

function columnPicked() {
    // $('#column-group').change(checkPick);
    $('#column-check').change(checkPick);
}
<|endoftext|>


<commit_before>//* @protected
/**
	If you make changes to _enyo.xhr_, be sure to add or update the appropriate
	[unit tests](https://github.com/enyojs/enyo/tree/master/tools/test/ajax/tests).
*/
enyo.xhr = {
	/**
		inParams is an Object that may contain these properties:

		- _url_: The URL to request (required).
		- _method_: The HTTP method to use for the request. Defaults to GET.
		- _callback_: Called when request is completed. (Optional)
		- _body_: Specific contents for the request body for POST method. (Optional)
		- _headers_: Additional request headers. (Optional).  Given headers override the ones that Enyo may set by default (`null` explictly removing the header from the AJAX request).
		- _username_: The optional user name to use for authentication purposes.
		- _password_: The optional password to use for authentication purposes.
		- _xhrFields_: Optional object containing name/value pairs to mix directly into the generated xhr object.
		- _mimeType_: Optional string to override the MIME-Type.

		Note: on iOS 6, we will explicity add a "cache-control: no-cache"
		header for any non-GET requests to workaround a system bug that caused
		non-cachable requests to be cached. To disable this, use the _header_
		property to specify an object where "cache-control" is set to null.
	*/
	request: function(inParams) {
		var xhr = this.getXMLHttpRequest(inParams);
		var url = enyo.path.rewrite(this.simplifyFileURL(inParams.url));
		//
		var method = inParams.method || "GET";
		var async = !inParams.sync;
		//
		if (inParams.username) {
			xhr.open(method, url, async, inParams.username, inParams.password);
		} else {
			xhr.open(method, url, async);
		}
		//
		enyo.mixin(xhr, inParams.xhrFields);
		// only setup handler when we have a callback
		if (inParams.callback) {
			this.makeReadyStateHandler(xhr, inParams.callback);
		}
		//
		inParams.headers = inParams.headers || {};
		// work around iOS 6.0 bug where non-GET requests are cached
		// see http://www.einternals.com/blog/web-development/ios6-0-caching-ajax-post-requests
		if (method !== "GET" && enyo.platform.ios && enyo.platform.ios == 6) {
			if (inParams.headers["cache-control"] !== null) {
				inParams.headers["cache-control"] = inParams.headers['cache-control'] || "no-cache";
			}
		}
		// user-set headers override any platform-default
		if (xhr.setRequestHeader) {
			for (var key in inParams.headers) {
				if (inParams.headers[key]) {
					xhr.setRequestHeader(key, inParams.headers[key]);
				}
			}
		}
		//
		if((typeof xhr.overrideMimeType == "function") && inParams.mimeType) {
			xhr.overrideMimeType(inParams.mimeType);
		}
		//
		xhr.send(inParams.body || null);
		if (!async && inParams.callback) {
			xhr.onreadystatechange(xhr);
		}
		return xhr;
	},
	//* remove any callbacks that might be set from Enyo code for an existing XHR
	//* and stop the XHR from completing.
	cancel: function(inXhr) {
		if (inXhr.onload) {
			inXhr.onload = null;
		}
		if (inXhr.onreadystatechange) {
			inXhr.onreadystatechange = null;
		}
		if (inXhr.abort) {
			inXhr.abort();
		}
	},
	//* @protected
	makeReadyStateHandler: function(inXhr, inCallback) {
		if (window.XDomainRequest && inXhr instanceof window.XDomainRequest) {
			inXhr.onload = function() {
				var data;
				if (inXhr.responseType === "arraybuffer") {
					data = inXhr.response;
				} else if (typeof inXhr.responseText === "string") {
					data = inXhr.responseText;
				}
				inCallback.apply(null, [data, inXhr]);
				inXhr = null;
			};
		} else {
			inXhr.onreadystatechange = function() {
				if (inXhr && inXhr.readyState == 4) {
					var data;
					if (inXhr.responseType === "arraybuffer") {
						data = inXhr.response;
					} else if (typeof inXhr.responseText === "string") {
						data = inXhr.responseText;
					}
					inCallback.apply(null, [data, inXhr]);
					inXhr = null;
				}
			};
		}
	},
	inOrigin: function(inUrl) {
		var a = document.createElement("a"), result = false;
		a.href = inUrl;
		// protocol is ":" for relative URLs
		if (a.protocol === ":" ||
				(a.protocol === window.location.protocol &&
					a.hostname === window.location.hostname &&
					a.port === (window.location.port ||
						(window.location.protocol === "https:" ? "443" : "80")))) {
			result = true;
		}
		return result;
	},
	simplifyFileURL: function(inUrl) {
		var a = document.createElement("a");
		a.href = inUrl;
		// protocol is ":" for relative URLs
		if (a.protocol === "file:" ||
			a.protocol === ":" && window.location.protocol === "file:") {
			// leave off search and hash parts of the URL
			return a.protocol + '//' + a.pathname;
		} else if (a.protocol === ":" && window.location.protocol === "x-wmapp0:") {
			// explicitly return absolute URL for Windows Phone 8, as an absolute path is required for local files
			return window.location.protocol + "//" + window.location.pathname.split('/')[0] + "/" + a.host + a.pathname;
		} else {
			return inUrl;
		}
	},
	getXMLHttpRequest: function(inParams) {
		try {
			// only use XDomainRequest when it exists, no extra headers were set, and the
			// target URL maps to a domain other than the document origin.
			if (enyo.platform.ie < 10 && window.XDomainRequest && !inParams.headers &&
				!this.inOrigin(inParams.url) && !/^file:\/\//.test(window.location.href)) {
				return new window.XDomainRequest();
			}
		} catch(e) {}
		try {
			return new XMLHttpRequest();
		} catch(e) {}
		return null;
	}
};
<commit_msg>Update file URL simplification code<commit_after>//* @protected
/**
	If you make changes to _enyo.xhr_, be sure to add or update the appropriate
	[unit tests](https://github.com/enyojs/enyo/tree/master/tools/test/ajax/tests).
*/
enyo.xhr = {
	/**
		inParams is an Object that may contain these properties:

		- _url_: The URL to request (required).
		- _method_: The HTTP method to use for the request. Defaults to GET.
		- _callback_: Called when request is completed. (Optional)
		- _body_: Specific contents for the request body for POST method. (Optional)
		- _headers_: Additional request headers. (Optional).  Given headers override the ones that Enyo may set by default (`null` explictly removing the header from the AJAX request).
		- _username_: The optional user name to use for authentication purposes.
		- _password_: The optional password to use for authentication purposes.
		- _xhrFields_: Optional object containing name/value pairs to mix directly into the generated xhr object.
		- _mimeType_: Optional string to override the MIME-Type.

		Note: on iOS 6, we will explicity add a "cache-control: no-cache"
		header for any non-GET requests to workaround a system bug that caused
		non-cachable requests to be cached. To disable this, use the _header_
		property to specify an object where "cache-control" is set to null.
	*/
	request: function(inParams) {
		var xhr = this.getXMLHttpRequest(inParams);
		var url = enyo.path.rewrite(this.simplifyFileURL(inParams.url));
		//
		var method = inParams.method || "GET";
		var async = !inParams.sync;
		//
		if (inParams.username) {
			xhr.open(method, url, async, inParams.username, inParams.password);
		} else {
			xhr.open(method, url, async);
		}
		//
		enyo.mixin(xhr, inParams.xhrFields);
		// only setup handler when we have a callback
		if (inParams.callback) {
			this.makeReadyStateHandler(xhr, inParams.callback);
		}
		//
		inParams.headers = inParams.headers || {};
		// work around iOS 6.0 bug where non-GET requests are cached
		// see http://www.einternals.com/blog/web-development/ios6-0-caching-ajax-post-requests
		if (method !== "GET" && enyo.platform.ios && enyo.platform.ios == 6) {
			if (inParams.headers["cache-control"] !== null) {
				inParams.headers["cache-control"] = inParams.headers['cache-control'] || "no-cache";
			}
		}
		// user-set headers override any platform-default
		if (xhr.setRequestHeader) {
			for (var key in inParams.headers) {
				if (inParams.headers[key]) {
					xhr.setRequestHeader(key, inParams.headers[key]);
				}
			}
		}
		//
		if((typeof xhr.overrideMimeType == "function") && inParams.mimeType) {
			xhr.overrideMimeType(inParams.mimeType);
		}
		//
		xhr.send(inParams.body || null);
		if (!async && inParams.callback) {
			xhr.onreadystatechange(xhr);
		}
		return xhr;
	},
	//* remove any callbacks that might be set from Enyo code for an existing XHR
	//* and stop the XHR from completing.
	cancel: function(inXhr) {
		if (inXhr.onload) {
			inXhr.onload = null;
		}
		if (inXhr.onreadystatechange) {
			inXhr.onreadystatechange = null;
		}
		if (inXhr.abort) {
			inXhr.abort();
		}
	},
	//* @protected
	makeReadyStateHandler: function(inXhr, inCallback) {
		if (window.XDomainRequest && inXhr instanceof window.XDomainRequest) {
			inXhr.onload = function() {
				var data;
				if (inXhr.responseType === "arraybuffer") {
					data = inXhr.response;
				} else if (typeof inXhr.responseText === "string") {
					data = inXhr.responseText;
				}
				inCallback.apply(null, [data, inXhr]);
				inXhr = null;
			};
		} else {
			inXhr.onreadystatechange = function() {
				if (inXhr && inXhr.readyState == 4) {
					var data;
					if (inXhr.responseType === "arraybuffer") {
						data = inXhr.response;
					} else if (typeof inXhr.responseText === "string") {
						data = inXhr.responseText;
					}
					inCallback.apply(null, [data, inXhr]);
					inXhr = null;
				}
			};
		}
	},
	inOrigin: function(inUrl) {
		var a = document.createElement("a"), result = false;
		a.href = inUrl;
		// protocol is ":" for relative URLs
		if (a.protocol === ":" ||
				(a.protocol === window.location.protocol &&
					a.hostname === window.location.hostname &&
					a.port === (window.location.port ||
						(window.location.protocol === "https:" ? "443" : "80")))) {
			result = true;
		}
		return result;
	},
	simplifyFileURL: function(inUrl) {
		var a = document.createElement("a");
		a.href = inUrl;
		// protocol is ":" for relative URLs
		if (a.protocol === "file:" ||
			a.protocol === ":" && window.location.protocol === "file:") {
			// leave off search and hash parts of the URL
			// and work around a bug in webOS 3 where the app's host has a domain string
			// in it that isn't resolved as a path
			var host = (enyo.platform.webos < 4) ? "" : a.host;
			return a.protocol + '//' + host + a.pathname;
		} else if (a.protocol === ":" && window.location.protocol === "x-wmapp0:") {
			// explicitly return absolute URL for Windows Phone 8, as an absolute path is required for local files
			return window.location.protocol + "//" + window.location.pathname.split('/')[0] + "/" + a.host + a.pathname;
		} else {
			return inUrl;
		}
	},
	getXMLHttpRequest: function(inParams) {
		try {
			// only use XDomainRequest when it exists, no extra headers were set, and the
			// target URL maps to a domain other than the document origin.
			if (enyo.platform.ie < 10 && window.XDomainRequest && !inParams.headers &&
				!this.inOrigin(inParams.url) && !/^file:\/\//.test(window.location.href)) {
				return new window.XDomainRequest();
			}
		} catch(e) {}
		try {
			return new XMLHttpRequest();
		} catch(e) {}
		return null;
	}
};
<|endoftext|>


<commit_before>/* ***** html5sql.js ******
 *
 * Description: A helper javascript module for creating and working with
 *     HTML5 Web Databases.
 *
 * License: MIT license <http://www.opensource.org/licenses/mit-license.php>
 *
 * Authors: Ken Corbett Jr
 *
 * Version 0.9
 *
 * General Module Design based on article by Ben Cherry
 * http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
 *
 */

var html5sql = (function () {

	var readTransactionAvailible = false,
		doNothing = function () {},
		emptyArray = [],
		trim = function (string) {
			return string.replace(/^\s+/, "").replace(/\s+$/, "");
		},
		isArray = function (o) {
			return Object.prototype.toString.call(o) === '[object Array]';
		},
		// transaction is an sql transaction, sqlObjects are properly formated
		// and cleaned SQL objects
		sqlProcessor = function (transaction, sqlObjects, finalSuccess, error) {

			var sequenceNumber = 0,
				dataForNextTransaction = null,
				runTransaction = function () {
					transaction.executeSql(sqlObjects[sequenceNumber].sql,
										   sqlObjects[sequenceNumber].data,
										   successCallback,
										   failureCallback);
				},
				successCallback = function (transaction, results) {
					if(html5sql.logInfo){
						console.log("Success processing: " + sqlObjects[sequenceNumber].sql);
					}

					//Call the success callback provided with sql object
					//If an array of data is returned use that data as the
					//data attribute of the next transaction
					dataForNextTransaction = sqlObjects[sequenceNumber].success(transaction, results);
					sequenceNumber++;
					if (dataForNextTransaction && $.isArray(dataForNextTransaction)) {
						sqlObjects[sequenceNumber].data = dataForNextTransaction;
						dataForNextTransaction = null;
					} else {
						dataForNextTransaction = null;
					}

					if (sqlObjects.length > sequenceNumber) {
						runTransaction();
					} else {
						finalSuccess();
					}
				},
				failureCallback = function (transaction, error) {
					if(html5sql.logErrors){
						console.error("Error: " + error.message + " while processing: " + sqlObjects[sequenceNumber].sql);
					}
					error(error, sqlObjects[sequenceNumber].sql);
				};

			runTransaction();
		},
		sqlObjectCreator = function (sqlInput) {
			var i;
			if (typeof sqlInput === "string") {
				trim(sqlInput);
				sqlInput = sqlInput.split(';');
				for(i = 1; i < sqlInput.length; i++){
					sqlInput[i] = trim(sqlInput[i]) + ';';
					if(sqlInput[i] === ';'){
						sqlInput.splice(i, 1);
					}
				}
			}
			for (i = 0; i < sqlInput.length; i++) {
				//If the array item is only a string format it into an sql object
				if (typeof sqlInput[i] === "string") {
					sqlInput[i] = {
						"sql": sqlInput[i],
						"data": [],
						"success": doNothing
					};
				} else {
					// Check to see that the sql object is formated correctly.
					if (typeof sqlInput[i]         !== "object"   ||
					    typeof sqlInput[i].sql     !== "string"   ||
					    typeof sqlInput[i].success !== "function" ||
						!$.isArray(sqlInput[i].data)) {
						throw new Error("Malformed sql object");
					}
				}
			}
			return sqlInput;
		},
		statementsAreSelectOnly = function (SQLObjects) {
		// Returns true if all SQL statement objects are SELECT statements.
			var i = 0,
			    SelectStmtMatch = new RegExp('^select\\s', 'i'),
			    isSelectStmt = function (sqlstring) {
					return SelectStmtMatch.test(sqlstring);
				};

			//Loop over SQL objects ensuring they are select statments
			do {
				//If the sql string is not a select statement return false
				if (!isSelectStmt(SQLObjects[i].sql)) {
					return false;
				}
				i++;
			} while (i < SQLObjects.length);

			//If all the statments happen to be select statments return true
			return true;
		};
	return {
		database: null,
		logInfo: false,
		logErrors: false,
		openDatabase: function (name, displayname, size, whenOpen) {
			html5sql.database = openDatabase(name, "", displayname, size);
			readTransactionAvailible = typeof html5sql.database.readTransaction === 'function';
			if (whenOpen) {
				whenOpen();
			}
		},

		process: function (sqlInput, finalCallback, errorCallback) {
		/*
		 *
		 *	Arguments:
		 *
		 *  sql = [array SQLObjects] ~ collection of SQL statement objects
		 *           or
		 *        [array SQLStrings] ~ collection of SQL statement strings
		 *           or
		 *        "SQLstring"        ~ SQL string to be split at the ';'
		 *                             character and processed sequentially
         *
		 *  errorCallback = (function) ~ called if any of the sql statements
		 *                               fails.  A default one is used if none
		 *                               is provided.
		 *
		 *  finalCallback = (function) ~ called after all sql statments have
		 *                               been processed.  Optional.
		 *
		 *
		 *	SQL statement object:
		 *	{
		 *	 sql: "string",      !Required! ~ Your sql as a string
		 *	 data: [array],       Optional  ~ The array of data to be sequentially
		 *	                                  inserted into your sql at the ?
		 *   success: (function), Optional  ~ A function to be called if this
		 *                                    individual sql statment succeeds.
		 *                                    If an array is returned it is used as
		 *                                    the data for the next sql statement
		 *                                    processed.
		 *  }
		 *
		 *	Usage:
		 *	html5sql.process(
		 *		[{
		 *		   sql: "SELECT * FROM table;",
		 *		   data: [],
		 *		   success: function(){}
		 *		 },
		 *		 {
		 *		   sql: "SELECT * FROM table;",
		 *		   data: [],
		 *		   success: function(){}
		 *		 }],
		 *		function(){},
		 *		function(){}
		 *	);
		 *
		 */
			if (html5sql.database) {

				var sqlObjects = sqlObjectCreator(sqlInput);

				if (statementsAreSelectOnly(sqlObjects) && readTransactionAvailible) {
					html5sql.database.readTransaction(function (transaction) {
						sqlProcessor(transaction, sqlObjects, finalCallback, errorCallback);
					});
				} else {
					html5sql.database.transaction(function (transaction) {
						sqlProcessor(transaction, sqlObjects, finalCallback, errorCallback);
					});
				}
			} else {
				// Database hasn't been opened.
				if(html5sql.logErrors){
					console.error("Error: Database needs to be opened before sql can be processed.");
				}
				return false;
			}
		},

		changeVersion: function (oldVersion, newVersion, sqlInput, finalCallback, errorCallback) {
		/* This is the same as html5sql.process but used when you want to change the
		 * version of your database.  If the database version matches the oldVersion
		 * passed to the function the statements passed to the funciton are
		 * processed and the version of the database is changed to the new version.
		 *
		 *	Arguments:
		 *	oldVersion = "String"             ~ the old version to upgrade
		 *	newVersion = "String"             ~ the new version after the upgrade
		 *  sqlObjects = [array]              ~ collection of SQL statement objects
		 *  finalCallback = (function)        ~ called after all sql statments have
		 *                                      been processed
		 *  errorCallback = (function) 		  ~ called if any of the sql statements
		 *                                      failsSQL statements, set false if
		 *                                      not applicable
		 *
		 *	SQL statement object:
		 *	{
		 *	 sql: "string",      !Required! ~ Your sql as a string
		 *	 data: [array],       Optional  ~ The array of data to be sequentially
		 *	                                  inserted into your sql at the ?
		 *   success: (function), Optional  ~ A function to be called if this
		 *                                    individual sql statment succeeds
		 *   failure: (function), Optional  ~ A function to be called if this
		 *                                    individual sql statement fails
		 *  }
		 *
		 *	Usage:
		 *	html5sql.changeVersion(
		 *	    "1.0",
		 *	    "2.0",
		 *		[{
		 *		   sql: "SELECT * FROM table;",
		 *		   data: [],
		 *		   success: function(){},
		 *		   failure: function(){}
		 *		 },
		 *		 {
		 *		   sql: "SELECT * FROM table;",
		 *		   data: [],
		 *		   success: function(){},
		 *		   failure: function(){}
		 *		 }],
		 *		function(){},
		 *		function(){}
		 *	);
		 *
		 */
			if (html5sql.database) {
				if(html5sql.database.version === oldVersion){
					var sqlObjects = sqlObjectCreator(sqlInput);

					html5sql.database.changeVersion(oldVersion, newVersion, function (transaction) {
						sqlProcessor(transaction, sqlObjects, finalCallback, errorCallback);
					});
				}
			} else {
				// Database hasn't been opened.
				if(html5sql.logErrors){
					console.log("Error: Database needs to be opened before sql can be processed.");
				}
				return false;
			}

		}
	};

})();
<commit_msg>Fixed bug: Semicolon in quoted text causes SQL statement to be split up<commit_after>/* ***** html5sql.js ******
 *
 * Description: A helper javascript module for creating and working with
 *     HTML5 Web Databases.
 *
 * License: MIT license <http://www.opensource.org/licenses/mit-license.php>
 *
 * Authors: Ken Corbett Jr
 *
 * Version 0.9
 *
 * General Module Design based on article by Ben Cherry
 * http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
 *
 */

var html5sql = (function () {

	var readTransactionAvailible = false,
		doNothing = function () {},
		emptyArray = [],
		trim = function (string) {
			return string.replace(/^\s+/, "").replace(/\s+$/, "");
		},
		isArray = function (o) {
			return Object.prototype.toString.call(o) === '[object Array]';
		},
		// transaction is an sql transaction, sqlObjects are properly formated
		// and cleaned SQL objects
		sqlProcessor = function (transaction, sqlObjects, finalSuccess, error) {

			var sequenceNumber = 0,
				dataForNextTransaction = null,
				runTransaction = function () {
					transaction.executeSql(sqlObjects[sequenceNumber].sql,
										   sqlObjects[sequenceNumber].data,
										   successCallback,
										   failureCallback);
				},
				successCallback = function (transaction, results) {
					if(html5sql.logInfo){
						console.log("Success processing: " + sqlObjects[sequenceNumber].sql);
					}

					//Call the success callback provided with sql object
					//If an array of data is returned use that data as the
					//data attribute of the next transaction
					dataForNextTransaction = sqlObjects[sequenceNumber].success(transaction, results);
					sequenceNumber++;
					if (dataForNextTransaction && $.isArray(dataForNextTransaction)) {
						sqlObjects[sequenceNumber].data = dataForNextTransaction;
						dataForNextTransaction = null;
					} else {
						dataForNextTransaction = null;
					}

					if (sqlObjects.length > sequenceNumber) {
						runTransaction();
					} else {
						finalSuccess();
					}
				},
				failureCallback = function (transaction, error) {
					if(html5sql.logErrors){
						console.error("Error: " + error.message + " while processing: " + sqlObjects[sequenceNumber].sql);
					}
					error(error, sqlObjects[sequenceNumber].sql);
				};

			runTransaction();
		},
		sqlObjectCreator = function (sqlInput) {
			var i;
			if (typeof sqlInput === "string") {
				trim(sqlInput);

				//Separate sql statements by their ending semicolon
				sqlInput = sqlInput.split(';');

				for(i = 1; i < sqlInput.length; i++){
					//Ensure semicolons within quotes are replaced
					while(sqlInput[i].split(/["]/gm).length % 2 === 0 ||
						  sqlInput[i].split(/[']/gm).length % 2 === 0 ||
						  sqlInput[i].split(/[`]/gm).length % 2 === 0){
						 sqlInput.splice(i,2,sqlInput[i] + ";" + sqlInput[i+1]);
					}
					//Add back the semicolon at the end of the line
					sqlInput[i] = trim(sqlInput[i]) + ';';
					//Get rid of any empty statements
					if(sqlInput[i] === ';'){
						sqlInput.splice(i, 1);
					}
				}
			}
			for (i = 0; i < sqlInput.length; i++) {
				//If the array item is only a string format it into an sql object
				if (typeof sqlInput[i] === "string") {
					sqlInput[i] = {
						"sql": sqlInput[i],
						"data": [],
						"success": doNothing
					};
				} else {
					// Check to see that the sql object is formated correctly.
					if (typeof sqlInput[i]         !== "object"   ||
					    typeof sqlInput[i].sql     !== "string"   ||
					    typeof sqlInput[i].success !== "function" ||
						!$.isArray(sqlInput[i].data)) {
						throw new Error("Malformed sql object");
					}
				}
			}
			return sqlInput;
		},
		statementsAreSelectOnly = function (SQLObjects) {
		// Returns true if all SQL statement objects are SELECT statements.
			var i = 0,
			    SelectStmtMatch = new RegExp('^select\\s', 'i'),
			    isSelectStmt = function (sqlstring) {
					return SelectStmtMatch.test(sqlstring);
				};

			//Loop over SQL objects ensuring they are select statments
			do {
				//If the sql string is not a select statement return false
				if (!isSelectStmt(SQLObjects[i].sql)) {
					return false;
				}
				i++;
			} while (i < SQLObjects.length);

			//If all the statments happen to be select statments return true
			return true;
		};
	return {
		database: null,
		logInfo: false,
		logErrors: false,
		openDatabase: function (name, displayname, size, whenOpen) {
			html5sql.database = openDatabase(name, "", displayname, size);
			readTransactionAvailible = typeof html5sql.database.readTransaction === 'function';
			if (whenOpen) {
				whenOpen();
			}
		},

		process: function (sqlInput, finalCallback, errorCallback) {
		/*
		 *
		 *	Arguments:
		 *
		 *  sql = [array SQLObjects] ~ collection of SQL statement objects
		 *           or
		 *        [array SQLStrings] ~ collection of SQL statement strings
		 *           or
		 *        "SQLstring"        ~ SQL string to be split at the ';'
		 *                             character and processed sequentially
         *
		 *  errorCallback = (function) ~ called if any of the sql statements
		 *                               fails.  A default one is used if none
		 *                               is provided.
		 *
		 *  finalCallback = (function) ~ called after all sql statments have
		 *                               been processed.  Optional.
		 *
		 *
		 *	SQL statement object:
		 *	{
		 *	 sql: "string",      !Required! ~ Your sql as a string
		 *	 data: [array],       Optional  ~ The array of data to be sequentially
		 *	                                  inserted into your sql at the ?
		 *   success: (function), Optional  ~ A function to be called if this
		 *                                    individual sql statment succeeds.
		 *                                    If an array is returned it is used as
		 *                                    the data for the next sql statement
		 *                                    processed.
		 *  }
		 *
		 *	Usage:
		 *	html5sql.process(
		 *		[{
		 *		   sql: "SELECT * FROM table;",
		 *		   data: [],
		 *		   success: function(){}
		 *		 },
		 *		 {
		 *		   sql: "SELECT * FROM table;",
		 *		   data: [],
		 *		   success: function(){}
		 *		 }],
		 *		function(){},
		 *		function(){}
		 *	);
		 *
		 */
			if (html5sql.database) {

				var sqlObjects = sqlObjectCreator(sqlInput);

				if (statementsAreSelectOnly(sqlObjects) && readTransactionAvailible) {
					html5sql.database.readTransaction(function (transaction) {
						sqlProcessor(transaction, sqlObjects, finalCallback, errorCallback);
					});
				} else {
					html5sql.database.transaction(function (transaction) {
						sqlProcessor(transaction, sqlObjects, finalCallback, errorCallback);
					});
				}
			} else {
				// Database hasn't been opened.
				if(html5sql.logErrors){
					console.error("Error: Database needs to be opened before sql can be processed.");
				}
				return false;
			}
		},

		changeVersion: function (oldVersion, newVersion, sqlInput, finalCallback, errorCallback) {
		/* This is the same as html5sql.process but used when you want to change the
		 * version of your database.  If the database version matches the oldVersion
		 * passed to the function the statements passed to the funciton are
		 * processed and the version of the database is changed to the new version.
		 *
		 *	Arguments:
		 *	oldVersion = "String"             ~ the old version to upgrade
		 *	newVersion = "String"             ~ the new version after the upgrade
		 *  sqlObjects = [array]              ~ collection of SQL statement objects
		 *  finalCallback = (function)        ~ called after all sql statments have
		 *                                      been processed
		 *  errorCallback = (function) 		  ~ called if any of the sql statements
		 *                                      failsSQL statements, set false if
		 *                                      not applicable
		 *
		 *	SQL statement object:
		 *	{
		 *	 sql: "string",      !Required! ~ Your sql as a string
		 *	 data: [array],       Optional  ~ The array of data to be sequentially
		 *	                                  inserted into your sql at the ?
		 *   success: (function), Optional  ~ A function to be called if this
		 *                                    individual sql statment succeeds
		 *   failure: (function), Optional  ~ A function to be called if this
		 *                                    individual sql statement fails
		 *  }
		 *
		 *	Usage:
		 *	html5sql.changeVersion(
		 *	    "1.0",
		 *	    "2.0",
		 *		[{
		 *		   sql: "SELECT * FROM table;",
		 *		   data: [],
		 *		   success: function(){},
		 *		   failure: function(){}
		 *		 },
		 *		 {
		 *		   sql: "SELECT * FROM table;",
		 *		   data: [],
		 *		   success: function(){},
		 *		   failure: function(){}
		 *		 }],
		 *		function(){},
		 *		function(){}
		 *	);
		 *
		 */
			if (html5sql.database) {
				if(html5sql.database.version === oldVersion){
					var sqlObjects = sqlObjectCreator(sqlInput);

					html5sql.database.changeVersion(oldVersion, newVersion, function (transaction) {
						sqlProcessor(transaction, sqlObjects, finalCallback, errorCallback);
					});
				}
			} else {
				// Database hasn't been opened.
				if(html5sql.logErrors){
					console.log("Error: Database needs to be opened before sql can be processed.");
				}
				return false;
			}

		}
	};

})();
<|endoftext|>


<commit_before>import _includes from './internal/_includes';
import _curry2 from './internal/_curry2';

/**
 * Returns `true` if the specified value is equal, in [`R.equals`](#equals)
 * terms, to at least one element of the given list; `false` otherwise.
 * Works also with strings.
 *
 * @func
 * @memberOf R
 * @since v0.1.0
 * @category List
 * @sig a -> [a] -> Boolean
 * @param {Object} a The item to compare against.
 * @param {Array} list The array to consider.
 * @return {Boolean} `true` if an equivalent item is in the list, `false` otherwise.
 * @see R.any
 * @example
 *
 *      R.includes(3, [1, 2, 3]); //=> true
 *      R.includes(4, [1, 2, 3]); //=> false
 *      R.includes({ name: 'Fred' }, [{ name: 'Fred' }]); //=> true
 *      R.includes([42], [[42]]); //=> true
 *      R.includes('ba', 'banana'); //=>true
 */
var includes = _curry2(_includes);
export default includes;
<commit_msg>fix `@since` in `includes` (#2764)<commit_after>import _includes from './internal/_includes';
import _curry2 from './internal/_curry2';

/**
 * Returns `true` if the specified value is equal, in [`R.equals`](#equals)
 * terms, to at least one element of the given list; `false` otherwise.
 * Works also with strings.
 *
 * @func
 * @memberOf R
 * @since v0.26.0
 * @category List
 * @sig a -> [a] -> Boolean
 * @param {Object} a The item to compare against.
 * @param {Array} list The array to consider.
 * @return {Boolean} `true` if an equivalent item is in the list, `false` otherwise.
 * @see R.any
 * @example
 *
 *      R.includes(3, [1, 2, 3]); //=> true
 *      R.includes(4, [1, 2, 3]); //=> false
 *      R.includes({ name: 'Fred' }, [{ name: 'Fred' }]); //=> true
 *      R.includes([42], [[42]]); //=> true
 *      R.includes('ba', 'banana'); //=>true
 */
var includes = _curry2(_includes);
export default includes;
<|endoftext|>


<commit_before>;(function($){
	$.fn.udslider = function(options){
		this.each(function(i, el){
			if(typeof el.Slider === 'object'){
				return el.Slider;
			}

			// settings
			var settings = $.extend({
				angle: 75,
				count: 5,
				speed: 600,
				timer: 5000
			}, options);

			// typized
			settings.count = parseInt(settings.count);
			settings.angle = parseFloat(settings.angle);
			settings.speed = parseFloat(settings.speed);
			settings.timer = parseFloat(settings.timer);

			// slider object
			var Slider = new (function(ul, options){
				var t = this;

				// Elements
				t.ul = $(ul).fadeTo(1, 'slow');
				t.panel = t.ul.append($('

')).find('.panel');
				t.panelText = t.panel.append($('

')).find('.text');
				t.children = t.ul.children('li');

				// Initial parameters
				t.options = options;
				t.currentIndex = 0;
				t.animateCount = 0;
				t.inAction = false;
				t.count = t.children.length;
				t.skewAngle = t.options.angle;
				t.calcAngle = 90 - t.skewAngle;
				t.skewWidth = 0;
				t.imageWidth = 0;
				t.stepPercent = 50 / (t.options.count - 1);
				t.sliding = false;

				t.getChildren = function(__reverse){
					var reverse = (typeof __reverse === 'undefined')? false : __reverse;
					var list = $(t.ul[0]).children('li').get();
					return (reverse)? $(list.reverse()) : $(list);
				};

				// Calculate sizes
				calculateSizes.call(t);

				t.slideTo = function(index, __important){
					if(index == t.currentIndex) return false;

					if(t.inAction) return false;

					t.inAction = true;

					if(index > t.count - 1) index = index - t.count;
					if(index < 0) index = t.count + index;

					var current = t.currentIndex;

					t.currentIndex = index;

					t.panelText.fadeOut(90, function(){
						$(this).empty();
					});

					var calcSide = (index - current <= (t.count - 1) + current - index)? 'left' : 'right';
						important = __important || calcSide;

					if(important == 'left'){
						t.slideLeft(index, current);
					}else{
						t.slideRight(index, current);
					}

				};

				t.slideLeft = function(index, __prev){
					var rightPosition = 95,
						zIndex = 100 + t.count,
						currentListIndex;

					var to = index,
						displace = Math.abs((to < __prev)? t.count - Math.abs(to - __prev) : __prev - to);

					t.getChildren().each(function(__i, el){
						if($(el).data('index') == to){
							currentListIndex = __i;
						}
					}).each(function(__i, el){
						var __li = $(el),
							__relocate = (__i < currentListIndex);

						(function(t, i, prev, relocate, displace){
							var li = this,
								fade = li.find('.fade'),
								logo = li.find('.logo'),
								p = li.find('p'),
								index = parseInt(li.data('index')),
								currentRight = parseInt(li.css('right')),
								isCurrent = (to == index),
								limit = t.options.count;

							var rightDisplace = (t.options.count - 1) - i + displace,
								right = rightDisplace * t.stepPercent;

							t.animateCount++;

							setTimeout(activateSlide, 120);

							if(relocate){

								var steps = Math.abs(rightDisplace),
									stepSpeed = t.options.speed / Math.abs(rightDisplace);

								var li = $(el).clone(true).css({
									zIndex: 99 - steps,
									right: '0%'
								}).appendTo(t.ul).animate({
									right: ((currentListIndex - i - 1) * t.stepPercent) + '%'
								}, t.options.speed, function(){

									t.animateCount--;

									if(t.animateCount == 0){
										t.inAction = false;
										//activateSlide();
									}
								});

								$(el).addClass('deleting').animate({
									right: 120 + '%'
								}, t.options.speed - 100, function(){
									$(this).remove();
								});

							}else{
								var li = $(el).css({
									//zIndex: 100 + t.count - i
								}).animate({
									right: right + '%'
								},function(){
									t.animateCount--;

									if(t.animateCount == 0){
										t.inAction = false;
										//activateSlide();
									}
								});
							}

						}).call(__li, t, __i, __prev, __relocate, displace);

						//zIndex--;
						rightPosition -= t.stepPercent;
					});

					t.getChildren().each(function(i, el){
						$(el).css({
							zIndex: 100 + t.count - i
						});
					});
				};

				t.slideRight = function(index, __prev){
					var rightPosition = t.stepPercent * (t.count - t.options.count) + 100,
						zIndex = 100 + t.count,
						currentListIndex;

					var to = index,
						displace = (to > __prev)? t.count - (to - __prev) : __prev - to;

					// Reversed children
					t.getChildren(true).each(function(__i, el){
						if($(el).data('index') == to){
							currentListIndex = __i;
						}
					}).each(function(__i, el){
						var __li = $(el),
							__relocate = (__i <= currentListIndex);

						(function(t, i, prev, relocate, displace){
							var li = this,
								el = li[0],
								fade = li.find('.fade'),
								logo = li.find('.logo'),
								p = li.find('p'),
								index = parseInt(li.data('index')),
								currentRight = parseInt(li.css('right')),

								isCurrent = (to == index),

								// лимит элементов в блоке
								limit = t.options.count;

							var rightDisplace = (i - (t.count - t.options.count) - displace),
								right = rightDisplace * t.stepPercent;

							t.animateCount++;

							setTimeout(activateSlide, 120);

							if(relocate){

								var steps = Math.abs(rightDisplace),
									stepSpeed = t.options.speed / Math.abs(rightDisplace),
									right = (isCurrent)? 50 : 50 - (currentListIndex - i) * t.stepPercent;

								$(el).clone(true).css({
									zIndex: 150 - steps,
									right: 120+'%'
								}).prependTo(t.ul).animate({
									right: right + '%',
									opacity: 1
								}, t.options.speed - 100, function(){

									t.animateCount--;

									if(t.animateCount == 0){
										t.inAction = false;
										//activateSlide();
									}
								});

								$(el).addClass('deleting').animate({
									right: (-1 * t.stepPercent) + '%',
									opacity: 0
								}, t.options.speed - 100, function(){
									$(this).remove();
								});
							}else{
								$(el).css({zIndex: 100 + i}).animate({
									right: right + '%'
								},function(){
									t.animateCount--;

									if(t.animateCount == 0){
										t.inAction = false;
										//activateSlide();
									}
								});
							}

						}).call(__li, t, __i, __prev, __relocate, displace);
					});

					t.getChildren().each(function(i, el){
						$(el).css({
							zIndex: 100 + t.count - i
						});
					});
				};

				var rightPosition = 50,
					zIndex = 100 + t.count;

				t.getChildren().each(function(i, el){
					var li = $(el),
						img = li.children('img').first(),
						src =  img.attr('src'),
						logo = li.find('.logo'),
						p = li.find('p');

					li
						.css({
							'width'				: t.imageWidth + t.skewWidth,
							'-ms-transform' 	: 'skewX(-' + t.calcAngle + 'deg)',
							'transform' 		: 'skewX(-' + t.calcAngle + 'deg)',
							'zIndex' 			: zIndex,
							'right'				: rightPosition + '%',
							'marginRight' 		: '-' + (t.skewWidth / 2) + 'px'
						})
						.data('index', i)
						.append($(''))
						.click(function(){
							t.slideTo(i);
						});
					if(typeof $.browser.msie !== 'undefined' && parseInt($.browser.version) < 9){
						li.hover(function(){
							$(this).addClass('hover');
						},function(){
							$(this).removeClass('hover');
						});
					}

					if(i == t.currentIndex){
						li.removeClass('clickable');

						li.find('.fade').fadeIn();

						if(logo.length) t.panelText.append(logo.hide().clone().show());

						if(p.length) t.panelText.append(p.clone());

						t.panelText.fadeIn();
					}else{
						li.addClass('clickable');
					}

					li.hover(function(){
						if(li.data('index') == t.currentIndex) return false;
						li.find('.fade').fadeIn();
					},function(){
						if(li.data('index') == t.currentIndex) return false;
						li.find('.fade').fadeOut();
					});

					img.css({
						'-ms-transform' 	: 'skewX(' + t.calcAngle + 'deg)',
						'transform' 		: 'skewX(' + t.calcAngle + 'deg)',
						'right' 			: '-' + (t.skewWidth / 2) + 'px',
						//'width' 			: t.imageWidth
					});

					zIndex--;
					rightPosition -= t.stepPercent;
				});

				t.panel.append(
					$('').click(function(){
						t.slideTo(t.currentIndex - 1, 'right');
					})
				).append(
					$('').click(function(){
						t.slideTo(t.currentIndex + 1, 'left');
					}).css({right: ((-1 * ( this.skewWidth / 2 )) + 20)})
				);

				if(t.options.timer){
					t.ul.hover(function(){
						clearInterval(t.sliding);
					},function(){
						t.sliding = setInterval(autoSlide, t.options.timer);
					});
					t.sliding = setInterval(autoSlide, t.options.timer);
				}

				$(window).resize(onWindowResize);

				function autoSlide(){
					t.slideTo(t.currentIndex + 1, 'left');
				}

				function calculateSizes(){
					this.width = this.ul.width();
					this.height = this.ul.height();
					this.skewWidth = Math.round(this.height/Math.tan(this.skewAngle/180*Math.PI)*1000)/1000;
					this.imageWidth = this.width / 2 + this.skewWidth;
				}

				function onWindowResize(e){
					calculateSizes.call(t);
				}

				function activateSlide(){
					t.panelText.hide().empty();

					t.panelText.unbind('click');

					t.getChildren().not('.deleting').each(function(i, el){
						var li = $(el),
							a = li.find('a').first(),
							fade = li.find('.fade'),
							logo = li.find('.logo'),
							p = li.find('p'),
							index = parseInt(li.data('index'));

						if(t.currentIndex == index){
							li.removeClass('clickable');
							fade.fadeIn(200);
							if(logo.length) t.panelText.append(logo.hide().clone().show());
							if(p.length) t.panelText.append(p.clone());

							t.panelText.fadeIn(300).bind('click', function(){
								location.href = a[0].href;
							});
						}else{
							fade.fadeOut();
							li.addClass('clickable');
						}
					});
				}

				window.t = t;

			})(this, settings);

			this.Slider = Slider;
		});

		return this;
	};
})(jQuery);
<commit_msg>Fix Hover Slides<commit_after>;(function($){
	$.fn.udslider = function(options){
		this.each(function(i, el){
			if(typeof el.Slider === 'object'){
				return el.Slider;
			}

			// settings
			var settings = $.extend({
				angle: 75,
				count: 5,
				speed: 600,
				timer: 5000
			}, options);

			// typized
			settings.count = parseInt(settings.count);
			settings.angle = parseFloat(settings.angle);
			settings.speed = parseFloat(settings.speed);
			settings.timer = parseFloat(settings.timer);

			// slider object
			var Slider = new (function(ul, options){
				var t = this;

				// Elements
				t.ul = $(ul).fadeTo(1, 'slow');
				t.panel = t.ul.append($('

')).find('.panel');
				t.panelText = t.panel.append($('

')).find('.text');
				t.children = t.ul.children('li');

				// Initial parameters
				t.options = options;
				t.currentIndex = 0;
				t.animateCount = 0;
				t.inAction = false;
				t.count = t.children.length;
				t.skewAngle = t.options.angle;
				t.calcAngle = 90 - t.skewAngle;
				t.skewWidth = 0;
				t.imageWidth = 0;
				t.stepPercent = 50 / (t.options.count - 1);
				t.sliding = false;

				t.getChildren = function(__reverse){
					var reverse = (typeof __reverse === 'undefined')? false : __reverse;
					var list = $(t.ul[0]).children('li').get();
					return (reverse)? $(list.reverse()) : $(list);
				};

				// Calculate sizes
				calculateSizes.call(t);

				t.slideTo = function(index, __important){
					if(index == t.currentIndex) return false;

					if(t.inAction) return false;

					t.inAction = true;

					if(index > t.count - 1) index = index - t.count;
					if(index < 0) index = t.count + index;

					var current = t.currentIndex;

					t.currentIndex = index;

					t.panelText.fadeOut(90, function(){
						$(this).empty();
					});

					var calcSide = (index - current <= (t.count - 1) + current - index)? 'left' : 'right';
						important = __important || calcSide;

					if(important == 'left'){
						t.slideLeft(index, current);
					}else{
						t.slideRight(index, current);
					}

				};

				t.slideLeft = function(index, __prev){
					var rightPosition = 95,
						zIndex = 100 + t.count,
						currentListIndex;

					var to = index,
						displace = Math.abs((to < __prev)? t.count - Math.abs(to - __prev) : __prev - to);

					t.getChildren().each(function(__i, el){
						if($(el).data('index') == to){
							currentListIndex = __i;
						}
					}).each(function(__i, el){
						var __li = $(el),
							__relocate = (__i < currentListIndex);

						(function(t, i, prev, relocate, displace){
							var li = this,
								fade = li.find('.fade'),
								logo = li.find('.logo'),
								p = li.find('p'),
								index = parseInt(li.data('index')),
								currentRight = parseInt(li.css('right')),
								isCurrent = (to == index),
								limit = t.options.count;

							var rightDisplace = (t.options.count - 1) - i + displace,
								right = rightDisplace * t.stepPercent;

							t.animateCount++;

							setTimeout(activateSlide, 120);

							if(relocate){

								var steps = Math.abs(rightDisplace),
									stepSpeed = t.options.speed / Math.abs(rightDisplace);

								var li = $(el).clone(true).css({
									zIndex: 99 - steps,
									right: '0%'
								}).appendTo(t.ul).animate({
									right: ((currentListIndex - i - 1) * t.stepPercent) + '%'
								}, t.options.speed, function(){

									t.animateCount--;

									if(t.animateCount == 0){
										t.inAction = false;
										//activateSlide();
									}
								});

								$(el).addClass('deleting').animate({
									right: 120 + '%'
								}, t.options.speed - 100, function(){
									$(this).remove();
								});

							}else{
								var li = $(el).css({
									//zIndex: 100 + t.count - i
								}).animate({
									right: right + '%'
								},function(){
									t.animateCount--;

									if(t.animateCount == 0){
										t.inAction = false;
										//activateSlide();
									}
								});
							}

						}).call(__li, t, __i, __prev, __relocate, displace);

						//zIndex--;
						rightPosition -= t.stepPercent;
					});

					t.getChildren().each(function(i, el){
						$(el).css({
							zIndex: 100 + t.count - i
						});
					});
				};

				t.slideRight = function(index, __prev){
					var rightPosition = t.stepPercent * (t.count - t.options.count) + 100,
						zIndex = 100 + t.count,
						currentListIndex;

					var to = index,
						displace = (to > __prev)? t.count - (to - __prev) : __prev - to;

					// Reversed children
					t.getChildren(true).each(function(__i, el){
						if($(el).data('index') == to){
							currentListIndex = __i;
						}
					}).each(function(__i, el){
						var __li = $(el),
							__relocate = (__i <= currentListIndex);

						(function(t, i, prev, relocate, displace){
							var li = this,
								el = li[0],
								fade = li.find('.fade'),
								logo = li.find('.logo'),
								p = li.find('p'),
								index = parseInt(li.data('index')),
								currentRight = parseInt(li.css('right')),

								isCurrent = (to == index),

								// лимит элементов в блоке
								limit = t.options.count;

							var rightDisplace = (i - (t.count - t.options.count) - displace),
								right = rightDisplace * t.stepPercent;

							t.animateCount++;

							setTimeout(activateSlide, 120);

							if(relocate){

								var steps = Math.abs(rightDisplace),
									stepSpeed = t.options.speed / Math.abs(rightDisplace),
									right = (isCurrent)? 50 : 50 - (currentListIndex - i) * t.stepPercent;

								$(el).clone(true).css({
									zIndex: 150 - steps,
									right: 120+'%'
								}).prependTo(t.ul).animate({
									right: right + '%',
									opacity: 1
								}, t.options.speed - 100, function(){

									t.animateCount--;

									if(t.animateCount == 0){
										t.inAction = false;
										//activateSlide();
									}
								});

								$(el).addClass('deleting').animate({
									right: (-1 * t.stepPercent) + '%',
									opacity: 0
								}, t.options.speed - 100, function(){
									$(this).remove();
								});
							}else{
								$(el).css({zIndex: 100 + i}).animate({
									right: right + '%'
								},function(){
									t.animateCount--;

									if(t.animateCount == 0){
										t.inAction = false;
										//activateSlide();
									}
								});
							}

						}).call(__li, t, __i, __prev, __relocate, displace);
					});

					t.getChildren().each(function(i, el){
						$(el).css({
							zIndex: 100 + t.count - i
						});
					});
				};

				var rightPosition = 50,
					zIndex = 100 + t.count;

				t.getChildren().each(function(i, el){
					var li = $(el),
						img = li.children('img').first(),
						src =  img.attr('src'),
						logo = li.find('.logo'),
						p = li.find('p');

					li
						.css({
							'width'				: t.imageWidth + t.skewWidth,
							'-ms-transform' 	: 'skewX(-' + t.calcAngle + 'deg)',
							'transform' 		: 'skewX(-' + t.calcAngle + 'deg)',
							'zIndex' 			: zIndex,
							'right'				: rightPosition + '%',
							'marginRight' 		: '-' + (t.skewWidth / 2) + 'px'
						})
						.data('index', i)
						.append($(''))
						.click(function(){
							t.slideTo(i);
						});
					if(typeof $.browser.msie !== 'undefined' && parseInt($.browser.version) < 9){
						li.hover(function(){
							$(this).addClass('hover');
						},function(){
							$(this).removeClass('hover');
						});
					}

					if(i == t.currentIndex){
						li.removeClass('clickable');

						li.find('.fade').fadeIn();

						if(logo.length) t.panelText.append(logo.hide().clone().show());

						if(p.length) t.panelText.append(p.clone());

						t.panelText.fadeIn();
					}else{
						li.addClass('clickable');
					}

					li.hover(function(){
						if($(this).data('index') == t.currentIndex) return false;
						$(this).children('.fade').fadeIn();
					},function(){
						if($(this).data('index') == t.currentIndex) return false;
						$(this).children('.fade').fadeOut();
					});

					img.css({
						'-ms-transform' 	: 'skewX(' + t.calcAngle + 'deg)',
						'transform' 		: 'skewX(' + t.calcAngle + 'deg)',
						'right' 			: '-' + (t.skewWidth / 2) + 'px',
						//'width' 			: t.imageWidth
					});

					zIndex--;
					rightPosition -= t.stepPercent;
				});

				t.panel.append(
					$('').click(function(){
						t.slideTo(t.currentIndex - 1, 'right');
					})
				).append(
					$('').click(function(){
						t.slideTo(t.currentIndex + 1, 'left');
					}).css({right: ((-1 * ( this.skewWidth / 2 )) + 20)})
				);

				if(t.options.timer){
					t.ul.hover(function(){
						clearInterval(t.sliding);
					},function(){
						t.sliding = setInterval(autoSlide, t.options.timer);
					});
					t.sliding = setInterval(autoSlide, t.options.timer);
				}

				$(window).resize(onWindowResize);

				function autoSlide(){
					t.slideTo(t.currentIndex + 1, 'left');
				}

				function calculateSizes(){
					this.width = this.ul.width();
					this.height = this.ul.height();
					this.skewWidth = Math.round(this.height/Math.tan(this.skewAngle/180*Math.PI)*1000)/1000;
					this.imageWidth = this.width / 2 + this.skewWidth;
				}

				function onWindowResize(e){
					calculateSizes.call(t);
				}

				function activateSlide(){
					t.panelText.hide().empty();

					t.panelText.unbind('click');

					t.getChildren().not('.deleting').each(function(i, el){
						var li = $(el),
							a = li.find('a').first(),
							fade = li.find('.fade'),
							logo = li.find('.logo'),
							p = li.find('p'),
							index = parseInt(li.data('index'));

						if(t.currentIndex == index){
							li.removeClass('clickable');
							fade.fadeIn(200);
							if(logo.length) t.panelText.append(logo.hide().clone().show());
							if(p.length) t.panelText.append(p.clone());

							t.panelText.fadeIn(300).bind('click', function(){
								location.href = a[0].href;
							});
						}else{
							fade.fadeOut();
							li.addClass('clickable');
						}
					});
				}

				window.t = t;

			})(this, settings);

			this.Slider = Slider;
		});

		return this;
	};
})(jQuery);
<|endoftext|>


<commit_before>'use strict';
var lpad = require('lpad');

module.exports = function (grunt) {
	grunt.registerMultiTask('concurrent', 'Run grunt tasks concurrently', function () {
		var spawnOptions;
		var cb = this.async();
		var options = this.options();
		// Set the tasks based on the config format
		var tasks = this.data.tasks || this.data;

		// Optionally log the task output
		if (options.logConcurrentOutput) {
			spawnOptions = { stdio: 'inherit' };
		}

		lpad.stdout('    ');
		grunt.util.async.forEach(tasks, function (el, next) {
			var command = [ el ],
				args = grunt.option.flags();

			grunt.util.spawn({
				grunt: true,
				args: command.concat(args),
				opts: spawnOptions
			}, function (err, result, code) {
				if (err || code > 0) {
					grunt.warn(result.stderr || result.stdout);
				}
				grunt.log.writeln('\n' + result.stdout);
				next();
			});
		}, function () {
			lpad.stdout();
			cb();
		});
	});
};
<commit_msg>Simplify the logic<commit_after>'use strict';
var lpad = require('lpad');

module.exports = function (grunt) {
	grunt.registerMultiTask('concurrent', 'Run grunt tasks concurrently', function () {
		var spawnOptions;
		var cb = this.async();
		var options = this.options();
		// Set the tasks based on the config format
		var tasks = this.data.tasks || this.data;

		// Optionally log the task output
		if (options.logConcurrentOutput) {
			spawnOptions = { stdio: 'inherit' };
		}

		lpad.stdout('    ');
		grunt.util.async.forEach(tasks, function (task, next) {
			grunt.util.spawn({
				grunt: true,
				args: [task].concat(grunt.option.flags()),
				opts: spawnOptions
			}, function (err, result, code) {
				if (err || code > 0) {
					grunt.warn(result.stderr || result.stdout);
				}
				grunt.log.writeln('\n' + result.stdout);
				next();
			});
		}, function () {
			lpad.stdout();
			cb();
		});
	});
};
<|endoftext|>