<commit_before>var http = require('http'),
    url = require('url'),
    fs = require('fs'),
    ejs = require('ejs'),
    path = require('path'),
    exec = require('child_process').exec,
    util = require('util'),
    zlib = require('zlib');
//var querystring = require('querystring');

var mime_types = {}
var routes = []
//--------------------------------------------------
var Route = function(){

    this.get = new Handler();
    this.post = new Handler();
    return this;
}
//--------------------------------------------------
var Handler = function(){
    return this;
}
//--------------------------------------------------
Handler.prototype.html = function(template_path){
    //load template
    var t = this;
    fs.readFile(template_path, function (err, data) {
          if (err) throw err;
          t.compiled = ejs.compile(String(data));
    });
    return this;
}
//===================================================
Handler.prototype.static = function(base_dir){

    //----------------------------------------------------
    var send_stream = function(fs_path,req,res,headers) {

        fs.stat(fs_path,function(err,stats){

            if(err){
                res.writeHead(404);
                res.end("404 - not found.");
                return;

            }
            var ins = util.inspect(stats);
            var size = ins.match(/size:\s*(\d+)/)[1];
            headers['Content-Length'] = size;

           var flags = {};
           //console.log(req.headers);
           range = req.headers['range'];

           if(range){
                var match = range.match(/^bytes\s*=\s*(\d+)-(\d*)/);
                if(match){
                    var start = parseInt(match[1]);
                    var end = match[2].length > 0 ? parseInt(match[2]) : parseInt(size) -1;
                    headers["Content-Range"] =  'bytes %start-%end/%length'.replace("%start",start).replace("%end",end).replace("%length",size);
                    res.writeHead(206,headers);
                    flags["start"] = start;
                    flags["end"] = end;
                }
                else{
                    res.writeHead(416,headers);
                }
            }
            else
                res.writeHead(200,headers);
            /*fs.readFile(fs_path, function (err, data) {
              if (err)
                throw err;

                res.end(data);
            });*/
            var fstream = fs.createReadStream(fs_path,flags);
            fstream.pipe(res);

        });

        /*}
            kv = range.split("=");
            if(!kv[1])
        }*/
    }
    //----------------------------------------------------
    var send_ogg= function(path,req,res,headers,flags){

       var child = exec("ogginfo %s | grep 'Playback length'".replace("%s",path),
                  function (error, stdout, stderr) {
                      if(error)
                            throw error;

                    var lens = stdout.trim().split(":");
                    var MINUTES = 1, SECONDS = 2;
                    var duration = parseFloat(lens[MINUTES])*60 + parseFloat(lens[SECONDS]);
                    headers['X-Content-Duration'] = String(duration);
                    send_stream(path,req,res,headers);
            });
    }
    //----------------------------------------------------

    if(typeof(base_dir)==="undefined")
        base_dir = "";

    this.send_static = function(file_path,req,res){

        var ext = path.extname(file_path).substring(1),
            mime_type = mime_types[ext],
            fs_path = path.join(path.resolve(base_dir),file_path),
            headers = {'Accept-Ranges': 'bytes','Content-Type':mime_type};

        if(Ys.ogg_header_support && headers["Content-Type"] && headers["Content-Type"].match(/^\w+\/ogg$/)){
            send_ogg(fs_path,req,res,headers);
            return;
        }

        send_stream(fs_path,req,res,headers);
    }
}
//===================================================
Handler.prototype.gzip = function(base_dir){

    if(typeof(base_dir)==="undefined")
        base_dir = "";

    this.send_gzip = function(file_path,req,res){

        var ext = path.extname(file_path).substring(1),
            mime_type = mime_types[ext],
            fs_path = path.join(path.resolve(base_dir),file_path),
            headers = {'Content-Type':mime_type};

        var raw = fs.createReadStream(fs_path);
        stream_gzip(raw,req,res,headers);
        /*
        var acceptEncoding = req.headers['accept-encoding'];
        if (!acceptEncoding)
            acceptEncoding = '';

        var stream = raw;

        // Note: this is not a conformant accept-encoding parser.
        // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
        if (acceptEncoding.match(/\bdeflate\b/)) {
            headers['content-encoding'] = 'deflate';
            stream = raw.pipe(zlib.createDeflate());
        } else if (acceptEncoding.match(/\bgzip\b/)) {
            headers['content-encoding'] = 'gzip';
            stream = raw.pipe(zlib.createGzip());
        }

       res.writeHead(200,headers);
       stream.pipe(res);
       */
    }
}
//===================================================
var Ys = exports.Ys = function(url) {

    var idx = -1;
    for(var i=0; i < routes.length; i++){
        if(routes[i][0]===url){
            idx = i;
        }
    }

    if(idx===-1){
        routes.push([url,new Route()]);
        idx = routes.length - 1;
    }

    return routes[idx][1]

}
//--------------------------------------------------
var jsonify = function(object){
    this.end(JSON.stringify(object));
}
//--------------------------------------------------
var htmlify = function(compiled_template,req,headers){

    return function(object){
        //this.end(compiled_template(object));
        var html = compiled_template(object);
	stream_gzip(html,req,this,headers);
    }
}
//--------------------------------------------------
var stream_gzip = Ys.stream_gzip = function(input,req,res,headers){

        var acceptEncoding = req.headers['accept-encoding'];
        if (!acceptEncoding)
            acceptEncoding = '';

        var stream = null,compression_stream = null;

        // Note: this is not a conformant accept-encoding parser.
        // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
        if (acceptEncoding.match(/\bdeflate\b/)) {
            headers['content-encoding'] = 'deflate';
	    compression_stream = zlib.createDeflate();
        } else if (acceptEncoding.match(/\bgzip\b/)) {
            headers['content-encoding'] = 'gzip';
	    compression_stream = zlib.createGzip();
        }

       res.writeHead(200,headers);

       if(typeof(input.pipe) === "function"){
	    if(compression_stream)
            	stream = input.pipe(compression_stream);
	    else
		stream = input;
       	    stream.pipe(res);
	    return;
       }

       if(compression_stream){
	    compression_stream.pipe(res);
	    compression_stream.write(input);
	    compression_stream.end();
	    return;
       }

       res.write(input);

}
//--------------------------------------------------
var PATH_REGEXP = 0, HANDLERS = 1;
var handle_request = function(req,res){

    var pathname = url.parse(req.url).pathname;
    for(var i=0; i < routes.length; i++){
        var regexp = RegExp(routes[i][PATH_REGEXP]);
        var route = routes[i];
        var match = regexp.exec(pathname);
        if(!match)
            continue;

        if(typeof(route[HANDLERS]["redirect"]) === "string"){
            pathname = route[HANDLERS]["redirect"].replace("$1",match[1]);
            res.writeHead(301,{"Location":pathname});
            res.end();
            return;
        }

        if(typeof(route[HANDLERS]["rewrite"]) === "string"){
            pathname = route[HANDLERS]["rewrite"].replace("$1",match[1]);
            continue;
        }

        if(typeof(route[HANDLERS][req.method.toLowerCase()])==="undefined")
            continue;

        if(match.length > 1)
            req.$1 = match[1];

        var handler = route[HANDLERS][req.method.toLowerCase()];

        function isEmpty(obj) {
            for(var prop in obj)
                if(obj.hasOwnProperty(prop))
                    return false;
            return true;
        }

        if(typeof(handler)==="object" && isEmpty(handler))
            throw new Error(pathname +" >> No handler defined for this path and method "+req.method);

        if(typeof(handler)==="function"){
            handler(req,res);
            return;
        }

        if(typeof(handler)==="object"){

            if("send_gzip" in handler){
                handler.send_gzip(pathname,req,res);
                return;
            }
            if("send_static" in handler){
                handler.send_static(pathname,req,res);
                return;
            }

            if("json" in handler){
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.returnObject = jsonify;
                handler.json(req,res);
                return;
            }

            if("html" in handler){
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.returnObject = htmlify(handler.compiled);

                if("args" in handler)//actual template
                    handler.args(req,res);
                else
                    res.returnObject();

            }

            return;
        }

    }

    throw new Error(pathname +" >> No mapping for this path");
}
//--------------------------------------------------
Ys.run = function(port,host,user){

    if(!port)
        port = 8780;

    if(!host)
        host= "127.0.0.1";

    var mimes_raw  = fs.readFileSync('/etc/mime.types','utf-8').split('\n')
    for(var i=0; i<mimes_raw.length; i++){
        var next = mimes_raw[i].split(/\s+/g)
        if(next && next.length >= 2)
            for(var j=1; j < next.length; j++)
                mime_types[next[j]] = next[0];
    }

    //correction for some types
    //mime_types["mp3"] = "audio/mp3";
    process.on('uncaughtException', function (err) {
            var str = err.stack;
            console.log(str);
            //res.end(str);
    });

    var server = http.createServer(function (req, res) {

        try{
            handle_request(req,res);
        }
        catch(e){
            var str = e.stack;
            console.log(str);
            res.end(str);
        }

    });

    if(user){
        server.once("listening",function(){
            process.setuid(user);
            //process.setgid(user);
        });
    }

    server.listen(port,host);

    console.log('Server running at '+host+':'+port+'/');
}
//--------------------------------------------------
<commit_msg>fix for redirect on post<commit_after>var http = require('http'),
    url = require('url'),
    fs = require('fs'),
    ejs = require('ejs'),
    path = require('path'),
    exec = require('child_process').exec,
    util = require('util'),
    zlib = require('zlib');
//var querystring = require('querystring');

