<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF 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.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        document.getElementById('fnCamera').addEventListener('click', this.fnCamera, false);
        document.getElementById('fnScan').addEventListener('click', this.fnScan, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        alert("test name item ");

         var db = window.sqlitePlugin.openDatabase({name: "my.db", androidDatabaseImplementation: 2});

  db.transaction(function(tx) {
    tx.executeSql('DROP TABLE IF EXISTS test_table');
    tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, datas text, data_num integer, trythis text)');

    tx.executeSql("INSERT INTO test_table (datas, data_num,trythis) VALUES (?,?,?)", ["test", 100, "hmm"], function(tx, res) {
      console.log("insertId: " + res.insertId + " -- probably 1");
      alert("rowsAffected: " + res.rowsAffected + " -- should be 1");

      tx.executeSql("select datas, data_num as cnt from test_table;", [], function(tx, res) {
        alert("res.rows.length: " + res.rows.length + " -- should be 1");
        alert("res.rows.item(0).data: " + res.rows.item(0).datas + " -- should be test");
          alert("res.rows.item(1).data: " + res.rows.item(0).data  + " -- should be 100");
        // alert("res.rows.item(2).data: " + res.rows.trythis + " -- should be hmm");

      });

    }, function(e) {
      alert("ERROR: " + e.message);
    });
  });

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    },
    fnCamera: function(){
        navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
            destinationType: Camera.DestinationType.DATA_URL
        });

        function onSuccess(imageData) {
            var image = document.getElementById('myImage');
            image.src = "data:image/jpeg;base64," + imageData;
        }

        function onFail(message) {
            alert('Failed because: ' + message);
        }
    },
    fnScan: function(){
        cordova.plugins.barcodeScanner.scan(
          function (result) {
              alert("We got a barcode\n" +
                    "Result: " + result.text + "\n" +
                    "Format: " + result.format + "\n" +
                    "Cancelled: " + result.cancelled);
          },
          function (error) {
              alert("Scanning failed: " + error);
          }
       );

    }
};
<commit_msg>test select<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF 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.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        document.getElementById('fnCamera').addEventListener('click', this.fnCamera, false);
        document.getElementById('fnScan').addEventListener('click', this.fnScan, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        alert("test name item ");

         var db = window.sqlitePlugin.openDatabase({name: "my.db", androidDatabaseImplementation: 2});

  db.transaction(function(tx) {
    tx.executeSql('DROP TABLE IF EXISTS test_table');
    tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, datas text, data_num integer, trythis text)');

    tx.executeSql("INSERT INTO test_table (datas, data_num,trythis) VALUES (?,?,?)", ["test", 100, "hmm"], function(tx, res) {
      console.log("insertId: " + res.insertId + " -- probably 1");
      alert("rowsAffected: " + res.rowsAffected + " -- should be 1");

      tx.executeSql("select datas, data_num as cnt, trythis from test_table;", [], function(tx, res) {
        alert("res.rows.length: " + res.rows.length + " -- should be 1");
        alert("res.rows.item(0).data: " + res.rows.item(0).datas + " -- should be test");
          alert("res.rows.item(1).data: " + res.rows.item(0).cnt  + " -- should be 100");
         alert("res.rows.item(2).data: " + res.rows.trythis + " -- should be hmm");

      });

    }, function(e) {
      alert("ERROR: " + e.message);
    });
  });

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    },
    fnCamera: function(){
        navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
            destinationType: Camera.DestinationType.DATA_URL
        });

        function onSuccess(imageData) {
            var image = document.getElementById('myImage');
            image.src = "data:image/jpeg;base64," + imageData;
        }

        function onFail(message) {
            alert('Failed because: ' + message);
        }
    },
    fnScan: function(){
        cordova.plugins.barcodeScanner.scan(
          function (result) {
              alert("We got a barcode\n" +
                    "Result: " + result.text + "\n" +
                    "Format: " + result.format + "\n" +
                    "Cancelled: " + result.cancelled);
          },
          function (error) {
              alert("Scanning failed: " + error);
          }
       );

    }
};
<|endoftext|>


<commit_before>
// Styling content

// Place suggestion in query box
function suggestionAsValue() {
    var sLabel;
    sLabel = document.getElementById("suggest-label");
    sLabel.addEventListener("click", function () {
        document.getElementById("query").value = sLabel.innerHTML;
    });
}

function register() {
    var set1;
    var set2;
    var set3;
    var check1;
    var check2;
    var check3;
    var query;
    var formats;
    var querySplit;
    var suggestedFormat;

    query = document.getElementById("query").value;
    query = encodeURIComponent(query);
    // Note :- avoid hardcoded uuid.
    uuid = "8fd531a3ba79466f8a80e5c71dea9723"
    check1 = document.getElementById("music").checked;
    check2 = document.getElementById("video").checked;
    check3 = document.getElementById("books").checked;

    // Warning messages
    if (query === "") {
        document.getElementById("searchWarning").style.display = "block";
        document.getElementById("checkboxWarning").style.display = "none";
        event.preventDefault();
    } else if (check1 || check2 || check3) {
        // query logic
        if (document.getElementById("music").checked === true) {
            set1 = "mp3|wav|m4a|ogg|wma|flac";
        } else {
            set1 = "";
        }
        if (document.getElementById("video").checked === true) {
            set2 = "|mkv|mp4|avi|webm|flv|mov|mpg|mpeg";
        } else {
            set2 = "";
        }
        if (document.getElementById("books").checked === true) {
            set3 = "|epub|pdf";
        } else {
            set3 = "";
        }

        formats = set1 + set2 + set3;
        querySplit = query.split(".");
        suggestedFormat = querySplit[1];
        query = querySplit[0];
        formats = formats + "|" + suggestedFormat;

        /* eslint-disable */
        window.open("http://www.google.com/search?q="+query+" -"+uuid+" -inurl:(htm|html|php|pls|txt) intitle:index.of \"last modified\" ("+formats+")");
        /* eslint-enable */
    } else {
        document.getElementById("searchWarning").style.display = "none";
        document.getElementById("checkboxWarning").style.display = "block";
        event.preventDefault();
    }
}

function suggestion() {
    var suggestions;
    var random;
    suggestions = ["Anime",
        "Manga",
        "TV-Series",
        "Pokemon",
        "Big Bang",
        "Blues",
        "Rock",
        "Metal",
        "AC/DC",
        "Pop",
        "Soft Rock",
        "MJ",
        "Pink Floyd",
        "The Wall",
        "Shakira",
        "JeLo",
        "Hard Rock",
        "Old Blues",
        "Fiction",
        "Thriller",
        "Learning",
        "Eminem",
        "Green Day",
        "Metaliica",
        "Taylor Swift",
        "Drake"];

    random = Math.floor(Math.random() * suggestions.length);
    document.getElementById("suggest-label").innerHTML = suggestions[random];
}

document.addEventListener("DOMContentLoaded", function () {
    document.querySelector("button").addEventListener("click", register);
    suggestion();
    suggestionAsValue();
});
<commit_msg>popup.js: Make filename extensions acceptable in search query again<commit_after>
// Styling content

// Place suggestion in query box
function suggestionAsValue() {
    var sLabel;
    sLabel = document.getElementById("suggest-label");
    sLabel.addEventListener("click", function () {
        document.getElementById("query").value = sLabel.innerHTML;
    });
}

function register() {
    var set1;
    var set2;
    var set3;
    var check1;
    var check2;
    var check3;
    var query;
    var formats;
    var querySplit;
    var suggestedFormat;
    var dotCheck;

    query = document.getElementById("query").value;
    query = encodeURIComponent(query);
    // Note :- avoid hardcoded uuid.
    uuid = "8fd531a3ba79466f8a80e5c71dea9723"
    check1 = document.getElementById("music").checked;
    check2 = document.getElementById("video").checked;
    check3 = document.getElementById("books").checked;
    querySplit = query.split(".");
    dotCheck = querySplit.length > 1 ? true : false;

    // Warning messages
    if (query === "") {
        document.getElementById("searchWarning").style.display = "block";
        document.getElementById("checkboxWarning").style.display = "none";
        event.preventDefault();
    } else if (check1 || check2 || check3 || dotCheck) {
        // query logic
        if (document.getElementById("music").checked === true) {
            set1 = "mp3|wav|m4a|ogg|wma|flac";
        } else {
            set1 = "";
        }
        if (document.getElementById("video").checked === true) {
            set2 = "|mkv|mp4|avi|webm|flv|mov|mpg|mpeg";
        } else {
            set2 = "";
        }
        if (document.getElementById("books").checked === true) {
            set3 = "|epub|pdf";
        } else {
            set3 = "";
        }
        formats = set1 + set2 + set3;
        if (dotCheck) {
            suggestedFormat = querySplit[1];
            query = querySplit[0];
            formats = formats + "|" + suggestedFormat;
        }
        /* eslint-disable */
        window.open("http://www.google.com/search?q="+query+" -"+uuid+" -inurl:(htm|html|php|pls|txt) intitle:index.of \"last modified\" ("+formats+")");
        /* eslint-enable */
    } else {
        document.getElementById("searchWarning").style.display = "none";
        document.getElementById("checkboxWarning").style.display = "block";
        event.preventDefault();
    }
}

function suggestion() {
    var suggestions;
    var random;
    suggestions = ["Anime",
        "Manga",
        "TV-Series",
        "Pokemon",
        "Big Bang",
        "Blues",
        "Rock",
        "Metal",
        "AC/DC",
        "Pop",
        "Soft Rock",
        "MJ",
        "Pink Floyd",
        "The Wall",
        "Shakira",
        "JeLo",
        "Hard Rock",
        "Old Blues",
        "Fiction",
        "Thriller",
        "Learning",
        "Eminem",
        "Green Day",
        "Metaliica",
        "Taylor Swift",
        "Drake"];

    random = Math.floor(Math.random() * suggestions.length);
    document.getElementById("suggest-label").innerHTML = suggestions[random];
}

document.addEventListener("DOMContentLoaded", function () {
    document.querySelector("button").addEventListener("click", register);
    suggestion();
    suggestionAsValue();
});
<|endoftext|>


<commit_before>import React, { useEffect, useRef } from "react";
import styled from "styled-components";

const Mandelbrot = () => {
  const canvas = useRef(null);

  const drawMandelbrot = () => {
    // Get our canvas and draw stars
    const cvs = canvas.current;
    const ctx = cvs.getContext("2d");

    // Mandelbrot set options
    let mag = 4700;
    const panX = 1.55;
    const panY = 0.105;
    const max = 100;

    // Check if coords are in mandelbrot set
    function checkCoord(x, y) {
      let r = x;
      let i = y;
      for (var itr = 0; itr < max; itr++) {
        const tr = r * r - i * i + x;
        const ti = 2 * r * i + y;
        r = tr;
        i = ti;

        // Return a number as a percentage if not in set for use in coloring
        if (r * i > 5) return (itr / max) * 100;
      }
      return 0; // Return zero if in set
    }

    // Add pixels to canvas
    for (let x = 0; x < cvs.width; x++) {
      for (let y = 0; y < cvs.height; y++) {
        const coordValue = checkCoord(x / mag - panX, y / mag - panY);
        ctx.fillStyle = `hsl(${coordValue * 3}, 100%, ${coordValue}%)`;
        ctx.fillRect(x, y, 1, 1);
      }
    }
  };

  useEffect(() => {
    // Get the canvas for resizing
    const cvs = canvas.current;

    // Size canvas to the parent, increase DPI
    cvs.width = cvs.offsetWidth * 2;
    cvs.height = cvs.offsetHeight * 2;

    // Add new event listener for resize the canvas on window resize
    const resizeCanvas = () => {
      cvs.width = cvs.offsetWidth;
      cvs.height = cvs.offsetHeight;
      drawMandelbrot();
    };
    window.addEventListener("resize", resizeCanvas);

    // Clean up event listener when dismounting the component
    return () => {
      window.removeEventListener("resize", resizeCanvas);
    };
  }, []);

  useEffect(() => {
    drawMandelbrot();
  }, []);

  return <Canvas ref={canvas} />;
};

export default Mandelbrot;

const Canvas = styled.canvas`
  width: 100%;
  height: 100%;
`;
<commit_msg>Fix dpi bug in mandelbrot<commit_after>import React, { useEffect, useRef } from "react";
import styled from "styled-components";

const Mandelbrot = () => {
  const canvas = useRef(null);

  const drawMandelbrot = () => {
    // Get our canvas and draw stars
    const cvs = canvas.current;
    const ctx = cvs.getContext("2d");

    // Mandelbrot set options
    let mag = 4700;
    const panX = 1.55;
    const panY = 0.105;
    const max = 100;

    // Check if coords are in mandelbrot set
    function checkCoord(x, y) {
      let r = x;
      let i = y;
      for (var itr = 0; itr < max; itr++) {
        const tr = r * r - i * i + x;
        const ti = 2 * r * i + y;
        r = tr;
        i = ti;

        // Return a number as a percentage if not in set for use in coloring
        if (r * i > 5) return (itr / max) * 100;
      }
      return 0; // Return zero if in set
    }

    // Add pixels to canvas
    for (let x = 0; x < cvs.width; x++) {
      for (let y = 0; y < cvs.height; y++) {
        const coordValue = checkCoord(x / mag - panX, y / mag - panY);
        ctx.fillStyle = `hsl(${coordValue * 3}, 100%, ${coordValue}%)`;
        ctx.fillRect(x, y, 1, 1);
      }
    }
  };

  useEffect(() => {
    // Get the canvas for resizing
    const cvs = canvas.current;
    const dpi = 2;

    // Size canvas to the parent, increase DPI
    cvs.width = cvs.offsetWidth * dpi;
    cvs.height = cvs.offsetHeight * dpi;

    // Add new event listener for resize the canvas on window resize
    const resizeCanvas = () => {
      cvs.width = cvs.offsetWidth * dpi;
      cvs.height = cvs.offsetHeight * dpi;
      drawMandelbrot();
    };
    window.addEventListener("resize", resizeCanvas);

    // Clean up event listener when dismounting the component
    return () => {
      window.removeEventListener("resize", resizeCanvas);
    };
  }, []);

  useEffect(() => {
    drawMandelbrot();
  }, []);

  return <Canvas ref={canvas} />;
};

export default Mandelbrot;

const Canvas = styled.canvas`
  width: 100%;
  height: 100%;
`;
<|endoftext|>


<commit_before>module.exports = function(data, Bot, Config, Helpers) {

	var request = require('request');
	var message;

	//
	// Get the param
	//

	var param = Helpers.getCommandPart(data.message, '2', Config);
	var param2 = Helpers.getCommandPart(data.message, '3', Config);

	if(typeof param !== 'undefined' && param.match(/<@[0-9]+>/gi).length == '1'){

	}

	request('http://codeshare.io/new', function (error, response, body) {
		if (!error && response.statusCode == 200) {

			if(typeof param !== 'undefined' && param.match(/<@[0-9]+>/gi).length == '1'){
				message = param + " -> " + response.request.href;
			}else{
				message = response.request.href;
			}

			Bot.setUsername(data.user, function(response) {
				Bot.sendMessage({
					'to': data.channelID,
					'message': message
				});
				Bot.setUsername(Config.commandPrefix + "" + Config.botName);
			});

		}else{

			if(typeof param !== 'undefined' && param.match(/<@[0-9]+>/gi).length == '1'){
				message = param + " -> " + "http://pastie.org/";
			}else{
				message = "http://pastie.org/";
			}

			Bot.setUsername(data.user, function(response) {
				Bot.sendMessage({
					'to': data.channelID,
					'message': message
				});
				Bot.setUsername(Config.commandPrefix + "" + Config.botName);
			});

		}
	});

}<commit_msg>Nettoyage<commit_after>module.exports = function(data, Bot, Config, Helpers) {

	var request = require('request');
	var message;

	//
	// Get the param
	//

	var param = Helpers.getCommandPart(data.message, '2', Config);

	request('http://codeshare.io/new', function (error, response, body) {
		if (!error && response.statusCode == 200) {

			if(typeof param !== 'undefined' && param.match(/<@[0-9]+>/gi).length == '1'){
				message = param + " -> " + response.request.href;
			}else{
				message = response.request.href;
			}

			Bot.setUsername(data.user, function(response) {
				Bot.sendMessage({
					'to': data.channelID,
					'message': message
				});
				Bot.setUsername(Config.commandPrefix + "" + Config.botName);
			});

		}else{

			if(typeof param !== 'undefined' && param.match(/<@[0-9]+>/gi).length == '1'){
				message = param + " -> " + "http://pastie.org/";
			}else{
				message = "http://pastie.org/";
			}

			Bot.setUsername(data.user, function(response) {
				Bot.sendMessage({
					'to': data.channelID,
					'message': message
				});
				Bot.setUsername(Config.commandPrefix + "" + Config.botName);
			});

		}
	});

}<|endoftext|>


<commit_before>/*! Remodal - v0.1.7 - 2014-07-14
 * https://github.com/VodkaBears/remodal
 * Copyright (c) 2014 VodkaBears; */