var mime_types = {}
var routes = []
//--------------------------------------------------
var Route = function(){

    this.get = new Handler();
    this.post = new Handler();
    return this;
}
//--------------------------------------------------
var Handler = function(){
    return this;
}
//--------------------------------------------------
Handler.prototype.html = function(template_path){
    //load template
    var t = this;
    fs.readFile(template_path, function (err, data) {
          if (err) throw err;
          t.compiled = ejs.compile(String(data));
    });
    return this;
}
//===================================================
Handler.prototype.static = function(base_dir){

    //----------------------------------------------------
    var send_stream = function(fs_path,req,res,headers) {

        fs.stat(fs_path,function(err,stats){

            if(err){
                res.writeHead(404);
                res.end("404 - not found.");
                return;

            }
            var ins = util.inspect(stats);
            var size = ins.match(/size:\s*(\d+)/)[1];
            headers['Content-Length'] = size;

           var flags = {};
           //console.log(req.headers);
           range = req.headers['range'];

           if(range){
                var match = range.match(/^bytes\s*=\s*(\d+)-(\d*)/);
                if(match){
                    var start = parseInt(match[1]);
                    var end = match[2].length > 0 ? parseInt(match[2]) : parseInt(size) -1;
                    headers["Content-Range"] =  'bytes %start-%end/%length'.replace("%start",start).replace("%end",end).replace("%length",size);
                    res.writeHead(206,headers);
                    flags["start"] = start;
                    flags["end"] = end;
                }
                else{
                    res.writeHead(416,headers);
                }
            }
            else
                res.writeHead(200,headers);
            /*fs.readFile(fs_path, function (err, data) {
              if (err)
                throw err;

                res.end(data);
            });*/
            var fstream = fs.createReadStream(fs_path,flags);
            fstream.pipe(res);

        });

        /*}
            kv = range.split("=");
            if(!kv[1])
        }*/
    }
    //----------------------------------------------------
    var send_ogg= function(path,req,res,headers,flags){

       var child = exec("ogginfo %s | grep 'Playback length'".replace("%s",path),
                  function (error, stdout, stderr) {
                      if(error)
                            throw error;

                    var lens = stdout.trim().split(":");
                    var MINUTES = 1, SECONDS = 2;
                    var duration = parseFloat(lens[MINUTES])*60 + parseFloat(lens[SECONDS]);
                    headers['X-Content-Duration'] = String(duration);
                    send_stream(path,req,res,headers);
            });
    }
    //----------------------------------------------------

    if(typeof(base_dir)==="undefined")
        base_dir = "";

    this.send_static = function(file_path,req,res){

        var ext = path.extname(file_path).substring(1),
            mime_type = mime_types[ext],
            fs_path = path.join(path.resolve(base_dir),file_path),
            headers = {'Accept-Ranges': 'bytes','Content-Type':mime_type};

        if(Ys.ogg_header_support && headers["Content-Type"] && headers["Content-Type"].match(/^\w+\/ogg$/)){
            send_ogg(fs_path,req,res,headers);
            return;
        }

        send_stream(fs_path,req,res,headers);
    }
}
//===================================================
Handler.prototype.gzip = function(base_dir){

    if(typeof(base_dir)==="undefined")
        base_dir = "";

    this.send_gzip = function(file_path,req,res){

        var ext = path.extname(file_path).substring(1),
            mime_type = mime_types[ext],
            fs_path = path.join(path.resolve(base_dir),file_path),
            headers = {'Content-Type':mime_type};

        var raw = fs.createReadStream(fs_path);
        stream_gzip(raw,req,res,headers);
        /*
        var acceptEncoding = req.headers['accept-encoding'];
        if (!acceptEncoding)
            acceptEncoding = '';

        var stream = raw;

        // Note: this is not a conformant accept-encoding parser.
        // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
        if (acceptEncoding.match(/\bdeflate\b/)) {
            headers['content-encoding'] = 'deflate';
            stream = raw.pipe(zlib.createDeflate());
        } else if (acceptEncoding.match(/\bgzip\b/)) {
            headers['content-encoding'] = 'gzip';
            stream = raw.pipe(zlib.createGzip());
        }

       res.writeHead(200,headers);
       stream.pipe(res);
       */
    }
}
//===================================================
var Ys = exports.Ys = function(url) {

    var idx = -1;
    for(var i=0; i < routes.length; i++){
        if(routes[i][0]===url){
            idx = i;
        }
    }

    if(idx===-1){
        routes.push([url,new Route()]);
        idx = routes.length - 1;
    }

    return routes[idx][1]

}
//--------------------------------------------------
var jsonify = function(object){
    this.end(JSON.stringify(object));
}
//--------------------------------------------------
var htmlify = function(compiled_template,req,headers){

    return function(object){
        //this.end(compiled_template(object));
        var html = compiled_template(object);
	    stream_gzip(html,req,this,headers);
    }
}
//--------------------------------------------------
var stream_gzip = Ys.stream_gzip = function(input,req,res,headers){

        var acceptEncoding = req.headers['accept-encoding'];
        if (!acceptEncoding)
            acceptEncoding = '';

        var stream = null,compression_stream = null;

        // Note: this is not a conformant accept-encoding parser.
        // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
        if (acceptEncoding.match(/\bdeflate\b/)) {
            headers['content-encoding'] = 'deflate';
	    compression_stream = zlib.createDeflate();
        } else if (acceptEncoding.match(/\bgzip\b/)) {
            headers['content-encoding'] = 'gzip';
	    compression_stream = zlib.createGzip();
        }

       res.writeHead(200,headers);

       if(typeof(input.pipe) === "function"){
	    if(compression_stream)
            	stream = input.pipe(compression_stream);
	    else
		stream = input;
       	    stream.pipe(res);
	    return;
       }

       if(compression_stream){
	    compression_stream.pipe(res);
	    compression_stream.write(input);
	    compression_stream.end();
	    return;
       }

       res.write(input);

}
//--------------------------------------------------
var PATH_REGEXP = 0, HANDLERS = 1;
var handle_request = function(req,res){

    var pathname = url.parse(req.url).pathname;
    for(var i=0; i < routes.length; i++){
        var regexp = RegExp(routes[i][PATH_REGEXP]);
        var route = routes[i];
        var match = regexp.exec(pathname);
        if(!match)
            continue;

        if(typeof(route[HANDLERS]["redirect"]) === "string"){
            pathname = route[HANDLERS]["redirect"].replace("$1",match[1]);
            if(req.method.toLowerCase() == "post")
                res.writeHead(307,{"Location":pathname});
            else
                res.writeHead(301,{"Location":pathname});
            res.end();
            return;
        }

        if(typeof(route[HANDLERS]["rewrite"]) === "string"){
            pathname = route[HANDLERS]["rewrite"].replace("$1",match[1]);
            continue;
        }

        if(typeof(route[HANDLERS][req.method.toLowerCase()])==="undefined")
            continue;

        if(match.length > 1)
            req.$1 = match[1];

        var handler = route[HANDLERS][req.method.toLowerCase()];

        function isEmpty(obj) {
            for(var prop in obj)
                if(obj.hasOwnProperty(prop))
                    return false;
            return true;
        }

        if(typeof(handler)==="object" && isEmpty(handler))
            throw new Error(pathname +" >> No handler defined for selector '"+regexp+"' and method "+req.method);

        if(typeof(handler)==="function"){
            handler(req,res);
            return;
        }

        if(typeof(handler)==="object"){

            if("send_gzip" in handler){
                handler.send_gzip(pathname,req,res);
                return;
            }
            if("send_static" in handler){
                handler.send_static(pathname,req,res);
                return;
            }

            if("json" in handler){
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.returnObject = jsonify;
                handler.json(req,res);
                return;
            }

            if("html" in handler){
                var headers ={'Content-Type': 'text/html'};
                res.returnObject = htmlify(handler.compiled,req,headers);

                if("args" in handler)//actual template
                    handler.args(req,res);
                else
                    res.returnObject();

            }

            return;
        }

    }

    throw new Error(pathname +" >> No mapping for this path");
}
//--------------------------------------------------
Ys.run = function(port,host,user){

    if(!port)
        port = 8780;

    if(!host)
        host= "127.0.0.1";

    var mimes_raw  = fs.readFileSync('/etc/mime.types','utf-8').split('\n')
    for(var i=0; i<mimes_raw.length; i++){
        var next = mimes_raw[i].split(/\s+/g)
        if(next && next.length >= 2)
            for(var j=1; j < next.length; j++)
                mime_types[next[j]] = next[0];
    }

    //correction for some types
    //mime_types["mp3"] = "audio/mp3";
    process.on('uncaughtException', function (err) {
            var str = err.stack;
            console.log(str);
            //res.end(str);
    });

    var server = http.createServer(function (req, res) {

        try{
            handle_request(req,res);
        }
        catch(e){
            var str = e.stack;
            console.log(str);
            res.end(str);
        }

    });

    if(user){
        server.once("listening",function(){
            process.setuid(user);
            //process.setgid(user);
        });
    }

    server.listen(port,host);

    console.log('Server running at '+host+':'+port+'/');
}
//--------------------------------------------------
<|endoftext|>