;(function ($) {
    "use strict";

    /**
     * Remodal settings
     */
    var pluginName = "remodal",
        defaults = {
            hashTracking: true,
            closeOnConfirm: true,
            closeOnCancel: true
        };

    /**
     * Special plugin object for instances.
     * @type {Object}
     */
    $[pluginName] = {
        lookup: []
    };

    var current, // current modal
        scrollTop; // scroll position

    /**
     * Get transition duration in ms
     * @return {Number}
     */
    var getTransitionDuration = function ($elem) {
        var duration = $elem.css('transition-duration') ||
            $elem.css('-webkit-transition-duration') ||
            $elem.css('-moz-transition-duration') ||
            $elem.css('-o-transition-duration') ||
            $elem.css('-ms-transition-duration') ||
            0;
        var delay = $elem.css('transition-delay') ||
            $elem.css('-webkit-transition-delay') ||
            $elem.css('-moz-transition-delay') ||
            $elem.css('-o-transition-delay') ||
            $elem.css('-ms-transition-delay') ||
            0;

        return (parseFloat(duration) + parseFloat(delay)) * 1000;
    };

    /**
     * Get a scrollbar width
     * @return {Number}
     */
    var getScrollbarWidth = function () {
        if ($(document.body).height() <= $(window).height()) {
            return 0;
        }

        var outer = document.createElement("div");
        outer.style.visibility = "hidden";
        outer.style.width = "100px";
        document.body.appendChild(outer);

        var widthNoScroll = outer.offsetWidth;
        // force scrollbars
        outer.style.overflow = "scroll";

        // add innerdiv
        var inner = document.createElement("div");
        inner.style.width = "100%";
        outer.appendChild(inner);

        var widthWithScroll = inner.offsetWidth;

        // remove divs
        outer.parentNode.removeChild(outer);

        return widthNoScroll - widthWithScroll;
    };

    /**
     * Lock screen
     */
    var lockScreen = function () {
        $(document.body).css("padding-right", "+=" + getScrollbarWidth());
        $("html, body").addClass(pluginName + "_lock");
    };

    /**
     * Unlock screen
     */
    var unlockScreen = function () {
        $(document.body).css("padding-right", "-=" + getScrollbarWidth());
        $("html, body").removeClass(pluginName + "_lock");
    };

    /**
     * Remodal constructor
     */
    function Remodal(modal, options) {
        this.settings = $.extend({}, defaults, options);
        this.modal = modal;
        this.buildDOM();
        this.addEventListeners();
        this.index = $[pluginName].lookup.push(this) - 1;
        this.busy = false;
    }

    /**
     * Build required DOM
     */
    Remodal.prototype.buildDOM = function () {
        this.body = $(document.body);
        this.bg = $("." + pluginName + "-bg");
        this.modalClose = $("").addClass(pluginName + "-close");
        this.overlay = $("
").addClass(pluginName + "-overlay");
        if (!this.modal.hasClass(pluginName)) {
            this.modal.addClass(pluginName);
        }

        this.modal.css("visibility", "visible");
        this.modal.append(this.modalClose);
        this.overlay.append(this.modal);
        this.body.append(this.overlay);

        this.confirm = this.modal.find("." + pluginName + "-confirm");
        this.cancel = this.modal.find("." + pluginName + "-cancel");

        var tdOverlay = getTransitionDuration(this.overlay),
            tdModal = getTransitionDuration(this.modal),
            tdBg = getTransitionDuration(this.bg);
        this.td = tdModal > tdOverlay ? tdModal : tdOverlay;
        this.td = tdBg > this.td ? tdBg : this.td;
    };

    /**
     * Add event listeners to the current modal window
     */
    Remodal.prototype.addEventListeners = function () {
        var self = this;

        this.modalClose.bind("click." + pluginName, function (e) {
            e.preventDefault();
            self.close();
        });

        this.cancel.bind("click." + pluginName, function (e) {
            e.preventDefault();
            self.modal.trigger("cancel");
            if (self.settings.closeOnCancel) {
                self.close();
            }
        });

        this.confirm.bind("click." + pluginName, function (e) {
            e.preventDefault();
            self.modal.trigger("confirm");
            if (self.settings.closeOnConfirm) {
                self.close();
            }
        });

        $(document).bind('keyup.' + pluginName, function (e) {
            if (e.keyCode === 27) {
                self.close();
            }
        });

        this.overlay.bind("click." + pluginName, function (e) {
            var $target = $(e.target);
            if (!$target.hasClass(pluginName + "-overlay")) {
                return;
            }

            self.close();
        });
    };

    /**
     * Open modal window
     */
    Remodal.prototype.open = function () {
        // check if animation is complete
        if (this.busy) {
            return;
        }
        this.busy = true;

        this.modal.trigger("open");

        var id = this.modal.attr("data-" + pluginName + "-id");
        if (id && this.settings.hashTracking) {
            scrollTop = $(window).scrollTop();
            location.hash = id;
        }

        if (current && current !== this) {
            current.overlay.hide();
            current.body.removeClass(pluginName + "_active");
        }
        current = this;

        lockScreen();
        this.overlay.show();

        var self = this;
        setTimeout(function () {
            self.body.addClass(pluginName + "_active");

            setTimeout(function () {
                self.busy = false;
                self.modal.trigger("opened");
            }, self.td + 50);
        }, 25);
    };

    /**
     * Close modal window
     */
    Remodal.prototype.close = function () {
        // check if animation is complete
        if (this.busy) {
            return;
        }
        this.busy = true;

        this.modal.trigger("close");

        if (this.settings.hashTracking &&
            this.modal.attr("data-" + pluginName + "-id") === location.hash.substr(1)) {
            location.hash = "";
            $(window).scrollTop(scrollTop);
        }

        this.body.removeClass(pluginName + "_active");

        var self = this;
        setTimeout(function () {
            self.overlay.hide();
            unlockScreen();

            self.busy = false;
            self.modal.trigger("closed");
        }, self.td + 50);
    };

    if ($) {
        $["fn"][pluginName] = function (opts) {
            var instance;
            this["each"](function (i, e) {
                var $e = $(e);
                if ($e.data(pluginName) == null) {
                    instance = new Remodal($e, opts);
                    $e.data(pluginName, instance.index);

                    if (instance.settings.hashTracking &&
                        $e.attr("data-" + pluginName + "-id") === location.hash.substr(1)) {
                        instance.open();
                    }
                }
            });

            return instance;
        };
    }

    $(document).ready(function () {
        /**
         * data-remodal-target opens a modal window with a special id without hash change.
         */
        $(document).on("click", "[data-" + pluginName + "-target]", function (e) {
            e.preventDefault();

            var elem = e.currentTarget,
                id = elem.getAttribute("data-" + pluginName + "-target"),
                $target = $("[data-" + pluginName + "-id=" + id + "]");

            $[pluginName].lookup[$target.data(pluginName)].open();
        });

        /**
         * Auto initialization of modal windows.
         * They should have the 'remodal' class attribute.
         * Also you can pass params into the modal throw the data-remodal-options attribute.
         * data-remodal-options must be a valid JSON string.
         */
        $(document).find("." + pluginName).each(function (i, container) {
            var $container = $(container),
                options = $container.data(pluginName + "-options");

            if (!options) {
                options = {};
            }

            $container[pluginName](options);
        });
    });

    /**
     * Hashchange handling to show a modal with a special id.
     */
    var hashHandler = function (e, closeOnEmptyHash) {
        var id = location.hash.replace("#", "");

        if (typeof closeOnEmptyHash === "undefined") {
            closeOnEmptyHash = true;
        }

        if (!id) {
            if (closeOnEmptyHash) {
                // check if we have currently opened modal and animation is complete
                if (current && !current.busy && current.settings.hashTracking) {
                    current.close();
                }
            }
        } else {
            var $elem;

            // Catch syntax error if your hash is bad
            try {
                $elem = $("[data-" + pluginName + "-id=" + id.replace(new RegExp('/', 'g'), "\\/") + "]");
            } catch (e) {}

            if ($elem && $elem.length) {
                var instance = $[pluginName].lookup[$elem.data(pluginName)];

                if (instance && instance.settings.hashTracking) {
                    instance.open();
                }
            }

        }
    };
    $(window).bind("hashchange." + pluginName, hashHandler);
})(window["jQuery"] || window["Zepto"]);
<commit_msg>Fix jshint errors<commit_after>/*! Remodal - v0.1.7 - 2014-07-14
 * https://github.com/VodkaBears/remodal
 * Copyright (c) 2014 VodkaBears; */
;(function ($) {
    "use strict";

    /**
     * Remodal settings
     */
    var pluginName = "remodal",
        defaults = {
            hashTracking: true,
            closeOnConfirm: true,
            closeOnCancel: true
        };

    /**
     * Special plugin object for instances.
     * @type {Object}
     */
    $[pluginName] = {
        lookup: []
    };

    var current, // current modal
        scrollTop; // scroll position

    /**
     * Get transition duration in ms
     * @return {Number}
     */
    var getTransitionDuration = function ($elem) {
        var duration = $elem.css("transition-duration") ||
            $elem.css("-webkit-transition-duration") ||
            $elem.css("-moz-transition-duration") ||
            $elem.css("-o-transition-duration") ||
            $elem.css("-ms-transition-duration") ||
            0;
        var delay = $elem.css("transition-delay") ||
            $elem.css("-webkit-transition-delay") ||
            $elem.css("-moz-transition-delay") ||
            $elem.css("-o-transition-delay") ||
            $elem.css("-ms-transition-delay") ||
            0;

        return (parseFloat(duration) + parseFloat(delay)) * 1000;
    };

    /**
     * Get a scrollbar width
     * @return {Number}
     */
    var getScrollbarWidth = function () {
        if ($(document.body).height() <= $(window).height()) {
            return 0;
        }

        var outer = document.createElement("div");
        outer.style.visibility = "hidden";
        outer.style.width = "100px";
        document.body.appendChild(outer);

        var widthNoScroll = outer.offsetWidth;
        // force scrollbars
        outer.style.overflow = "scroll";

        // add innerdiv
        var inner = document.createElement("div");
        inner.style.width = "100%";
        outer.appendChild(inner);

        var widthWithScroll = inner.offsetWidth;

        // remove divs
        outer.parentNode.removeChild(outer);

        return widthNoScroll - widthWithScroll;
    };

    /**
     * Lock screen
     */
    var lockScreen = function () {
        $(document.body).css("padding-right", "+=" + getScrollbarWidth());
        $("html, body").addClass(pluginName + "_lock");
    };

    /**
     * Unlock screen
     */
    var unlockScreen = function () {
        $(document.body).css("padding-right", "-=" + getScrollbarWidth());
        $("html, body").removeClass(pluginName + "_lock");
    };

    /**
     * Remodal constructor
     */
    function Remodal(modal, options) {
        this.settings = $.extend({}, defaults, options);
        this.modal = modal;
        this.buildDOM();
        this.addEventListeners();
        this.index = $[pluginName].lookup.push(this) - 1;
        this.busy = false;
    }

    /**
     * Build required DOM
     */
    Remodal.prototype.buildDOM = function () {
        this.body = $(document.body);
        this.bg = $("." + pluginName + "-bg");
        this.modalClose = $("").addClass(pluginName + "-close");
        this.overlay = $("
").addClass(pluginName + "-overlay");
        if (!this.modal.hasClass(pluginName)) {
            this.modal.addClass(pluginName);
        }

        this.modal.css("visibility", "visible");
        this.modal.append(this.modalClose);
        this.overlay.append(this.modal);
        this.body.append(this.overlay);

        this.confirm = this.modal.find("." + pluginName + "-confirm");
        this.cancel = this.modal.find("." + pluginName + "-cancel");

        var tdOverlay = getTransitionDuration(this.overlay),
            tdModal = getTransitionDuration(this.modal),
            tdBg = getTransitionDuration(this.bg);
        this.td = tdModal > tdOverlay ? tdModal : tdOverlay;
        this.td = tdBg > this.td ? tdBg : this.td;
    };

    /**
     * Add event listeners to the current modal window
     */
    Remodal.prototype.addEventListeners = function () {
        var self = this;

        this.modalClose.bind("click." + pluginName, function (e) {
            e.preventDefault();
            self.close();
        });

        this.cancel.bind("click." + pluginName, function (e) {
            e.preventDefault();
            self.modal.trigger("cancel");
            if (self.settings.closeOnCancel) {
                self.close();
            }
        });

        this.confirm.bind("click." + pluginName, function (e) {
            e.preventDefault();
            self.modal.trigger("confirm");
            if (self.settings.closeOnConfirm) {
                self.close();
            }
        });

        $(document).bind("keyup." + pluginName, function (e) {
            if (e.keyCode === 27) {
                self.close();
            }
        });

        this.overlay.bind("click." + pluginName, function (e) {
            var $target = $(e.target);
            if (!$target.hasClass(pluginName + "-overlay")) {
                return;
            }

            self.close();
        });
    };

    /**
     * Open modal window
     */
    Remodal.prototype.open = function () {
        // check if animation is complete
        if (this.busy) {
            return;
        }
        this.busy = true;

        this.modal.trigger("open");

        var id = this.modal.attr("data-" + pluginName + "-id");
        if (id && this.settings.hashTracking) {
            scrollTop = $(window).scrollTop();
            location.hash = id;
        }

        if (current && current !== this) {
            current.overlay.hide();
            current.body.removeClass(pluginName + "_active");
        }
        current = this;

        lockScreen();
        this.overlay.show();

        var self = this;
        setTimeout(function () {
            self.body.addClass(pluginName + "_active");

            setTimeout(function () {
                self.busy = false;
                self.modal.trigger("opened");
            }, self.td + 50);
        }, 25);
    };

    /**
     * Close modal window
     */
    Remodal.prototype.close = function () {
        // check if animation is complete
        if (this.busy) {
            return;
        }
        this.busy = true;

        this.modal.trigger("close");

        if (this.settings.hashTracking &&
            this.modal.attr("data-" + pluginName + "-id") === location.hash.substr(1)) {
            location.hash = "";
            $(window).scrollTop(scrollTop);
        }

        this.body.removeClass(pluginName + "_active");

        var self = this;
        setTimeout(function () {
            self.overlay.hide();
            unlockScreen();

            self.busy = false;
            self.modal.trigger("closed");
        }, self.td + 50);
    };

    if ($) {
        $.fn[pluginName] = function (opts) {
            var instance;
            this.each(function (i, e) {
                var $e = $(e);
                if ($e.data(pluginName) == null) {
                    instance = new Remodal($e, opts);
                    $e.data(pluginName, instance.index);

                    if (instance.settings.hashTracking &&
                        $e.attr("data-" + pluginName + "-id") === location.hash.substr(1)) {
                        instance.open();
                    }
                }
            });

            return instance;
        };
    }

    $(document).ready(function () {
        /**
         * data-remodal-target opens a modal window with a special id without hash change.
         */
        $(document).on("click", "[data-" + pluginName + "-target]", function (e) {
            e.preventDefault();

            var elem = e.currentTarget,
                id = elem.getAttribute("data-" + pluginName + "-target"),
                $target = $("[data-" + pluginName + "-id=" + id + "]");

            $[pluginName].lookup[$target.data(pluginName)].open();
        });

        /**
         * Auto initialization of modal windows.
         * They should have the 'remodal' class attribute.
         * Also you can pass params into the modal throw the data-remodal-options attribute.
         * data-remodal-options must be a valid JSON string.
         */
        $(document).find("." + pluginName).each(function (i, container) {
            var $container = $(container),
                options = $container.data(pluginName + "-options");

            if (!options) {
                options = {};
            }

            $container[pluginName](options);
        });
    });

    /**
     * Hashchange handling to show a modal with a special id.
     */
    var hashHandler = function (e, closeOnEmptyHash) {
        var id = location.hash.replace("#", "");

        if (typeof closeOnEmptyHash === "undefined") {
            closeOnEmptyHash = true;
        }

        if (!id) {
            if (closeOnEmptyHash) {
                // check if we have currently opened modal and animation is complete
                if (current && !current.busy && current.settings.hashTracking) {
                    current.close();
                }
            }
        } else {
            var $elem;

            // Catch syntax error if your hash is bad
            try {
                $elem = $("[data-" + pluginName + "-id=" + id.replace(new RegExp("/", "g"), "\\/") + "]");
            } catch (e) {}

            if ($elem && $elem.length) {
                var instance = $[pluginName].lookup[$elem.data(pluginName)];

                if (instance && instance.settings.hashTracking) {
                    instance.open();
                }
            }

        }
    };
    $(window).bind("hashchange." + pluginName, hashHandler);
})(window.jQuery || window.Zepto);
<|endoftext|>


<commit_before>
/**
 * header cell view, manages operations on table columns
 */

(function() {

var HeaderView = cdb.admin.HeaderView = cdb.core.View.extend({

  _TEXTS: {
    no_geo: {
      title:        _t('Georeference your table'),
      description:  _t('This funcionality is not available in the visualization view. \
                    Please, visit <a href="<%- prefix %>/tables/<%- table_name %>">your table and start georeferencing there.'),
      ok:           _t('Ok, close')
    }
  },

  NO_MENU_COLUMNS: ['the_geom', 'the_geom_webmercator'],

  events: {
    'dblclick .coloptions':     'renameColumn',
    'click    .coloptions':     'showColumnOptions',
    'click    .coltype':        'showColumnTypeOptions',
    'click    .geo':            'showGeoreferenceWindow',
    'keydown  .col_name_edit':  '_checkEditColnameInput',
    'focusout input':           '_finishEdit',
    'click':                    'activateColumnOptions'
  },

  initialize: function() {
    var self = this;
    this.column = this.options.column;
    this.table = this.options.table;
    this.vis = this.options.vis;
    this.template = this.getTemplate('table/views/table_header_view');
    this.editing_name = false;
    this.changing_type = false;

    this.vis.bind('change:type', function() {
      // You can't geocode being in a visualization of type derived
      HeaderView && HeaderView.colTypeOptions.render();
    });

    this.add_related_model(this.vis);

    if (HeaderView.colOptions === undefined) {
      HeaderView.colOptions= new cdb.admin.HeaderDropdown({
        user: this.options.user,
        position: 'position',
        horizontal_position: "right",
        tick: "right",
        template_base: "table/views/table_header_options",
        sqlView: this.options.sqlView,
        vis: this.vis
      });
      HeaderView.colOptions.render();

      cdb.god.bind("closeDialogs", HeaderView.colOptions.hide, HeaderView.colOptions);
    }

    if (HeaderView.colTypeOptions === undefined) {
      HeaderView.colTypeOptions= new cdb.admin.ColumntypeDropdown({
        user: this.options.user,
        position: 'position',
        horizontal_position: "right",
        tick: "right",
        template_base: "table/views/table_column_type_options"
      });
      HeaderView.colTypeOptions.render();
      cdb.god.bind("closeDialogs", HeaderView.colTypeOptions.hide, HeaderView.colTypeOptions);
    }
  },

  _addColumn: function(column) {
    table.tableTab.tableView.addColumn(column);
  },

  render: function() {
    this.$el.html('');

    this.$el.append(this.template({
      col_name:         this.column[0],
      col_type:         this.column[1],
      editing_name:     this.editing_name,
      changing_type:    this.changing_type,
      read_only:        this.table.isReadOnly(),
      isReservedColumn: this.table.isReadOnly() || this.table.isReservedColumn(this.column[0]),
      noMenu:           (this.NO_MENU_COLUMNS.indexOf(this.column[0]) >= 0)
    }));

    // Focus in the input if it is being edited
    // and set the correct width
    if (this.editing_name) {
      var w = this.$el.find("p.auto").width();
      this.$el.find("input")
        .css({
          "max-width":  w,
          "width":      w
        })
        .focus();
    }

    this.delegateEvents();

    return this;
  },

  _openColOptions: function(e) {
    var self = this;
    var colOptions = HeaderView.colOptions;

    // Unbind events
    colOptions.off();
    cdb.god.unbind('closeDialogs', HeaderView.colOptions.hide, HeaderView.colOptions);

    // Close other dialogs
    cdb.god.trigger("closeDialogs");

    // set data for column and table currently editing
    colOptions.setTable(this.table, this.column[0]);

    colOptions.bind('addColumn', this._addColumn, this);
    colOptions.bind('renameColumn', this.renameColumn, this);
    colOptions.bind('changeType', this._changeType, this);
    colOptions.bind('clearView', function(){
      self.trigger('clearView');
    }, this);
    colOptions.bind('georeference', function(column) {
      self.trigger('georeference', column);
    }, this);
    colOptions.bind('applyFilter', function(column) {
      self.trigger('applyFilter', column);
    }, this);

    // bind the stuff
    var container = $(e.target).parent().parent();
    container.append(colOptions.el);

    var link_width  = $(e.target).width() + 26
      , th          = container.parent();

    // align to the right of the target with a little of margin
    colOptions.openAt(link_width - colOptions.$el.width(), (th.height()/2) + 7);

    // Bind again!
    cdb.god.bind("closeDialogs", HeaderView.colOptions.hide, HeaderView.colOptions);
  },

  _openColTypeOptions: function(e) {
    if(this.table.isReadOnly()) {
      return;
    }
    var colOptions = HeaderView.colTypeOptions;

    // Unbind events
    colOptions.off();
    cdb.god.unbind('closeDialogs', HeaderView.colTypeOptions.hide, HeaderView.colTypeOptions);

    // Close other dialogs
    cdb.god.trigger("closeDialogs");

    // set data for column and table currently editing
    colOptions.setTable(this.table, this.column[0]);

    // bind the stuff
    var container = $(e.target).parent().parent();
    container.append(colOptions.el);

    var link_width  = $(e.target).outerWidth() + 24
      , th          = container.parent();

    // align to the right of the target with a little of margin
    colOptions.openAt(link_width - colOptions.$el.width(), (th.height()/2) + 25);

    // Bind again
    cdb.god.bind("closeDialogs", HeaderView.colTypeOptions.hide, HeaderView.colTypeOptions);
  },

  _checkEditColnameInput: function(e) {
    if(e.keyCode === 13) {
      this._submitEdit();
    }
    if(e.keyCode === 27) {
      this._finishEdit();
    }

  },

  _submitEdit: function() {
    this.table.renameColumn(this.column[0], $('.col_name_edit').val());
    this._finishEdit();
  },

  _finishEdit: function() {
    this.editing_name = false;
    this.render();
  },

  renameColumn: function(ev) {
    if (ev) {
      this.killEvent(ev)
    }

    this.editing_name = true;
    this.changing_type = false;
    this.render();
  },

  _changeType: function(column) {
    this.editing_name = false;
    this.changing_type = true;

    // Simulate click
    var $coltype_link = this.$el.find('a.coltype');
    $coltype_link.click();
  },

  activateColumnOptions: function(e) {
    this.killEvent(e);
    this.$el.find("a.coloptions").click();
  },

  showColumnOptions: function(e) {
    var self = this;
    var colOptions = HeaderView.colOptions;
    var columnName = this.column[0];

    e.preventDefault();

    // If submenu was openened before, let's close it.
    if (colOptions.isOpen && columnName == colOptions.column) {
      colOptions.hide();
      return false;
    }

    // If submenu is from different column or it is closed.
    if (this.NO_MENU_COLUMNS.indexOf(this.column[0]) < 0) {
      colOptions.hide(function() {
        colOptions.parent_ && colOptions.parent_.css('z-index', 0);
        var parent_ = self.$el.find('th > div');
        colOptions.parent_ = parent_;
        parent_.css('z-index', '100');
        self._openColOptions(e);
      });
    }

    return false;
  },

  showGeoreferenceWindow: function(e) {
    this.killEvent(e);
    this.trigger('georeference', null);
  },

  showColumnTypeOptions: function(e) {
    var self = this;
    var colOptions = HeaderView.colTypeOptions;
    var columnName = this.column[0];

    if (e) e.preventDefault();

    // If submenu was openened before, let's close it.
    if (colOptions.isOpen && columnName == colOptions.column) {
      colOptions.hide();
      return false;
    }

    // If submenu is from different column or it is closed.
    colOptions.hide(function() {
      self._openColTypeOptions(e);
    });

    return false;
  }

});

})();
<commit_msg>Set a reasonable fallback width<commit_after>
/**
 * header cell view, manages operations on table columns
 */

(function() {

var HeaderView = cdb.admin.HeaderView = cdb.core.View.extend({

  _TEXTS: {
    no_geo: {
      title:        _t('Georeference your table'),
      description:  _t('This funcionality is not available in the visualization view. \
                    Please, visit <a href="<%- prefix %>/tables/<%- table_name %>">your table and start georeferencing there.'),
      ok:           _t('Ok, close')
    }
  },

  NO_MENU_COLUMNS: ['the_geom', 'the_geom_webmercator'],

  events: {
    'dblclick .coloptions':     'renameColumn',
    'click    .coloptions':     'showColumnOptions',
    'click    .coltype':        'showColumnTypeOptions',
    'click    .geo':            'showGeoreferenceWindow',
    'keydown  .col_name_edit':  '_checkEditColnameInput',
    'focusout input':           '_finishEdit',
    'click':                    'activateColumnOptions'
  },

  initialize: function() {
    var self = this;
    this.column = this.options.column;
    this.table = this.options.table;
    this.vis = this.options.vis;
    this.template = this.getTemplate('table/views/table_header_view');
    this.editing_name = false;
    this.changing_type = false;

    this.vis.bind('change:type', function() {
      // You can't geocode being in a visualization of type derived
      HeaderView && HeaderView.colTypeOptions.render();
    });

    this.add_related_model(this.vis);

    if (HeaderView.colOptions === undefined) {
      HeaderView.colOptions= new cdb.admin.HeaderDropdown({
        user: this.options.user,
        position: 'position',
        horizontal_position: "right",
        tick: "right",
        template_base: "table/views/table_header_options",
        sqlView: this.options.sqlView,
        vis: this.vis
      });
      HeaderView.colOptions.render();

      cdb.god.bind("closeDialogs", HeaderView.colOptions.hide, HeaderView.colOptions);
    }

    if (HeaderView.colTypeOptions === undefined) {
      HeaderView.colTypeOptions= new cdb.admin.ColumntypeDropdown({
        user: this.options.user,
        position: 'position',
        horizontal_position: "right",
        tick: "right",
        template_base: "table/views/table_column_type_options"
      });
      HeaderView.colTypeOptions.render();
      cdb.god.bind("closeDialogs", HeaderView.colTypeOptions.hide, HeaderView.colTypeOptions);
    }
  },

  _addColumn: function(column) {
    table.tableTab.tableView.addColumn(column);
  },

  render: function() {
    this.$el.html('');

    this.$el.append(this.template({
      col_name:         this.column[0],
      col_type:         this.column[1],
      editing_name:     this.editing_name,
      changing_type:    this.changing_type,
      read_only:        this.table.isReadOnly(),
      isReservedColumn: this.table.isReadOnly() || this.table.isReservedColumn(this.column[0]),
      noMenu:           (this.NO_MENU_COLUMNS.indexOf(this.column[0]) >= 0)
    }));

    // Focus in the input if it is being edited
    // and set the correct width
    if (this.editing_name) {
      // In case the element is not present in DOM or not visible the width would be 0, so fallback on a reasonable
      // width (e.g. happens for adding a column on an empty dataset)
      var w = this.$el.find("p.auto").width() || 175;
      this.$el.find("input")
        .css({
          "max-width":  w,
          "width":      w
        })
        .focus();
    }

    this.delegateEvents();

    return this;
  },

  _openColOptions: function(e) {
    var self = this;
    var colOptions = HeaderView.colOptions;

    // Unbind events
    colOptions.off();
    cdb.god.unbind('closeDialogs', HeaderView.colOptions.hide, HeaderView.colOptions);

    // Close other dialogs
    cdb.god.trigger("closeDialogs");

    // set data for column and table currently editing
    colOptions.setTable(this.table, this.column[0]);

    colOptions.bind('addColumn', this._addColumn, this);
    colOptions.bind('renameColumn', this.renameColumn, this);
    colOptions.bind('changeType', this._changeType, this);
    colOptions.bind('clearView', function(){
      self.trigger('clearView');
    }, this);
    colOptions.bind('georeference', function(column) {
      self.trigger('georeference', column);
    }, this);
    colOptions.bind('applyFilter', function(column) {
      self.trigger('applyFilter', column);
    }, this);

    // bind the stuff
    var container = $(e.target).parent().parent();
    container.append(colOptions.el);

    var link_width  = $(e.target).width() + 26
      , th          = container.parent();

    // align to the right of the target with a little of margin
    colOptions.openAt(link_width - colOptions.$el.width(), (th.height()/2) + 7);

    // Bind again!
    cdb.god.bind("closeDialogs", HeaderView.colOptions.hide, HeaderView.colOptions);
  },

  _openColTypeOptions: function(e) {
    if(this.table.isReadOnly()) {
      return;
    }
    var colOptions = HeaderView.colTypeOptions;

    // Unbind events
    colOptions.off();
    cdb.god.unbind('closeDialogs', HeaderView.colTypeOptions.hide, HeaderView.colTypeOptions);

    // Close other dialogs
    cdb.god.trigger("closeDialogs");

    // set data for column and table currently editing
    colOptions.setTable(this.table, this.column[0]);

    // bind the stuff
    var container = $(e.target).parent().parent();
    container.append(colOptions.el);

    var link_width  = $(e.target).outerWidth() + 24
      , th          = container.parent();

    // align to the right of the target with a little of margin
    colOptions.openAt(link_width - colOptions.$el.width(), (th.height()/2) + 25);

    // Bind again
    cdb.god.bind("closeDialogs", HeaderView.colTypeOptions.hide, HeaderView.colTypeOptions);
  },

  _checkEditColnameInput: function(e) {
    if(e.keyCode === 13) {
      this._submitEdit();
    }
    if(e.keyCode === 27) {
      this._finishEdit();
    }

  },

  _submitEdit: function() {
    this.table.renameColumn(this.column[0], $('.col_name_edit').val());
    this._finishEdit();
  },

  _finishEdit: function() {
    this.editing_name = false;
    this.render();
  },

  renameColumn: function(ev) {
    if (ev) {
      this.killEvent(ev)
    }

    this.editing_name = true;
    this.changing_type = false;
    this.render();
  },

  _changeType: function(column) {
    this.editing_name = false;
    this.changing_type = true;

    // Simulate click
    var $coltype_link = this.$el.find('a.coltype');
    $coltype_link.click();
  },

  activateColumnOptions: function(e) {
    this.killEvent(e);
    this.$el.find("a.coloptions").click();
  },

  showColumnOptions: function(e) {
    var self = this;
    var colOptions = HeaderView.colOptions;
    var columnName = this.column[0];

    e.preventDefault();

    // If submenu was openened before, let's close it.
    if (colOptions.isOpen && columnName == colOptions.column) {
      colOptions.hide();
      return false;
    }

    // If submenu is from different column or it is closed.
    if (this.NO_MENU_COLUMNS.indexOf(this.column[0]) < 0) {
      colOptions.hide(function() {
        colOptions.parent_ && colOptions.parent_.css('z-index', 0);
        var parent_ = self.$el.find('th > div');
        colOptions.parent_ = parent_;
        parent_.css('z-index', '100');
        self._openColOptions(e);
      });
    }

    return false;
  },

  showGeoreferenceWindow: function(e) {
    this.killEvent(e);
    this.trigger('georeference', null);
  },

  showColumnTypeOptions: function(e) {
    var self = this;
    var colOptions = HeaderView.colTypeOptions;
    var columnName = this.column[0];

    if (e) e.preventDefault();

    // If submenu was openened before, let's close it.
    if (colOptions.isOpen && columnName == colOptions.column) {
      colOptions.hide();
      return false;
    }

    // If submenu is from different column or it is closed.
    colOptions.hide(function() {
      self._openColTypeOptions(e);
    });

    return false;
  }

});

})();
<|endoftext|>


<commit_before>'use strict';
var NATIVE_ARRAY_BUFFER = require('../internals/array-buffer-native');
var DESCRIPTORS = require('../internals/descriptors');
var global = require('../internals/global');
var isCallable = require('../internals/is-callable');
var isObject = require('../internals/is-object');
var hasOwn = require('../internals/has-own-property');
var classof = require('../internals/classof');
var tryToString = require('../internals/try-to-string');
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
var defineBuiltIn = require('../internals/define-built-in');
var defineProperty = require('../internals/object-define-property').f;
var isPrototypeOf = require('../internals/object-is-prototype-of');
var getPrototypeOf = require('../internals/object-get-prototype-of');
var setPrototypeOf = require('../internals/object-set-prototype-of');
var wellKnownSymbol = require('../internals/well-known-symbol');
var uid = require('../internals/uid');
var InternalStateModule = require('../internals/internal-state');

var enforceInternalState = InternalStateModule.enforce;
var getInternalState = InternalStateModule.get;
var Int8Array = global.Int8Array;
var Int8ArrayPrototype = Int8Array && Int8Array.prototype;
var Uint8ClampedArray = global.Uint8ClampedArray;
var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;
var TypedArray = Int8Array && getPrototypeOf(Int8Array);
var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);
var ObjectPrototype = Object.prototype;
var TypeError = global.TypeError;

var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG');
var TYPED_ARRAY_CONSTRUCTOR = 'TypedArrayConstructor';
// Fixing native typed arrays in Opera Presto crashes the browser, see #595
var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera';
var TYPED_ARRAY_TAG_REQUIRED = false;
var NAME, Constructor, Prototype;

var TypedArrayConstructorsList = {
  Int8Array: 1,
  Uint8Array: 1,
  Uint8ClampedArray: 1,
  Int16Array: 2,
  Uint16Array: 2,
  Int32Array: 4,
  Uint32Array: 4,
  Float32Array: 4,
  Float64Array: 8
};

var BigIntArrayConstructorsList = {
  BigInt64Array: 8,
  BigUint64Array: 8
};

var isView = function isView(it) {
  if (!isObject(it)) return false;
  var klass = classof(it);
  return klass === 'DataView'
    || hasOwn(TypedArrayConstructorsList, klass)
    || hasOwn(BigIntArrayConstructorsList, klass);
};

var getTypedArrayConstructor = function (it) {
  var proto = getPrototypeOf(it);
  if (!isObject(proto)) return;
  var state = getInternalState(proto);
  if (state && hasOwn(state, TYPED_ARRAY_CONSTRUCTOR)) return state[TYPED_ARRAY_CONSTRUCTOR];
  return getTypedArrayConstructor(proto);
};

var isTypedArray = function (it) {
  if (!isObject(it)) return false;
  var klass = classof(it);
  return hasOwn(TypedArrayConstructorsList, klass)
    || hasOwn(BigIntArrayConstructorsList, klass);
};

var aTypedArray = function (it) {
  if (isTypedArray(it)) return it;
  throw TypeError('Target is not a typed array');
};

var aTypedArrayConstructor = function (C) {
  if (isCallable(C) && (!setPrototypeOf || isPrototypeOf(TypedArray, C))) return C;
  throw TypeError(tryToString(C) + ' is not a typed array constructor');
};

var exportTypedArrayMethod = function (KEY, property, forced, options) {
  if (!DESCRIPTORS) return;
  if (forced) for (var ARRAY in TypedArrayConstructorsList) {
    var TypedArrayConstructor = global[ARRAY];
    if (TypedArrayConstructor && hasOwn(TypedArrayConstructor.prototype, KEY)) try {
      delete TypedArrayConstructor.prototype[KEY];
    } catch (error) {
      // old WebKit bug - some methods are non-configurable
      try {
        TypedArrayConstructor.prototype[KEY] = property;
      } catch (error2) { /* empty */ }
    }
  }
  if (!TypedArrayPrototype[KEY] || forced) {
    defineBuiltIn(TypedArrayPrototype, KEY, forced ? property
      : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property, options);
  }
};

var exportTypedArrayStaticMethod = function (KEY, property, forced) {
  var ARRAY, TypedArrayConstructor;
  if (!DESCRIPTORS) return;
  if (setPrototypeOf) {
    if (forced) for (ARRAY in TypedArrayConstructorsList) {
      TypedArrayConstructor = global[ARRAY];
      if (TypedArrayConstructor && hasOwn(TypedArrayConstructor, KEY)) try {
        delete TypedArrayConstructor[KEY];
      } catch (error) { /* empty */ }
    }
    if (!TypedArray[KEY] || forced) {
      // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable
      try {
        return defineBuiltIn(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && TypedArray[KEY] || property);
      } catch (error) { /* empty */ }
    } else return;
  }
  for (ARRAY in TypedArrayConstructorsList) {
    TypedArrayConstructor = global[ARRAY];
    if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {
      defineBuiltIn(TypedArrayConstructor, KEY, property);
    }
  }
};

for (NAME in TypedArrayConstructorsList) {
  Constructor = global[NAME];
  Prototype = Constructor && Constructor.prototype;
  if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;
  else NATIVE_ARRAY_BUFFER_VIEWS = false;
}

for (NAME in BigIntArrayConstructorsList) {
  Constructor = global[NAME];
  Prototype = Constructor && Constructor.prototype;
  if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;
}

// WebKit bug - typed arrays constructors prototype is Object.prototype
if (!NATIVE_ARRAY_BUFFER_VIEWS || !isCallable(TypedArray) || TypedArray === Function.prototype) {
  // eslint-disable-next-line no-shadow -- safe
  TypedArray = function TypedArray() {
    throw TypeError('Incorrect invocation');
  };
  if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
    if (global[NAME]) setPrototypeOf(global[NAME], TypedArray);
  }
}

if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {
  TypedArrayPrototype = TypedArray.prototype;
  if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
    if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype);
  }
}

// WebKit bug - one more object in Uint8ClampedArray prototype chain
if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {
  setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);
}

if (DESCRIPTORS && !hasOwn(TypedArrayPrototype, TO_STRING_TAG)) {
  TYPED_ARRAY_TAG_REQUIRED = true;
  defineProperty(TypedArrayPrototype, TO_STRING_TAG, { get: function () {
    return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;
  } });
  for (NAME in TypedArrayConstructorsList) if (global[NAME]) {
    createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME);
  }
}

module.exports = {
  NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,
  TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQUIRED && TYPED_ARRAY_TAG,
  aTypedArray: aTypedArray,
  aTypedArrayConstructor: aTypedArrayConstructor,
  exportTypedArrayMethod: exportTypedArrayMethod,
  exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,
  getTypedArrayConstructor: getTypedArrayConstructor,
  isView: isView,
  isTypedArray: isTypedArray,
  TypedArray: TypedArray,
  TypedArrayPrototype: TypedArrayPrototype
};
<commit_msg>some stylistic changes<commit_after>'use strict';
var NATIVE_ARRAY_BUFFER = require('../internals/array-buffer-native');
var DESCRIPTORS = require('../internals/descriptors');
var global = require('../internals/global');
var isCallable = require('../internals/is-callable');
var isObject = require('../internals/is-object');
var hasOwn = require('../internals/has-own-property');
var classof = require('../internals/classof');
var tryToString = require('../internals/try-to-string');
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
var defineBuiltIn = require('../internals/define-built-in');
var defineProperty = require('../internals/object-define-property').f;
var isPrototypeOf = require('../internals/object-is-prototype-of');
var getPrototypeOf = require('../internals/object-get-prototype-of');
var setPrototypeOf = require('../internals/object-set-prototype-of');
var wellKnownSymbol = require('../internals/well-known-symbol');
var uid = require('../internals/uid');
var InternalStateModule = require('../internals/internal-state');