<commit_before>suite('local-time', function() {
  test('null getFormattedDate when datetime missing', function() {
    var time = document.createElement('local-time')
    time.setAttribute('format', '%Y-%m-%dT%H:%M:%SZ')
    assert.isUndefined(time.getFormattedDate())
  })

  test('getFormattedDate returns empty string when format missing', function() {
    var time = document.createElement('local-time')
    time.setAttribute('datetime', '1970-01-01T00:00:00.000Z')
    assert.equal(time.getFormattedDate(), '')
  })

  test('getFormattedDate with only date attributes', function() {
    var time = document.createElement('local-time')
    time.setAttribute('datetime', '1970-01-01T00:00:00.000Z')
    time.setAttribute('day', 'numeric')
    time.setAttribute('month', 'short')
    time.setAttribute('year', 'numeric')

    var value = time.getFormattedDate()
    assert.include(['Dec 31, 1969', '31 Dec 1969', 'Jan 1, 1970', '1 Jan 1970'], value)
  })

  test('getFormattedDate without year attribute', function() {
    var time = document.createElement('local-time')
    time.setAttribute('datetime', '1970-01-01T00:00:00.000Z')
    time.setAttribute('day', 'numeric')
    time.setAttribute('month', 'short')

    var value = time.getFormattedDate()
    assert.include(['Dec 31', '31 Dec', 'Jan 1', '1 Jan'], value)
  })

  test('getFormattedDate with only time attributes', function() {
    var time = document.createElement('local-time')
    time.setAttribute('datetime', '1970-01-01T00:00:00.000Z')
    time.setAttribute('hour', 'numeric')
    time.setAttribute('minute', '2-digit')

    if ('Intl' in window) {
      assert.match(time.getFormattedDate(), /^\d{1,2}:\d\d (AM|PM)$/)
    } else {
      assert.match(time.getFormattedDate(), /^\d{2}:\d{2}$/)
    }
  })

  test('ignores contents if datetime attribute is missing', function() {
    var time = document.createElement('local-time')
    time.setAttribute('year', 'numeric')
    assert.equal(time.textContent, '')
  })

  test('sets formatted contents to format attribute', function() {
    var time = document.createElement('local-time')
    time.setAttribute('datetime', '1970-01-01T00:00:00.000Z')
    time.setAttribute('year', 'numeric')
    assert.include(['1969', '1970'], time.textContent)
  })

  test('sets formatted contents when parsed element is upgraded', function() {
    var root = document.createElement('div')
    root.innerHTML = '<local-time datetime="1970-01-01T00:00:00.000Z" year="numeric"></local-time>'
    if ('CustomElements' in window) {
      window.CustomElements.upgradeSubtree(root)
    }
    assert.include(['1969', '1970'], root.children[0].textContent)
  })

  ;('Intl' in window ? test : test.skip)('displays time zone name', function() {
    var time = document.createElement('local-time')
    time.setAttribute('datetime', '1970-01-01T00:00:00.000Z')
    time.setAttribute('minute', '2-digit')
    time.setAttribute('time-zone-name', 'short')
    assert.match(time.textContent, /^\d{1,2} (UTC|GMT([+-]\d+)?)$/)
  })
})
<commit_msg>Fix timezone test<commit_after>suite('local-time', function() {
  test('null getFormattedDate when datetime missing', function() {
    var time = document.createElement('local-time')
    time.setAttribute('format', '%Y-%m-%dT%H:%M:%SZ')
    assert.isUndefined(time.getFormattedDate())
  })

  test('getFormattedDate returns empty string when format missing', function() {
    var time = document.createElement('local-time')
    time.setAttribute('datetime', '1970-01-01T00:00:00.000Z')
    assert.equal(time.getFormattedDate(), '')
  })

  test('getFormattedDate with only date attributes', function() {
    var time = document.createElement('local-time')
    time.setAttribute('datetime', '1970-01-01T00:00:00.000Z')
    time.setAttribute('day', 'numeric')
    time.setAttribute('month', 'short')
    time.setAttribute('year', 'numeric')

    var value = time.getFormattedDate()
    assert.include(['Dec 31, 1969', '31 Dec 1969', 'Jan 1, 1970', '1 Jan 1970'], value)
  })

  test('getFormattedDate without year attribute', function() {
    var time = document.createElement('local-time')
    time.setAttribute('datetime', '1970-01-01T00:00:00.000Z')
    time.setAttribute('day', 'numeric')
    time.setAttribute('month', 'short')

    var value = time.getFormattedDate()
    assert.include(['Dec 31', '31 Dec', 'Jan 1', '1 Jan'], value)
  })

  test('getFormattedDate with only time attributes', function() {
    var time = document.createElement('local-time')
    time.setAttribute('datetime', '1970-01-01T00:00:00.000Z')
    time.setAttribute('hour', 'numeric')
    time.setAttribute('minute', '2-digit')

    if ('Intl' in window) {
      assert.match(time.getFormattedDate(), /^\d{1,2}:\d\d (AM|PM)$/)
    } else {
      assert.match(time.getFormattedDate(), /^\d{2}:\d{2}$/)
    }
  })

  test('ignores contents if datetime attribute is missing', function() {
    var time = document.createElement('local-time')
    time.setAttribute('year', 'numeric')
    assert.equal(time.textContent, '')
  })

  test('sets formatted contents to format attribute', function() {
    var time = document.createElement('local-time')
    time.setAttribute('datetime', '1970-01-01T00:00:00.000Z')
    time.setAttribute('year', 'numeric')
    assert.include(['1969', '1970'], time.textContent)
  })

  test('sets formatted contents when parsed element is upgraded', function() {
    var root = document.createElement('div')
    root.innerHTML = '<local-time datetime="1970-01-01T00:00:00.000Z" year="numeric"></local-time>'
    if ('CustomElements' in window) {
      window.CustomElements.upgradeSubtree(root)
    }
    assert.include(['1969', '1970'], root.children[0].textContent)
  })
  ;('Intl' in window ? test : test.skip)('displays time zone name', function() {
    var root = document.createElement('div')
    root.innerHTML =
      '<local-time datetime="1970-01-01T00:00:00.000Z" minute="2-digit" time-zone-name="short"></local-time>'
    if ('CustomElements' in window) {
      window.CustomElements.upgradeSubtree(root)
    }
    assert.match(root.children[0].textContent, /^\d{1,2} (UTC|GMT([+-]\d+)?)$/)
  })
})
<|endoftext|>


<commit_before>'use strict';

angular.module('npm-plugin-browser')
  .controller('PluginListCtrl', function ($scope, $http, $location, $q) {

    var fields = ['name','keywords','rating','description','author','modified','homepage','version'];

    var initialFetchSize = 20;

    var makeRequest = function (start, size) {
      return $http.get('http://npmsearch.com/query', {
        params: {
          q: 'keywords:gulpplugin,gulpfriendly',
          fields: fields.join(','),
          start: start,
          size: size,
          sort: 'rating:desc'
        },
        transformResponse: $http.defaults.transformResponse.concat([formatData])
      });
    };

    var sortBy = function () {
      var args = arguments;

      return function (a, b) {
        var scoreA, scoreB;

        for (var i = 0, len = args.length; i < len; i++) {
          scoreA = args[i](a);
          scoreB = args[i](b);
          if (scoreA < scoreB) {
            return -1;
          } else if (scoreA > scoreB) {
            return 1;
          }
        }

        return 0;
      };
    };

    var sortResults = function (results) {
      return results.sort(sortBy(
        // Sort blackList plugins to bottom
        function (plugin) {
          return $scope.blackList[plugin.name] ? 1 : 0;
        },
        // Sort highly-rated plugins to top
        function (plugin) {
          return -plugin.rating;
        },
        // Fall back to sort by name
        function (plugin) {
          return plugin.name;
        }
      ));
    };

    $q.all([$http.get('blackList.json'), makeRequest(0, initialFetchSize)])
      .then(function (responses) {
        $scope.blackList = responses[0].data;
        $scope.data = sortResults(responses[1].data.results);
        return makeRequest(initialFetchSize, responses[1].data.total);
      })
      .then(function (response) {
        $scope.data = sortResults($scope.data.concat(response.data.results));
        if (angular.isString(($location.search()).q)) {
          $scope.search = ($location.search()).q;
        }
      });

    $scope.orderByGulpKeywords = function (item) {
      return (item === 'gulpplugin' || item === 'gulpfriendly') ? -1 : 0;
    };

    $scope.notBlacklisted = function (item) {
      return (item && !$scope.blackList[item.name]);
    };
  });
<commit_msg>Fixes plugin search<commit_after>'use strict';

angular.module('npm-plugin-browser')
  .controller('PluginListCtrl', function ($scope, $http, $location, $q) {

    var fields = ['name','keywords','rating','description','author','modified','homepage','version'];

    var initialFetchSize = 20;

    var formatResult = function(data){
      fields.forEach(function(k){
        if (k === 'keywords') return;
        if (!Array.isArray(data[k])) return;
        data[k] = data[k][0];
      });
      return data;
    };

    var formatData = function(data){
      var out = {
        results: data.results.map(formatResult),
        total: data.total
      };
      return out;
    };

    var makeRequest = function (start, size) {
      return $http.get('http://npmsearch.com/query', {
        params: {
          q: ['keywords:gulpfriendly', 'keywords:gulpplugin'],
          fields: fields.join(','),
          start: start,
          size: size,
          sort: 'rating:desc'
        },
        transformResponse: $http.defaults.transformResponse.concat([formatData])
      });
    };

    var sortBy = function () {
      var args = arguments;

      return function (a, b) {
        var scoreA, scoreB;

        for (var i = 0, len = args.length; i < len; i++) {
          scoreA = args[i](a);
          scoreB = args[i](b);
          if (scoreA < scoreB) {
            return -1;
          } else if (scoreA > scoreB) {
            return 1;
          }
        }

        return 0;
      };
    };

    var sortResults = function (results) {
      return results.sort(sortBy(
        // Sort blackList plugins to bottom
        function (plugin) {
          return $scope.blackList[plugin.name] ? 1 : 0;
        },
        // Sort highly-rated plugins to top
        function (plugin) {
          return -plugin.rating;
        },
        // Fall back to sort by name
        function (plugin) {
          return plugin.name;
        }
      ));
    };

    $q.all([$http.get('blackList.json'), makeRequest(0, initialFetchSize)])
      .then(function (responses) {
        $scope.blackList = responses[0].data;
        $scope.data = sortResults(responses[1].data.results);
        return makeRequest(initialFetchSize, responses[1].data.total);
      })
      .then(function (response) {
        $scope.data = sortResults($scope.data.concat(response.data.results));
        if (angular.isString(($location.search()).q)) {
          $scope.search = ($location.search()).q;
        }
      });

    $scope.orderByGulpKeywords = function (item) {
      return (item === 'gulpplugin' || item === 'gulpfriendly') ? -1 : 0;
    };

    $scope.notBlacklisted = function (item) {
      return (item && !$scope.blackList[item.name]);
    };
  });