var enforceInternalState = InternalStateModule.enforce;
var getInternalState = InternalStateModule.get;
var Int8Array = global.Int8Array;
var Int8ArrayPrototype = Int8Array && Int8Array.prototype;
var Uint8ClampedArray = global.Uint8ClampedArray;
var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;
var TypedArray = Int8Array && getPrototypeOf(Int8Array);
var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);
var ObjectPrototype = Object.prototype;
var TypeError = global.TypeError;

var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG');
var TYPED_ARRAY_CONSTRUCTOR = 'TypedArrayConstructor';
// Fixing native typed arrays in Opera Presto crashes the browser, see #595
var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera';
var TYPED_ARRAY_TAG_REQUIRED = false;
var NAME, Constructor, Prototype;

var TypedArrayConstructorsList = {
  Int8Array: 1,
  Uint8Array: 1,
  Uint8ClampedArray: 1,
  Int16Array: 2,
  Uint16Array: 2,
  Int32Array: 4,
  Uint32Array: 4,
  Float32Array: 4,
  Float64Array: 8
};

var BigIntArrayConstructorsList = {
  BigInt64Array: 8,
  BigUint64Array: 8
};

var isView = function isView(it) {
  if (!isObject(it)) return false;
  var klass = classof(it);
  return klass === 'DataView'
    || hasOwn(TypedArrayConstructorsList, klass)
    || hasOwn(BigIntArrayConstructorsList, klass);
};