<|endoftext|>


<commit_before>/**
 * Load .textContent by iframe from specified HTML elemen of specified (same origin)
 * web page.
 *
 * @param {string} iframeSrcURL
 *   The web page to be loaded. An iframe will be used to load it. After .textContent
 * has been extracted, the iframe will be released.
 *
 * @param {string} elementIdInsideIFrame
 *   The HTML element id. When the web page has been loaded, the .textContent of the
 * the HTML element with this id will be extracted.
 *
 * @return {Promise}
 *   Return a Promise. When the Promise resolve, the .textContent of the HTML element
 * will be returned.
 */
function createPromise_GetTextContent_ByIFrame(iframeSrcURL, elementIdInsideIFrame) {
  return new Promise(function(resolve, reject) {
    let theIFrame = document.createElement("iframe");
    theIFrame.style.display = "none";
    theIFrame.src           = iframeSrcURL;
    theIFrame.sandbox       ="allow-same-origin";
    theIFrame.onload        = function() { resolve(theIFrame); }
    document.body.appendChild(theIFrame);         // Load the URL by iframe.

  }).then(function(theIFrame) {
    let theTextContent = theIFrame.contentDocument
      .getElementById(elementIdInsideIFrame).textContent;
    theIFrame.parentNode.removeChild(theIFrame);  // Release the iframe.
    return theTextContent;
  });
}
<commit_msg>Improve comments.<commit_after>/**
 * Dynamically load .textContent by iframe from specified HTML elemen of specified
 * (same origin) web page.
 *
 * @param {string} iframeSrcURL
 *   The web page to be loaded. An iframe will be used to load it. After .textContent
 * has been extracted, the iframe will be released.
 *
 * @param {string} elementIdInsideIFrame
 *   The HTML element id. When the web page has been loaded, the .textContent of the
 * the HTML element with this id will be extracted.
 *
 * @return {Promise}
 *   Return a Promise. When the Promise resolve, the .textContent of the HTML element
 * will be returned.
 */
function createPromise_GetTextContent_ByIFrame(iframeSrcURL, elementIdInsideIFrame) {
  return new Promise(function(resolve, reject) {
    let theIFrame = document.createElement("iframe");
    theIFrame.style.display = "none";
    theIFrame.src           = iframeSrcURL;
    theIFrame.sandbox       ="allow-same-origin";
    theIFrame.onload        = function() { resolve(theIFrame); }
    document.body.appendChild(theIFrame);         // Load the URL by iframe.

  }).then(function(theIFrame) {
    let theTextContent = theIFrame.contentDocument
      .getElementById(elementIdInsideIFrame).textContent;
    theIFrame.parentNode.removeChild(theIFrame);  // Release the iframe.
    return theTextContent;
  });
}
<|endoftext|>


<commit_before>// Info here: http://ad.aloodo.com/

function doAloodoPopup() {
	var url = 'https://www.aloodo.org/protection/';
	var message = 	'Third-party tracking detected. ' +
			'Missing or misconfigured tracking protection.';
	var txt = '' + message + '';

	if (typeof toastr=='undefined') {
		window.setTimeout(doAloodoPopup, 1000);
	} else {
		toastr.options = { 'timeOut': 30000 };
		toastr.error(txt);
	}
}

function toastrSetup() {
	if (typeof toastr !== 'undefined') {
		doAloodoPopup();
	}
	var sc = document.createElement('script');
	sc.setAttribute('src', 'https://ad.aloodo.com/toastr/toastr.js');
	document.body.appendChild(sc);
	sc.onload = doAloodoPopup();
	var cs = document.createElement('link');
	cs.setAttribute("rel", "stylesheet");
	cs.setAttribute("type", "text/css");
	cs.setAttribute("href", 'https://ad.aloodo.com/toastr/toastr.css');
	document.getElementsByTagName('head')[0].appendChild(cs);
}

function startAloodo(ev) {
	if (ev.data !== 'tracking detected') {
		return;
	}

	if (window.trackingAlternateLocation) {
		document.getElementsByTagName('body')[0].style.display='none';
		window.location.href = trackingAlternateLocation;
		return;
	}

	var safety = document.getElementById('tracking-safety');
	if (safety) {
		safety.style.display = 'none';
	}

	var done = false;
	var warning = document.getElementById('tracking-warning-block');
	if (warning) {
		warning.style.display = 'block';
		done = true;
	}
	var warning = document.getElementById('tracking-warning-table-cell');
	if (warning) {
		warning.style.display = 'table-cell';
		done = true;
	}
	var warning = document.getElementById('tracking-warning-inline');
	if (warning) {
		warning.style.display = 'inline';
		done = true;
	}
	if (done) { return; }

	if(typeof jQuery=='undefined') {
		var jq = document.createElement('script');
		jq.src = '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js';
		jq.onload = toastrSetup;
		document.body.appendChild(jq);
	} else {
		toastrSetup();
	}
}

function isMSIE() {
	return "ActiveXObject" in window
}

function setupAloodo() {
	// This puts the tracker in an iframe.
	var ifr = document.createElement('iframe');
	ifr.src = "//ad.aloodo.com/track/";
	ifr.style.visibility = 'hidden';
	document.body.appendChild(ifr);
}

window.addEventListener("message", startAloodo, false);
window.addEventListener("load", setupAloodo);

// Workaround for not being able to send cross-domain messages
// from iframe to its parent.  Assumes that MSIE is unprotected
// if this script runs at all.
if (isMSIE()) {
	window.postMessage('tracking detected', '*');
}
<commit_msg>Temporarily link to HTTP version of protection page<commit_after>// Info here: http://ad.aloodo.com/

function doAloodoPopup() {
	var url = 'http://www.aloodo.org/protection/';
	var message = 	'Third-party tracking detected. ' +
			'Missing or misconfigured tracking protection.';
	var txt = '' + message + '';

	if (typeof toastr=='undefined') {
		window.setTimeout(doAloodoPopup, 1000);
	} else {
		toastr.options = { 'timeOut': 30000 };
		toastr.error(txt);
	}
}

function toastrSetup() {
	if (typeof toastr !== 'undefined') {
		doAloodoPopup();
	}
	var sc = document.createElement('script');
	sc.setAttribute('src', 'https://ad.aloodo.com/toastr/toastr.js');
	document.body.appendChild(sc);
	sc.onload = doAloodoPopup();
	var cs = document.createElement('link');
	cs.setAttribute("rel", "stylesheet");
	cs.setAttribute("type", "text/css");
	cs.setAttribute("href", 'https://ad.aloodo.com/toastr/toastr.css');
	document.getElementsByTagName('head')[0].appendChild(cs);
}

function startAloodo(ev) {
	if (ev.data !== 'tracking detected') {
		return;
	}

	if (window.trackingAlternateLocation) {
		document.getElementsByTagName('body')[0].style.display='none';
		window.location.href = trackingAlternateLocation;
		return;
	}

	var safety = document.getElementById('tracking-safety');
	if (safety) {
		safety.style.display = 'none';
	}

	var done = false;
	var warning = document.getElementById('tracking-warning-block');
	if (warning) {
		warning.style.display = 'block';
		done = true;
	}
	var warning = document.getElementById('tracking-warning-table-cell');
	if (warning) {
		warning.style.display = 'table-cell';
		done = true;
	}
	var warning = document.getElementById('tracking-warning-inline');
	if (warning) {
		warning.style.display = 'inline';
		done = true;
	}
	if (done) { return; }

	if(typeof jQuery=='undefined') {
		var jq = document.createElement('script');
		jq.src = '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js';
		jq.onload = toastrSetup;
		document.body.appendChild(jq);
	} else {
		toastrSetup();
	}
}

function isMSIE() {
	return "ActiveXObject" in window
}

function setupAloodo() {
	// This puts the tracker in an iframe.
	var ifr = document.createElement('iframe');
	ifr.src = "//ad.aloodo.com/track/";
	ifr.style.visibility = 'hidden';
	document.body.appendChild(ifr);
}

window.addEventListener("message", startAloodo, false);
window.addEventListener("load", setupAloodo);

// Workaround for not being able to send cross-domain messages
// from iframe to its parent.  Assumes that MSIE is unprotected
// if this script runs at all.
if (isMSIE()) {
	window.postMessage('tracking detected', '*');
}
<|endoftext|>