var getTypedArrayConstructor = function (it) {
  var proto = getPrototypeOf(it);
  if (!isObject(proto)) return;
  var state = getInternalState(proto);
  return (state && hasOwn(state, TYPED_ARRAY_CONSTRUCTOR)) ? state[TYPED_ARRAY_CONSTRUCTOR] : getTypedArrayConstructor(proto);
};

var isTypedArray = function (it) {
  if (!isObject(it)) return false;
  var klass = classof(it);
  return hasOwn(TypedArrayConstructorsList, klass)
    || hasOwn(BigIntArrayConstructorsList, klass);
};

var aTypedArray = function (it) {
  if (isTypedArray(it)) return it;
  throw TypeError('Target is not a typed array');
};

var aTypedArrayConstructor = function (C) {
  if (isCallable(C) && (!setPrototypeOf || isPrototypeOf(TypedArray, C))) return C;
  throw TypeError(tryToString(C) + ' is not a typed array constructor');
};

var exportTypedArrayMethod = function (KEY, property, forced, options) {
  if (!DESCRIPTORS) return;
  if (forced) for (var ARRAY in TypedArrayConstructorsList) {
    var TypedArrayConstructor = global[ARRAY];
    if (TypedArrayConstructor && hasOwn(TypedArrayConstructor.prototype, KEY)) try {
      delete TypedArrayConstructor.prototype[KEY];
    } catch (error) {
      // old WebKit bug - some methods are non-configurable
      try {
        TypedArrayConstructor.prototype[KEY] = property;
      } catch (error2) { /* empty */ }
    }
  }
  if (!TypedArrayPrototype[KEY] || forced) {
    defineBuiltIn(TypedArrayPrototype, KEY, forced ? property
      : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property, options);
  }
};