<commit_before>window.iD = function () {
    window.locale.en = iD.data.en;
    window.locale.current('en');

    var context = {},
        storage;

    // https://github.com/openstreetmap/iD/issues/772
    // http://mathiasbynens.be/notes/localstorage-pattern#comment-9
    try { storage = localStorage; } catch (e) {}
    storage = storage || (function() {
        var s = {};
        return {
            getItem: function(k) { return s[k]; },
            setItem: function(k, v) { s[k] = v; },
            removeItem: function(k) { delete s[k]; }
        };
    })();

    context.storage = function(k, v) {
        try {
            if (arguments.length === 1) return storage.getItem(k);
            else if (v === null) storage.removeItem(k);
            else storage.setItem(k, v);
        } catch(e) {
            // localstorage quota exceeded
            /* jshint devel:true */
            if (typeof console !== 'undefined') console.error('localStorage quota exceeded');
            /* jshint devel:false */
        }
    };

    /* Accessor for setting minimum zoom for editing features. */

    var minEditableZoom = 16;
    context.minEditableZoom = function(_) {
        if (!arguments.length) return minEditableZoom;
        minEditableZoom = _;
        connection.tileZoom(_);
        return context;
    };

    var history = iD.History(context),
        dispatch = d3.dispatch('enter', 'exit'),
        mode,
        container,
        ui = iD.ui(context),
        connection = iD.Connection(),
        locale = iD.detect().locale,
        localePath;

    if (locale && iD.data.locales.indexOf(locale) === -1) {
        locale = locale.split('-')[0];
    }

    context.preauth = function(options) {
        connection.switch(options);
        return context;
    };

    context.locale = function(_, path) {
        locale = _;
        localePath = path;
        return context;
    };

    context.loadLocale = function(cb) {
        if (locale && locale !== 'en' && iD.data.locales.indexOf(locale) !== -1) {
            localePath = localePath || context.assetPath() + 'locales/' + locale + '.json';
            d3.json(localePath, function(err, result) {
                window.locale[locale] = result;
                window.locale.current(locale);
                cb();
            });
        } else {
            cb();
        }
    };

    /* Straight accessors. Avoid using these if you can. */
    context.ui = function() { return ui; };
    context.connection = function() { return connection; };
    context.history = function() { return history; };

    /* Connection */
    function entitiesLoaded(err, result) {
        if (!err) history.merge(result.data, result.extent);
    }

    context.loadTiles = function(projection, dimensions, callback) {
        function done(err, result) {
            entitiesLoaded(err, result);
            if (callback) callback(err, result);
        }
        connection.loadTiles(projection, dimensions, done);
    };

    context.loadEntity = function(id, callback) {
        function done(err, result) {
            entitiesLoaded(err, result);
            if (callback) callback(err, result);
        }
        connection.loadEntity(id, done);
    };

    context.zoomToEntity = function(id, zoomTo) {
        if (zoomTo !== false) {
            this.loadEntity(id, function(err, result) {
                if (err) return;
                var entity = _.find(result.data, function(e) { return e.id === id; });
                if (entity) { map.zoomTo(entity); }
            });
        }

        map.on('drawn.zoomToEntity', function() {
            if (!context.hasEntity(id)) return;
            map.on('drawn.zoomToEntity', null);
            context.on('enter.zoomToEntity', null);
            context.enter(iD.modes.Select(context, [id]));
        });

        context.on('enter.zoomToEntity', function() {
            if (mode.id !== 'browse') {
                map.on('drawn.zoomToEntity', null);
                context.on('enter.zoomToEntity', null);
            }
        });
    };

    /* History */
    context.graph = history.graph;
    context.changes = history.changes;
    context.intersects = history.intersects;

    var inIntro = false;

    context.inIntro = function(_) {
        if (!arguments.length) return inIntro;
        inIntro = _;
        return context;
    };

    context.save = function() {
        if (inIntro) return;
        history.save();
        if (history.hasChanges()) return t('save.unsaved_changes');
    };

    context.flush = function() {
        connection.flush();
        features.reset();
        history.reset();
        return context;
    };

    // Debounce save, since it's a synchronous localStorage write,
    // and history changes can happen frequently (e.g. when dragging).
    var debouncedSave = _.debounce(context.save, 350);
    function withDebouncedSave(fn) {
        return function() {
            var result = fn.apply(history, arguments);
            debouncedSave();
            return result;
        };
    }

    context.perform = withDebouncedSave(history.perform);
    context.replace = withDebouncedSave(history.replace);
    context.pop = withDebouncedSave(history.pop);
    context.undo = withDebouncedSave(history.undo);
    context.redo = withDebouncedSave(history.redo);

    /* Graph */
    context.hasEntity = function(id) {
        return history.graph().hasEntity(id);
    };

    context.entity = function(id) {
        return history.graph().entity(id);
    };

    context.childNodes = function(way) {
        return history.graph().childNodes(way);
    };

    context.geometry = function(id) {
        return context.entity(id).geometry(history.graph());
    };

    /* Modes */
    context.enter = function(newMode) {
        if (mode) {
            mode.exit();
            dispatch.exit(mode);
        }

        mode = newMode;
        mode.enter();
        dispatch.enter(mode);
    };

    context.mode = function() {
        return mode;
    };

    context.selectedIDs = function() {
        if (mode && mode.selectedIDs) {
            return mode.selectedIDs();
        } else {
            return [];
        }
    };

    /* Behaviors */
    context.install = function(behavior) {
        context.surface().call(behavior);
    };

    context.uninstall = function(behavior) {
        context.surface().call(behavior.off);
    };

    /* Copy/Paste */
    var copiedIDs = [];
    context.copiedIDs = function(_) {
        if (!arguments.length) return copiedIDs;
        copiedIDs = _;
        return context;
    };

    /* Projection */
    context.projection = iD.geo.RawMercator();

    /* Background */
    var background = iD.Background(context);
    context.background = function() { return background; };

    /* Features */
    var features = iD.Features(context);
    context.features = function() { return features; };
    context.hasHiddenConnections = function(id) {
        var graph = history.graph(),
            entity = graph.entity(id);
        return features.hasHiddenConnections(entity, graph);
    };

    /* Map */
    var map = iD.Map(context);
    context.map = function() { return map; };
    context.layers = function() { return map.layers; };
    context.surface = function() { return map.surface; };
    context.editable = function() { return map.editable(); };
    context.mouse = map.mouse;
    context.extent = map.extent;
    context.pan = map.pan;
    context.zoomIn = map.zoomIn;
    context.zoomOut = map.zoomOut;

    context.surfaceRect = function() {
        // Work around a bug in Firefox.
        //   http://stackoverflow.com/questions/18153989/
        //   https://bugzilla.mozilla.org/show_bug.cgi?id=530985
        return context.surface().node().parentNode.getBoundingClientRect();
    };

    /* Presets */
    var presets = iD.presets();

    context.presets = function(_) {
        if (!arguments.length) return presets;
        presets.load(_);
        iD.areaKeys = presets.areaKeys();
        return context;
    };

    context.imagery = function(_) {
        background.load(_);
        return context;
    };

    context.container = function(_) {
        if (!arguments.length) return container;
        container = _;
        container.classed('id-container', true);
        return context;
    };

    /* Taginfo */
    var taginfo;
    context.taginfo = function(_) {
        if (!arguments.length) return taginfo;
        taginfo = _;
        return context;
    };

    var embed = false;
    context.embed = function(_) {
        if (!arguments.length) return embed;
        embed = _;
        return context;
    };

    var assetPath = '';
    context.assetPath = function(_) {
        if (!arguments.length) return assetPath;
        assetPath = _;
        return context;
    };

    var assetMap = {};
    context.assetMap = function(_) {
        if (!arguments.length) return assetMap;
        assetMap = _;
        return context;
    };

    context.imagePath = function(_) {
        var asset = 'img/' + _;
        return assetMap[asset] || assetPath + asset;
    };

    return d3.rebind(context, dispatch, 'on');
};

iD.version = '1.6.1';

(function() {
    var detected = {};

    var ua = navigator.userAgent,
        msie = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})');

    if (msie.exec(ua) !== null) {
        var rv = parseFloat(RegExp.$1);
        detected.support = !(rv && rv < 9);
    } else {
        detected.support = true;
    }

    // Added due to incomplete svg style support. See #715
    detected.opera = ua.indexOf('Opera') >= 0;

    detected.locale = navigator.language || navigator.userLanguage;

    detected.filedrop = (window.FileReader && 'ondrop' in window);

    function nav(x) {
        return navigator.userAgent.indexOf(x) !== -1;
    }

    if (nav('Win')) detected.os = 'win';
    else if (nav('Mac')) detected.os = 'mac';
    else if (nav('X11')) detected.os = 'linux';
    else if (nav('Linux')) detected.os = 'linux';
    else detected.os = 'win';

    iD.detect = function() { return detected; };
})();
<commit_msg>Don't save history to localstorage in save mode<commit_after>window.iD = function () {
    window.locale.en = iD.data.en;
    window.locale.current('en');

    var context = {},
        storage;

    // https://github.com/openstreetmap/iD/issues/772
    // http://mathiasbynens.be/notes/localstorage-pattern#comment-9
    try { storage = localStorage; } catch (e) {}
    storage = storage || (function() {
        var s = {};
        return {
            getItem: function(k) { return s[k]; },
            setItem: function(k, v) { s[k] = v; },
            removeItem: function(k) { delete s[k]; }
        };
    })();

    context.storage = function(k, v) {
        try {
            if (arguments.length === 1) return storage.getItem(k);
            else if (v === null) storage.removeItem(k);
            else storage.setItem(k, v);
        } catch(e) {
            // localstorage quota exceeded
            /* jshint devel:true */
            if (typeof console !== 'undefined') console.error('localStorage quota exceeded');
            /* jshint devel:false */
        }
    };

    /* Accessor for setting minimum zoom for editing features. */

    var minEditableZoom = 16;
    context.minEditableZoom = function(_) {
        if (!arguments.length) return minEditableZoom;
        minEditableZoom = _;
        connection.tileZoom(_);
        return context;
    };

    var history = iD.History(context),
        dispatch = d3.dispatch('enter', 'exit'),
        mode,
        container,
        ui = iD.ui(context),
        connection = iD.Connection(),
        locale = iD.detect().locale,
        localePath;

    if (locale && iD.data.locales.indexOf(locale) === -1) {
        locale = locale.split('-')[0];
    }

    context.preauth = function(options) {
        connection.switch(options);
        return context;
    };

    context.locale = function(_, path) {
        locale = _;
        localePath = path;
        return context;
    };

    context.loadLocale = function(cb) {
        if (locale && locale !== 'en' && iD.data.locales.indexOf(locale) !== -1) {
            localePath = localePath || context.assetPath() + 'locales/' + locale + '.json';
            d3.json(localePath, function(err, result) {
                window.locale[locale] = result;
                window.locale.current(locale);
                cb();
            });
        } else {
            cb();
        }
    };

    /* Straight accessors. Avoid using these if you can. */
    context.ui = function() { return ui; };
    context.connection = function() { return connection; };
    context.history = function() { return history; };

    /* Connection */
    function entitiesLoaded(err, result) {
        if (!err) history.merge(result.data, result.extent);
    }

    context.loadTiles = function(projection, dimensions, callback) {
        function done(err, result) {
            entitiesLoaded(err, result);
            if (callback) callback(err, result);
        }
        connection.loadTiles(projection, dimensions, done);
    };

    context.loadEntity = function(id, callback) {
        function done(err, result) {
            entitiesLoaded(err, result);
            if (callback) callback(err, result);
        }
        connection.loadEntity(id, done);
    };

    context.zoomToEntity = function(id, zoomTo) {
        if (zoomTo !== false) {
            this.loadEntity(id, function(err, result) {
                if (err) return;
                var entity = _.find(result.data, function(e) { return e.id === id; });
                if (entity) { map.zoomTo(entity); }
            });
        }

        map.on('drawn.zoomToEntity', function() {
            if (!context.hasEntity(id)) return;
            map.on('drawn.zoomToEntity', null);
            context.on('enter.zoomToEntity', null);
            context.enter(iD.modes.Select(context, [id]));
        });

        context.on('enter.zoomToEntity', function() {
            if (mode.id !== 'browse') {
                map.on('drawn.zoomToEntity', null);
                context.on('enter.zoomToEntity', null);
            }
        });
    };

    /* History */
    context.graph = history.graph;
    context.changes = history.changes;
    context.intersects = history.intersects;

    var inIntro = false;

    context.inIntro = function(_) {
        if (!arguments.length) return inIntro;
        inIntro = _;
        return context;
    };

    context.save = function() {
        if (inIntro || (mode && mode.id === 'save')) return;
        history.save();
        if (history.hasChanges()) return t('save.unsaved_changes');
    };

    context.flush = function() {
        connection.flush();
        features.reset();
        history.reset();
        return context;
    };

    // Debounce save, since it's a synchronous localStorage write,
    // and history changes can happen frequently (e.g. when dragging).
    var debouncedSave = _.debounce(context.save, 350);
    function withDebouncedSave(fn) {
        return function() {
            var result = fn.apply(history, arguments);
            debouncedSave();
            return result;
        };
    }

    context.perform = withDebouncedSave(history.perform);
    context.replace = withDebouncedSave(history.replace);
    context.pop = withDebouncedSave(history.pop);
    context.undo = withDebouncedSave(history.undo);
    context.redo = withDebouncedSave(history.redo);

    /* Graph */
    context.hasEntity = function(id) {
        return history.graph().hasEntity(id);
    };

    context.entity = function(id) {
        return history.graph().entity(id);
    };

    context.childNodes = function(way) {
        return history.graph().childNodes(way);
    };

    context.geometry = function(id) {
        return context.entity(id).geometry(history.graph());
    };

    /* Modes */
    context.enter = function(newMode) {
        if (mode) {
            mode.exit();
            dispatch.exit(mode);
        }

        mode = newMode;
        mode.enter();
        dispatch.enter(mode);
    };

    context.mode = function() {
        return mode;
    };

    context.selectedIDs = function() {
        if (mode && mode.selectedIDs) {
            return mode.selectedIDs();
        } else {
            return [];
        }
    };

    /* Behaviors */
    context.install = function(behavior) {
        context.surface().call(behavior);
    };

    context.uninstall = function(behavior) {
        context.surface().call(behavior.off);
    };

    /* Copy/Paste */
    var copiedIDs = [];
    context.copiedIDs = function(_) {
        if (!arguments.length) return copiedIDs;
        copiedIDs = _;
        return context;
    };

    /* Projection */
    context.projection = iD.geo.RawMercator();

    /* Background */
    var background = iD.Background(context);
    context.background = function() { return background; };

    /* Features */
    var features = iD.Features(context);
    context.features = function() { return features; };
    context.hasHiddenConnections = function(id) {
        var graph = history.graph(),
            entity = graph.entity(id);
        return features.hasHiddenConnections(entity, graph);
    };

    /* Map */
    var map = iD.Map(context);
    context.map = function() { return map; };
    context.layers = function() { return map.layers; };
    context.surface = function() { return map.surface; };
    context.editable = function() { return map.editable(); };
    context.mouse = map.mouse;
    context.extent = map.extent;
    context.pan = map.pan;
    context.zoomIn = map.zoomIn;
    context.zoomOut = map.zoomOut;

    context.surfaceRect = function() {
        // Work around a bug in Firefox.
        //   http://stackoverflow.com/questions/18153989/
        //   https://bugzilla.mozilla.org/show_bug.cgi?id=530985
        return context.surface().node().parentNode.getBoundingClientRect();
    };

    /* Presets */
    var presets = iD.presets();

    context.presets = function(_) {
        if (!arguments.length) return presets;
        presets.load(_);
        iD.areaKeys = presets.areaKeys();
        return context;
    };

    context.imagery = function(_) {
        background.load(_);
        return context;
    };

    context.container = function(_) {
        if (!arguments.length) return container;
        container = _;
        container.classed('id-container', true);
        return context;
    };

    /* Taginfo */
    var taginfo;
    context.taginfo = function(_) {
        if (!arguments.length) return taginfo;
        taginfo = _;
        return context;
    };

    var embed = false;
    context.embed = function(_) {
        if (!arguments.length) return embed;
        embed = _;
        return context;
    };

    var assetPath = '';
    context.assetPath = function(_) {
        if (!arguments.length) return assetPath;
        assetPath = _;
        return context;
    };

    var assetMap = {};
    context.assetMap = function(_) {
        if (!arguments.length) return assetMap;
        assetMap = _;
        return context;
    };

    context.imagePath = function(_) {
        var asset = 'img/' + _;
        return assetMap[asset] || assetPath + asset;
    };

    return d3.rebind(context, dispatch, 'on');
};

iD.version = '1.6.1';

(function() {
    var detected = {};

    var ua = navigator.userAgent,
        msie = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})');

    if (msie.exec(ua) !== null) {
        var rv = parseFloat(RegExp.$1);
        detected.support = !(rv && rv < 9);
    } else {
        detected.support = true;
    }

    // Added due to incomplete svg style support. See #715
    detected.opera = ua.indexOf('Opera') >= 0;

    detected.locale = navigator.language || navigator.userLanguage;

    detected.filedrop = (window.FileReader && 'ondrop' in window);

    function nav(x) {
        return navigator.userAgent.indexOf(x) !== -1;
    }

    if (nav('Win')) detected.os = 'win';
    else if (nav('Mac')) detected.os = 'mac';
    else if (nav('X11')) detected.os = 'linux';
    else if (nav('Linux')) detected.os = 'linux';
    else detected.os = 'win';

    iD.detect = function() { return detected; };
})();
<|endoftext|>


<commit_before>/* global describe, it, beforeEach */
var assert = require("assert");
var url = require("url");
var express = require("express");
var request = require("supertest");
var jwt = require("jwt-simple");

var puavo = require("../index");
var testHookRunCount = 0;

function now() {
    return Math.round(Date.now() / 1000);
}