var exportTypedArrayStaticMethod = function (KEY, property, forced) {
  var ARRAY, TypedArrayConstructor;
  if (!DESCRIPTORS) return;
  if (setPrototypeOf) {
    if (forced) for (ARRAY in TypedArrayConstructorsList) {
      TypedArrayConstructor = global[ARRAY];
      if (TypedArrayConstructor && hasOwn(TypedArrayConstructor, KEY)) try {
        delete TypedArrayConstructor[KEY];
      } catch (error) { /* empty */ }
    }
    if (!TypedArray[KEY] || forced) {
      // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable
      try {
        return defineBuiltIn(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && TypedArray[KEY] || property);
      } catch (error) { /* empty */ }
    } else return;
  }
  for (ARRAY in TypedArrayConstructorsList) {
    TypedArrayConstructor = global[ARRAY];
    if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {
      defineBuiltIn(TypedArrayConstructor, KEY, property);
    }
  }
};

for (NAME in TypedArrayConstructorsList) {
  Constructor = global[NAME];
  Prototype = Constructor && Constructor.prototype;
  if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;
  else NATIVE_ARRAY_BUFFER_VIEWS = false;
}

for (NAME in BigIntArrayConstructorsList) {
  Constructor = global[NAME];
  Prototype = Constructor && Constructor.prototype;
  if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;
}

// WebKit bug - typed arrays constructors prototype is Object.prototype
if (!NATIVE_ARRAY_BUFFER_VIEWS || !isCallable(TypedArray) || TypedArray === Function.prototype) {
  // eslint-disable-next-line no-shadow -- safe
  TypedArray = function TypedArray() {
    throw TypeError('Incorrect invocation');
  };
  if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
    if (global[NAME]) setPrototypeOf(global[NAME], TypedArray);
  }
}

if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {
  TypedArrayPrototype = TypedArray.prototype;
  if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
    if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype);
  }
}

// WebKit bug - one more object in Uint8ClampedArray prototype chain
if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {
  setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);
}

if (DESCRIPTORS && !hasOwn(TypedArrayPrototype, TO_STRING_TAG)) {
  TYPED_ARRAY_TAG_REQUIRED = true;
  defineProperty(TypedArrayPrototype, TO_STRING_TAG, { get: function () {
    return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;
  } });
  for (NAME in TypedArrayConstructorsList) if (global[NAME]) {
    createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME);
  }
}

module.exports = {
  NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,
  TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQUIRED && TYPED_ARRAY_TAG,
  aTypedArray: aTypedArray,
  aTypedArrayConstructor: aTypedArrayConstructor,
  exportTypedArrayMethod: exportTypedArrayMethod,
  exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,
  getTypedArrayConstructor: getTypedArrayConstructor,
  isView: isView,
  isTypedArray: isTypedArray,
  TypedArray: TypedArray,
  TypedArrayPrototype: TypedArrayPrototype
};
<|endoftext|>


<commit_before>// transpile|t <xodball>            Transpile code
// -t --target [espruino|arduino]   Transpile code for target device (espruino by default).
// -o --output [filename.txt]       Output result into file (or stdout by default).

/* eslint-disable no-console */

import path from 'path';
import { writeJSON, readJSON } from 'xod-fs';
import { transpile, runtime } from 'xod-espruino';
import { Spinner } from 'clui';
import * as msg from './messages';

export default (xodball, program) => {
  const target = program.target;
  const output = program.output;
  const filename = path.basename(xodball);

  msg.notice(`Transpiling ${filename} for ${msg.bold(target)}`);

  const spinner = new Spinner('Transpiling code...');

  spinner.start();

  readJSON(xodball)
    .then(project => transpile({ project, runtime }))
    .then(code => {
      spinner.stop();
      if (output) {
        return writeJSON(output, code)
          .then(() => {
            msg.success(`Result has been wrote into ${output} file.`);
          })
          .catch(err => {
            msg.error(`Error: Can't write result into ${output} file.`);
            msg.notice(err);
          });
      }

      process.stdout.write(code);
      process.exit(1);
      return Promise.resolve(code);
    })
    .catch(err => {
      spinner.stop();
      msg.error('Error: Can\'t transpile code!');
      msg.notice(err);
    });
};
<commit_msg>fix(xod-cli): remove excessive promise.resolve<commit_after>// transpile|t <xodball>            Transpile code
// -t --target [espruino|arduino]   Transpile code for target device (espruino by default).
// -o --output [filename.txt]       Output result into file (or stdout by default).

/* eslint-disable no-console */

import path from 'path';
import { writeJSON, readJSON } from 'xod-fs';
import { transpile, runtime } from 'xod-espruino';
import { Spinner } from 'clui';
import * as msg from './messages';

export default (xodball, program) => {
  const target = program.target;
  const output = program.output;
  const filename = path.basename(xodball);

  msg.notice(`Transpiling ${filename} for ${msg.bold(target)}`);

  const spinner = new Spinner('Transpiling code...');

  spinner.start();

  readJSON(xodball)
    .then(project => transpile({ project, runtime }))
    .then(code => {
      spinner.stop();
      if (output) {
        return writeJSON(output, code)
          .then(() => {
            msg.success(`Result has been wrote into ${output} file.`);
          })
          .catch(err => {
            msg.error(`Error: Can't write result into ${output} file.`);
            msg.notice(err);
          });
      }

      process.stdout.write(code);
      process.exit(1);
      return code;
    })
    .catch(err => {
      spinner.stop();
      msg.error('Error: Can\'t transpile code!');
      msg.notice(err);
    });
};
<|endoftext|>


<commit_before>/*jslint node: true */
/*jshint esversion: 6 */
'use strict';
//require('babel-register');
const express = require('express');
const path = require('path');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express();
const swig = require('swig');

app.set('port', process.env.PORT || 7777);
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '../build')));

app.get('/', (req, res) => {
  const page = swig.renderFile('index.html');
  res.status(200).send(page);
});

app.listen(app.get('port'), ()=> {
  console.log('Express server listening on port ' + app.get('port'));
});
//各种请求处理
const auth = require('./auth');
const user = require('./user');
const project = require('./project');
const task = require('./task');
app.post('/register', bodyValidate(['name','email','passwd']), auth.register);
app.post('/login', bodyValidate(['name','passwd']), auth.login);
//各种check处理
app.get('/user/check', queryValidate(['name']), user.userCheck);
app.get('/email/check', queryValidate(['email']), user.emailCheck);
app.get('/project/check', queryValidate(['name']), project.check);
//进行token验证
app.use(auth.checkToken);
//以下都是必须要带token的请求
app.get('/token/check', auth.check);
app.get('/user/get', user.get);
app.post('/user/update', user.update);
app.get('/user/list', user.list);
app.post('/project/add', bodyValidate(['name','start','end','intro', 'members']), project.add);
app.get('/project/list', project.list);
app.get('/project/member/list', queryValidate(['id']), project.memberList);
app.post('/task/add', bodyValidate(['project_id','start','end','charge','intro']), task.add);
app.post('/task/list', bodyValidate(['status']), task.list);
app.get('/init/tasks', task.init);
app.post('/task/update', bodyValidate(['id']), task.update);
app.get('/project/one', queryValidate(['id']), project.one);
app.post('/project/update', bodyValidate(['id']), project.update);

function queryValidate(params){
  return paramsVaildate('get', params);
}
function bodyValidate(params){
  return paramsVaildate('post', params);
}
function paramsVaildate(method, params){
  return (req, res, next) => {
    const json = method === 'post' ? req.body : req.query;
    const arr = params.filter(param => !json.hasOwnProperty(param));
    arr.length > 0 ? res.json({errcode: 40002, errmsg: '不合法参数，请重新提交!'}) : next();
  }
}
<commit_msg>调整端口为3000<commit_after>/*jslint node: true */
/*jshint esversion: 6 */
'use strict';
//require('babel-register');
const express = require('express');
const path = require('path');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express();
const swig = require('swig');

app.set('port', process.env.PORT || 3000);
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '../build')));

app.get('/', (req, res) => {
  const page = swig.renderFile('index.html');
  res.status(200).send(page);
});

app.listen(app.get('port'), ()=> {
  console.log('Express server listening on port ' + app.get('port'));
});
//各种请求处理
const auth = require('./auth');
const user = require('./user');
const project = require('./project');
const task = require('./task');
app.post('/register', bodyValidate(['name','email','passwd']), auth.register);
app.post('/login', bodyValidate(['name','passwd']), auth.login);
//各种check处理
app.get('/user/check', queryValidate(['name']), user.userCheck);
app.get('/email/check', queryValidate(['email']), user.emailCheck);
app.get('/project/check', queryValidate(['name']), project.check);
//进行token验证
app.use(auth.checkToken);
//以下都是必须要带token的请求
app.get('/token/check', auth.check);
app.get('/user/get', user.get);
app.post('/user/update', user.update);
app.get('/user/list', user.list);
app.post('/project/add', bodyValidate(['name','start','end','intro', 'members']), project.add);
app.get('/project/list', project.list);
app.get('/project/member/list', queryValidate(['id']), project.memberList);
app.post('/task/add', bodyValidate(['project_id','start','end','charge','intro']), task.add);
app.post('/task/list', bodyValidate(['status']), task.list);
app.get('/init/tasks', task.init);
app.post('/task/update', bodyValidate(['id']), task.update);
app.get('/project/one', queryValidate(['id']), project.one);
app.post('/project/update', bodyValidate(['id']), project.update);

function queryValidate(params){
  return paramsVaildate('get', params);
}
function bodyValidate(params){
  return paramsVaildate('post', params);
}
function paramsVaildate(method, params){
  return (req, res, next) => {
    const json = method === 'post' ? req.body : req.query;
    const arr = params.filter(param => !json.hasOwnProperty(param));
    arr.length > 0 ? res.json({errcode: 40002, errmsg: '不合法参数，请重新提交!'}) : next();
  }
}
<|endoftext|>


<commit_before>import { toArray } from './util'

export function $ (selector, el = document) {
  return el.querySelector(selector)
}

export function $$ (selector, el = document) {
  return toArray(el.querySelectorAll(selector))
}

export function id (name, el = document) {
  return el.getElementById(name)
}

export function replace (oldElement, newElement) {
  oldElement.parentNode.replaceChild(newElement, oldElement)
  return newElement
}

export function index (el) {
  let idx = 0
  while (el) {
    idx++
    el = el.previousElementSibling
  }
  return idx
}

export function remove (el) {
  el.parentNode && el.parentNode.removeChild(el)
  return el
}

export function rect (el) {
  const rect = el.getBoundingClientRect()

  return {
    top: window.pageYOffset + rect.top,
    left: window.pageXOffset + rect.left,
    width: rect.width,
    height: rect.height
  }
}

export function className (name) {
  return {
    add: (el, ...args) => {
      addClass(el, ...args.concat(name))
      return this
    },
    remove: (el, ...args) => {
      removeClass(el, ...args.concat(name))
      return this
    },
    toggle: (el, force = undefined) => {
      toggleClass(el, name, force)
      return this
    },
    selector: () => `.${name}`,
    toString: () => name
  }
}

export function addClass (el, ...args) {
  el.classList.add(...args)
  return el
}

export function toggleClass (el, className, force = undefined) {
  el.classList.toggle(className, force)
  return el
}

export function removeClass (el, ...args) {
  el.classList.remove(...args)
  return el
}

export function attr (name) {
  return {
    get: (el, ...args) => {
      getAttr(el, name, ...args)
      return this
    },
    set: (el, ...args) => {
      setAttr(el, name, ...args)
      return this
    },
    has: el => hasAttr(el, name),
    selector: (value = undefined) => `[${name}${value ? `="${value}"` : ''}]`,
    toString: () => name
  }
}

export function getAttr (el, name, defaultValue = undefined) {
  return el && el.hasAttribute(name) ? el.getAttribute(name) : defaultValue
}

export function setAttr (el, name, value, append = false) {
  const attrValue = append ? getAttr(el, name, '') + ' ' + value : value
  el.setAttribute(name, attrValue)
  return el
}

export function hasAttr (el, name) {
  return el && el.hasAttribute(name)
}

export function insertElement (position, node, newNode) {
  switch (position) {
    case 'beforebegin':
      node.parentNode.insertBefore(newNode, node)
      break
    case 'afterend':
      node.parentNode.insertBefore(newNode, node.nextElementSibling)
      break
  }

  return newNode
}

insertElement.before = (node, newNode) => insertElement('beforebegin', node, newNode)
insertElement.after = (node, newNode) => insertElement('afterend', node, newNode)

export default {
  $,
  $$,
  id,
  replace,
  index,
  remove,
  rect,
  className,
  addClass,
  toggleClass,
  removeClass,
  attr,
  getAttr,
  setAttr,
  hasAttr,
  insertElement
}
<commit_msg>actually return attribute when using get<commit_after>import { toArray } from './util'

export function $ (selector, el = document) {
  return el.querySelector(selector)
}

export function $$ (selector, el = document) {
  return toArray(el.querySelectorAll(selector))
}

export function id (name, el = document) {
  return el.getElementById(name)
}

export function replace (oldElement, newElement) {
  oldElement.parentNode.replaceChild(newElement, oldElement)
  return newElement
}

export function index (el) {
  let idx = 0
  while (el) {
    idx++
    el = el.previousElementSibling
  }
  return idx
}

export function remove (el) {
  el.parentNode && el.parentNode.removeChild(el)
  return el
}

export function rect (el) {
  const rect = el.getBoundingClientRect()

  return {
    top: window.pageYOffset + rect.top,
    left: window.pageXOffset + rect.left,
    width: rect.width,
    height: rect.height
  }
}

export function className (name) {
  return {
    add: (el, ...args) => {
      addClass(el, ...args.concat(name))
      return this
    },
    remove: (el, ...args) => {
      removeClass(el, ...args.concat(name))
      return this
    },
    toggle: (el, force = undefined) => {
      toggleClass(el, name, force)
      return this
    },
    selector: () => `.${name}`,
    toString: () => name
  }
}

export function addClass (el, ...args) {
  el.classList.add(...args)
  return el
}

export function toggleClass (el, className, force = undefined) {
  el.classList.toggle(className, force)
  return el
}

export function removeClass (el, ...args) {
  el.classList.remove(...args)
  return el
}

export function attr (name) {
  return {
    get: (el, ...args) => getAttr(el, name, ...args),
    set: (el, ...args) => {
      setAttr(el, name, ...args)
      return this
    },
    has: el => hasAttr(el, name),
    selector: (value = undefined) => `[${name}${value ? `="${value}"` : ''}]`,
    toString: () => name
  }
}

export function getAttr (el, name, defaultValue = undefined) {
  return el && el.hasAttribute(name) ? el.getAttribute(name) : defaultValue
}

export function setAttr (el, name, value, append = false) {
  const attrValue = append ? getAttr(el, name, '') + ' ' + value : value
  el.setAttribute(name, attrValue)
  return el
}

export function hasAttr (el, name) {
  return el && el.hasAttribute(name)
}

export function insertElement (position, node, newNode) {
  switch (position) {
    case 'beforebegin':
      node.parentNode.insertBefore(newNode, node)
      break
    case 'afterend':
      node.parentNode.insertBefore(newNode, node.nextElementSibling)
      break
  }

  return newNode
}

insertElement.before = (node, newNode) => insertElement('beforebegin', node, newNode)
insertElement.after = (node, newNode) => insertElement('afterend', node, newNode)

export default {
  $,
  $$,
  id,
  replace,
  index,
  remove,
  rect,
  className,
  addClass,
  toggleClass,
  removeClass,
  attr,
  getAttr,
  setAttr,
  hasAttr,
  insertElement
}
<|endoftext|>


<commit_before>'use strict';

const pconfig = require('./project-config');

const config = {

  /*The baseUrl is the URL that webdriver will visit*/
  baseUrl: 'http://localhost:' + pconfig.project.srvPort,

  /* connect to the webdriver instead of connecting to a local Selenium server */
  directConnect: true,

  // Framework to use. Jasmine is recommended.
  framework: 'jasmine',

  // Spec patterns are relative to this config file
  specs: [pconfig.paths.destinations.e2e + '**/*.e2e-spec.js'],

  /* useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page */
  useAllAngular2AppRoots: true,

  /*
  * Options to be passed to jasmine.
  *
  * See https://github.com/jasmine/jasmine-npm/blob/master/lib/jasmine.js
  * for the exact options available.
  */
  jasmineNodeOpts: {
    showTiming: true,
    showColors: true,
    isVerbose: false,
    includeStackTrace: false,
  },

};

/* Capabilities to be passed to the webdriver instance.*/
if (process.env.TRAVIS) {
  config.capabilities = {
    browserName: 'chrome',
    chromeOptions: {
      'args': ['--no-sandbox'],
      'binary': process.env.CHROME_BIN,
    }
  };
} else {
  config.capabilities = {
    browserName: 'chrome'
  };
}

exports.config = config;<commit_msg>BUG(travis+protractor) fix 3<commit_after>'use strict';

const pconfig = require('./project-config');

const config = {

  /*The baseUrl is the URL that webdriver will visit*/
  baseUrl: 'http://localhost:' + pconfig.project.srvPort,

  /* connect to the webdriver instead of connecting to a local Selenium server */
  directConnect: true,

  // Framework to use. Jasmine is recommended.
  framework: 'jasmine',

  // Spec patterns are relative to this config file
  specs: [pconfig.paths.destinations.e2e + '**/*.e2e-spec.js'],

  /* useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page */
  useAllAngular2AppRoots: true,

  /*
  * Options to be passed to jasmine.
  *
  * See https://github.com/jasmine/jasmine-npm/blob/master/lib/jasmine.js
  * for the exact options available.
  */
  jasmineNodeOpts: {
    showTiming: true,
    showColors: true,
    isVerbose: false,
    includeStackTrace: false,
  },

};

/* Capabilities to be passed to the webdriver instance.*/
if (process.env.TRAVIS) {
  config.capabilities = {
    browserName: 'chrome',
    chromeOptions: {
      'args': ['--no-sandbox'],
//      'binary': process.env.CHROME_BIN_PROTRACTOR,
    }
  };
} else {
  config.capabilities = {
    browserName: 'chrome'
  };
}

exports.config = config;<|endoftext|>