describe("connect-puavo", function(){

    describe("res.requestJwt()", function() {
        beforeEach(function() {
            this.app = express();
            this.app.use(express.cookieParser());
            this.app.use(express.session({ secret: "secret" }));
            this.app.use(puavo({
                authEndpoint: "https://authserver.opinsys.net/v3/remote_auth",
                sharedSecret: "secret",
                mountPoint: "http://myapp.example.com"
            }));
        });

        it("redirects to auth server when called from route", function(done){

            this.app.get("/foo", function(req, res) {
                res.requestJwt();
            });

            request(this.app)
            .get("/foo")
            .end(function(err, res) {
                if (err) throw err;
                assert(res.headers.location, "got redirect");
                var redirUrl = url.parse(res.headers.location, true);
                assert.equal(redirUrl.host, "authserver.opinsys.net");
                assert.equal(redirUrl.pathname, "/v3/remote_auth");
                assert.equal(redirUrl.query.return_to, "http://myapp.example.com/foo");
                done();

            });
        });

        it("can set custom path", function(done){
            this.app.get("/foo", function(req, res) {
                res.requestJwt("/custom/path");
            });

            request(this.app)
            .get("/foo")
            .end(function(err, res) {
                if (err) throw err;
                assert(res.headers.location, "got redirect");
                var redirUrl = url.parse(res.headers.location, true);
                assert.equal(redirUrl.query.return_to, "http://myapp.example.com/custom/path");
                done();
            });
        });

        it("can set custom path with query string", function(done){
            this.app.get("/foo", function(req, res) {
                res.requestJwt("/custom/path?my=query");
            });

            request(this.app)
            .get("/foo")
            .end(function(err, res) {
                if (err) throw err;
                assert(res.headers.location, "got redirect");
                var redirUrl = url.parse(res.headers.location, true);
                assert.equal(redirUrl.query.return_to, "http://myapp.example.com/custom/path?my=query");
                done();
            });
        });

    });

    describe("jwt", function() {
        beforeEach(function() {
            this.app = express();
            this.app.use(express.cookieParser());
            this.app.use(express.session({ secret: "secret" }));
            this.app.use(puavo({
                authEndpoint: "https://authserver.opinsys.net/v3/remote_auth",
                sharedSecret: "secret",
                mountPoint: "http://myapp.example.com"
            }));

            this.requestWithToken = function(token, cb) {
                request(this.app)
                .get("/fooroute?foo=bar&jwt=" + token)
                .end(cb);
            }.bind(this);
        });

        it("sets jwt token to session object", function(done){
            this.app.get("/fooroute", function(req, res) {
                res.end("ok");
                assert(req.session.jwt, "jwt is on session object");
                assert.equal(req.session.jwt.foo, "bar");
                assert.equal(req.query.foo, "bar", "persist query values");
                done();
            });

            var token = jwt.encode({
                iat: now(),
                foo: "bar"
            }, "secret");

            this.requestWithToken(token, function(err, res) {
                if (err) done(err);
                assert(res.headers.location, "got redirect");
                request(this.app)
                .get(res.headers.location)
                .set("cookie", res.headers["set-cookie"])
                .end(function(err) {
                    if (err) done(err);
                });
            }.bind(this));
        });

        it("emits error for invalid shared secret", function(done){
            this.app.use(function(err, req, res, next) {
                assert(err);
                assert.equal(err.message, "Signature verification failed");
                done();
            });

            var token = jwt.encode({
                iat: now(),
                foo: "bar"
            }, "invalid");

            this.requestWithToken(token, function(err) {
                if (err) done(err);
            });
        });

        it("emits error for too old token", function(done){
            this.app.use(function(err, req, res, next) {
                assert(err);
                assert.equal(err.message, "token is too old");
                done();
            });

            var token = jwt.encode({
                iat: now() - 300,
                foo: "bar"
            }, "secret");

            this.requestWithToken(token, function(err) {
                if (err) done(err);
            });
        });

        it("emits error for expired tokens", function(done){
            this.app.use(function(err, req, res, next) {
                assert(err);
                assert.equal(err.message, "token has expired");
                done();
            });

            var token = jwt.encode({
                iat: now() - 40,
                exp: now() - 3,
                foo: "bar"
            }, "secret");

            this.requestWithToken(token, function(err) {
                if (err) done(err);
            });
        });

    });

    describe("hook options", function() {
        beforeEach(function() {
            this.app = express();
            this.app.use(express.cookieParser());
            this.app.use(express.session({ secret: "secret" }));
            this.app.use(puavo({
                authEndpoint: "https://authserver.opinsys.net/v3/remote_auth",
                sharedSecret: "secret",
                mountPoint: "http://myapp.example.com",
                hook: function(token, done) {
                    testHookRunCount += 1;
                    assert.equal(token.foo, "bar");
                    done();
                }
            }));

            this.requestWithToken = function(token, cb) {
                request(this.app)
                .get("/fooroute?foo=bar&jwt=" + token)
                .end(cb);
            }.bind(this);
        });

        it("hook function is ran", function(done) {
            this.app.get("/fooroute", function(req, res) {
                res.end("ok");
                done();
            });

            var token = jwt.encode({
                iat: now(),
                foo: "bar"
            }, "secret");

            this.requestWithToken(token, function(err, res) {
                if (err) return done(err);

                assert.equal(testHookRunCount, 1);

                request(this.app)
                .get(res.headers.location)
                .end(function(err) {
                    if (err) return done(err);
                    assert.equal(testHookRunCount, 1, "hook should be called only once");
                });
            }.bind(this));
        });
    });

});
<commit_msg>fix tests<commit_after>/* global describe, it, beforeEach */
var assert = require("assert");
var url = require("url");
var express = require("express");
var request = require("supertest");
var jwt = require("jwt-simple");

var puavo = require("../index");
var testHookRunCount = 0;

function now() {
    return Math.round(Date.now() / 1000);
}

describe("connect-puavo", function(){

    describe("res.requestJwt()", function() {
        beforeEach(function() {
            this.app = express();
            this.app.use(express.cookieParser());
            this.app.use(express.session({ secret: "secret" }));
            this.app.use(puavo({
                authEndpoint: "https://authserver.opinsys.net/v3/remote_auth",
                sharedSecret: "secret",
                host: "myapp.example.com"
            }));
        });

        it("redirects to auth server when called from route", function(done){

            this.app.get("/foo", function(req, res) {
                res.requestJwt();
            });

            request(this.app)
            .get("/foo")
            .end(function(err, res) {
                if (err) throw err;
                assert(res.headers.location, "got redirect");
                var redirUrl = url.parse(res.headers.location, true);
                assert.equal(redirUrl.host, "authserver.opinsys.net");
                assert.equal(redirUrl.pathname, "/v3/remote_auth");
                assert.equal(redirUrl.query.return_to, "http://myapp.example.com/foo");
                done();

            });
        });

        it("can set custom path", function(done){
            this.app.get("/foo", function(req, res) {
                res.requestJwt("/custom/path");
            });

            request(this.app)
            .get("/foo")
            .end(function(err, res) {
                if (err) throw err;
                assert(res.headers.location, "got redirect");
                var redirUrl = url.parse(res.headers.location, true);
                assert.equal(redirUrl.query.return_to, "http://myapp.example.com/custom/path");
                done();
            });
        });

        it("can set custom path with query string", function(done){
            this.app.get("/foo", function(req, res) {
                res.requestJwt("/custom/path?my=query");
            });

            request(this.app)
            .get("/foo")
            .end(function(err, res) {
                if (err) throw err;
                assert(res.headers.location, "got redirect");
                var redirUrl = url.parse(res.headers.location, true);
                assert.equal(redirUrl.query.return_to, "http://myapp.example.com/custom/path?my=query");
                done();
            });
        });

    });

    describe("jwt", function() {
        beforeEach(function() {
            this.app = express();
            this.app.use(express.cookieParser());
            this.app.use(express.session({ secret: "secret" }));
            this.app.use(puavo({
                authEndpoint: "https://authserver.opinsys.net/v3/remote_auth",
                sharedSecret: "secret",
                mountPoint: "http://myapp.example.com"
            }));

            this.requestWithToken = function(token, cb) {
                request(this.app)
                .get("/fooroute?foo=bar&jwt=" + token)
                .end(cb);
            }.bind(this);
        });

        it("sets jwt token to session object", function(done){
            this.app.get("/fooroute", function(req, res) {
                res.end("ok");
                assert(req.session.jwt, "jwt is on session object");
                assert.equal(req.session.jwt.foo, "bar");
                assert.equal(req.query.foo, "bar", "persist query values");
                done();
            });

            var token = jwt.encode({
                iat: now(),
                foo: "bar"
            }, "secret");

            this.requestWithToken(token, function(err, res) {
                if (err) done(err);
                assert(res.headers.location, "got redirect");
                request(this.app)
                .get(res.headers.location)
                .set("cookie", res.headers["set-cookie"])
                .end(function(err) {
                    if (err) done(err);
                });
            }.bind(this));
        });

        it("emits error for invalid shared secret", function(done){
            this.app.use(function(err, req, res, next) {
                assert(err);
                assert.equal(err.message, "Signature verification failed");
                done();
            });

            var token = jwt.encode({
                iat: now(),
                foo: "bar"
            }, "invalid");

            this.requestWithToken(token, function(err) {
                if (err) done(err);
            });
        });

        it("emits error for too old token", function(done){
            this.app.use(function(err, req, res, next) {
                assert(err);
                assert.equal(err.message, "token is too old");
                done();
            });

            var token = jwt.encode({
                iat: now() - 300,
                foo: "bar"
            }, "secret");

            this.requestWithToken(token, function(err) {
                if (err) done(err);
            });
        });

        it("emits error for expired tokens", function(done){
            this.app.use(function(err, req, res, next) {
                assert(err);
                assert.equal(err.message, "token has expired");
                done();
            });

            var token = jwt.encode({
                iat: now() - 40,
                exp: now() - 3,
                foo: "bar"
            }, "secret");

            this.requestWithToken(token, function(err) {
                if (err) done(err);
            });
        });

    });

    describe("hook options", function() {
        beforeEach(function() {
            this.app = express();
            this.app.use(express.cookieParser());
            this.app.use(express.session({ secret: "secret" }));
            this.app.use(puavo({
                authEndpoint: "https://authserver.opinsys.net/v3/remote_auth",
                sharedSecret: "secret",
                mountPoint: "http://myapp.example.com",
                hook: function(token, done) {
                    testHookRunCount += 1;
                    assert.equal(token.foo, "bar");
                    done();
                }
            }));

            this.requestWithToken = function(token, cb) {
                request(this.app)
                .get("/fooroute?foo=bar&jwt=" + token)
                .end(cb);
            }.bind(this);
        });

        it("hook function is ran", function(done) {
            this.app.get("/fooroute", function(req, res) {
                res.end("ok");
                done();
            });

            var token = jwt.encode({
                iat: now(),
                foo: "bar"
            }, "secret");

            this.requestWithToken(token, function(err, res) {
                if (err) return done(err);

                assert.equal(testHookRunCount, 1);

                request(this.app)
                .get(res.headers.location)
                .end(function(err) {
                    if (err) return done(err);
                    assert.equal(testHookRunCount, 1, "hook should be called only once");
                });
            }.bind(this));
        });
    });

});
<|endoftext|>


<commit_before>/*The following vars are used for different parameters of generated tree:

mainBranch = the main generated branch
subBranches = the sub branches that are generated "infinitely"
travel = the "distance" the branches will travel
branchWidth = Width of the stroke generated branches - keep in mind they
get exponentially thinner and thinner as recursion continues
startX, StartY, endX, endY = Defines path starting and ending values
length = length of each new tree relative to window
angle = angle of path of each new tree

I annotated the code so you can follow along!
*/

void function () {
	//Declare variables travel, branchWidth, canvas, and the canvas context
	var travel = 100 , branchWidth = 10
	//Draw canvas and set 2D context
	var canvas = document.getElementById('mycanvas')
	var ctx = canvas.getContext('2d')
	//set width and height of canvas to fill screen
	canvas.width = window.innerWidth
	canvas.height = window.innerHeight
  ctx.globalCompositeOperation;
	var fractalTree = function () {
		/* accesses clearRect() method of Canvas's 2d API with starting point (0,0) and size set to window.innerWidth
		and .innerHeight
		*/
		ctx.clearRect(0, 0, window.innerWidth, window.innerHeight)
		//Defines placement of tree relative to window, also
		drawTree(ctx, (window.innerWidth/2), (window.innerHeight/1), 40, -Math.PI/2, travel+10, branchWidth)
	}
	//Define drawTree var as function that has following variables as parameters
	var drawTree = function (ctx, startX, startY, length, angle, travel, branchWidth) {
		var rand = Math.random, dept,
			newLength, newAngle,
			mainBranch = 3,
			endX, endY, maxAngle = Math.PI /2;
		//Creates new canvas path
		ctx.beginPath()
		//Sets new trees to defined x and y coordinates - placed in center
		ctx.moveTo(startX, startY)
		//defines x and y end values by start values
		endX = startX + length * Math.cos(angle)
		endY = startY + length * Math.sin(angle)
		//uses lineCap canvas property to round the lines
		ctx.lineCap = 'round'
		ctx.lineWidth = branchWidth
		ctx.lineTo(endX, endY)
		//sets white color for generated tree and branches
		ctx.strokeStyle = 'white'
		ctx.stroke()
		newTravel = travel
		if (!newTravel) return
		subBranches = mainBranch -1
		/*This is where the recursion really occurs!
		Each new child branch is 7/10 the size of its parent branch,
		so they are generated infinitely until they "fizzle out". */
		branchWidth *= .7
		for (var i = 0; i < subBranches; i++) {
			/*set new angles defined by a formula
			that is based on the max angle multiplied by a random value.
			The value can't be negative because the branches will turn in onto themselves!
			*/
			newAngle = angle + rand()*maxAngle - maxAngle*.5
			newLength = length * (.7 + rand()*.5)
			/*uses setTimeout method with input as the drawTree function that draws tree
			and its parameters. Expression is evaluated after 60 ms.
			*/
			setTimeout(function () {
				drawTree(ctx, endX, endY, newLength, newAngle, newTravel, branchWidth);
				}, 60)
		}
	}
	/*adds event listener that detects whether DOM has loaded, runs fractalTree regardless if content has loaded
	so it triggers quicker */
	document.addEventListener('DOMContentLoaded',function(){
		fractalTree()
	}, false);
}();
<commit_msg>Update index.js<commit_after>/*The following vars are used for different parameters of generated tree and can searched easily:

mainBranch = the main generated branch
subBranches = the sub branches that are generated "infinitely"
travel = the "distance" the branches will travel
branchWidth = Width of the stroke generated branches - keep in mind they
get exponentially thinner and thinner as recursion continues
startX, StartY, endX, endY = Defines path starting and ending values
length = length of each new tree relative to window
angle = angle of path of each new tree

I annotated the code so you can follow along!
*/

void function () {
	//Declare variables travel, branchWidth, canvas, and the canvas context
	var travel = 100 , branchWidth = 10
	//Draw canvas and set 2D context
	var canvas = document.getElementById('mycanvas')
	var ctx = canvas.getContext('2d')
	//set width and height of canvas to fill screen
	canvas.width = window.innerWidth
	canvas.height = window.innerHeight
  ctx.globalCompositeOperation;
	var fractalTree = function () {
		/* accesses clearRect() method of Canvas's 2d API with starting point (0,0) and size set to window.innerWidth
		and .innerHeight
		*/
		ctx.clearRect(0, 0, window.innerWidth, window.innerHeight)
		//Defines placement of tree relative to window, also
		drawTree(ctx, (window.innerWidth/2), (window.innerHeight/1), 40, -Math.PI/2, travel+10, branchWidth)
	}
	//Define drawTree var as function that has following variables as parameters
	var drawTree = function (ctx, startX, startY, length, angle, travel, branchWidth) {
		var rand = Math.random, dept,
			newLength, newAngle,
			mainBranch = 3,
			endX, endY, maxAngle = Math.PI /2;
		//Creates new canvas path
		ctx.beginPath()
		//Sets new trees to defined x and y coordinates - placed in center
		ctx.moveTo(startX, startY)
		//defines x and y end values by start values
		endX = startX + length * Math.cos(angle)
		endY = startY + length * Math.sin(angle)
		//uses lineCap canvas property to round the lines
		ctx.lineCap = 'round'
		ctx.lineWidth = branchWidth
		ctx.lineTo(endX, endY)
		//sets white color for generated tree and branches
		ctx.strokeStyle = 'white'
		ctx.stroke()
		newTravel = travel
		if (!newTravel) return
		subBranches = mainBranch -1
		/*This is where the recursion really occurs!
		Each new child branch is 7/10 the size of its parent branch,
		so they are generated infinitely until they "fizzle out". */
		branchWidth *= .7
		for (var i = 0; i < subBranches; i++) {
			/*set new angles defined by a formula
			that is based on the max angle multiplied by a random value.
			The value can't be negative because the branches will turn in onto themselves!
			*/
			newAngle = angle + rand()*maxAngle - maxAngle*.5
			newLength = length * (.7 + rand()*.5)
			/*uses setTimeout method with input as the drawTree function that draws tree
			and its parameters. Expression is evaluated after 60 ms.
			*/
			setTimeout(function () {
				drawTree(ctx, endX, endY, newLength, newAngle, newTravel, branchWidth);
				}, 60)
		}
	}
	/*adds event listener that detects whether DOM has loaded, runs fractalTree regardless if content has loaded
	so it triggers quicker */
	document.addEventListener('DOMContentLoaded',function(){
		fractalTree()
	}, false);
}();
<|endoftext|>


<commit_before>import factory from './factory/grid-factory';

module.exports = {
  version: '0.1.0-30',
  GridView: require('./grid-view'),
  projections: require('./projection/index'),
  layout: require('./layout/index'),
  factory,
  popupEditorPrompt: require('./popup-editor/index'),
};
<commit_msg>change the version in index.js<commit_after>import factory from './factory/grid-factory';

module.exports = {
  version: '0.1.0-31',
  GridView: require('./grid-view'),
  projections: require('./projection/index'),
  layout: require('./layout/index'),
  factory,
  popupEditorPrompt: require('./popup-editor/index'),
};
<|endoftext|>


<commit_before>// var namebtn=document.getElementById("namediv");
// var picdiv=document.getElementById('picdiv');
// namebtn.onclick=function(){
// 	alert("welcome to my webside");
// };
var namebtn=$('#namediv');
var images=$('.image');
var picdiv=$('#picdiv');

var sideimage=$('sideimage');

namebtn.click(function(){
	alert('welcome!');
});

$(function() {
    $('.banner').unslider();
});

$('.banner').unslider({
	speed: 500,               //  The speed to animate each slide (in milliseconds)
	delay: 1000,              //  The delay between slide animations (in milliseconds)
	complete: function() {},  //  A function that gets called after every slide animation
	keys: true,               //  Enable keyboard (left, right) arrow shortcuts
	dots: true,               //  Display dot navigation
	fluid: false              //  Support responsive design. May break non-responsive designs
});

$('document').load(function(){
	$.get('https://api.github.com/gists/1f4d05e72c615872dd5c',function(data,status){
		if(status==200){
			var responsejson=eval("("+data+")");
			sideimage.html(responsejson.content);
		}
	});
});<commit_msg>update<commit_after>// var namebtn=document.getElementById("namediv");
// var picdiv=document.getElementById('picdiv');
// namebtn.onclick=function(){
// 	alert("welcome to my webside");
// };
var namebtn=$('#namediv');
var images=$('.image');
var picdiv=$('#picdiv');

var sideimage=$('sideimage');

namebtn.click(function(){
	alert('welcome!');
});

$(function() {
    $('.banner').unslider();
});

$('.banner').unslider({
	speed: 500,               //  The speed to animate each slide (in milliseconds)
	delay: 1000,              //  The delay between slide animations (in milliseconds)
	complete: function() {},  //  A function that gets called after every slide animation
	keys: true,               //  Enable keyboard (left, right) arrow shortcuts
	dots: true,               //  Display dot navigation
	fluid: false              //  Support responsive design. May break non-responsive designs
});

$('document').load(function(){
	$.get('https://api.github.com/gists/1f4d05e72c615872dd5c',function(data,status){
		if(status==200){
			var responsejson=eval("("+data+")");
			alert(responsejson);
			sideimage.html(responsejson.content);
		}
	});
});<|endoftext|>