<commit_before>"use strict";
const http = require('http');
const fs = require('fs');
const path = require('path');
const reactEngine = require('react-engine');
var app = require('http').createServer(handler)
var io = require('socket.io')(app);

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
  	console.log(err);
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection', function(socket){
  console.log('a user connected');

  socket.on('Response', function(data) {
  	//Send data to presenter
  	socket.emit('responseDate', data);
  })

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});<commit_msg>conflicts resolved<commit_after>"use strict";
const http = require('http');
const fs = require('fs');
const path = require('path');
const reactEngine = require('react-engine');
var app = require('http').createServer(handler)
var io = require('socket.io')(app);

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
  	console.log(err);
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection', function(socket){
  console.log('a user connected');

  socket.on('Response', function(data) {
  	//Send data to presenter
  	socket.emit('responseDate', data);

  })

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});<|endoftext|>


<commit_before>var assert = require("assert");
describe('sanitizeHtml', function() {
  var sanitizeHtml;
  it('should be successfully initialized', function() {
    sanitizeHtml = require('../index.js');
  });
  it('should pass through simple well-formed whitelisted markup', function() {
    assert.equal(sanitizeHtml('

Hello there

'), '

Hello there

');
  });
  it('should respect text nodes at top level', function() {
    assert.equal(sanitizeHtml('Blah blah blah
Whee!
'), 'Blah blah blah
Whee!
');
  });
  it('should reject markup not whitelisted without destroying its text', function() {
    assert.equal(sanitizeHtml('
<wiggly>Hello</wiggly>
'), '
Hello
');
  });
  it('should accept a custom list of allowed tags', function() {
    assert.equal(sanitizeHtml('<blue><red><green>Cheese</green></red></blue>', { allowedTags: [ 'blue', 'green' ] }), '<blue><green>Cheese</green></blue>');
  });
  it('should reject attributes not whitelisted', function() {
    assert.equal(sanitizeHtml('foo'), 'foo');
  });
  it('should accept a custom list of allowed attributes per element', function() {
    assert.equal(sanitizeHtml('foo', { allowedAttributes: { a: [ 'href', 'whizbang' ] } } ), 'foo');
  });
  it('should clean up unclosed img tags and p tags', function() {
    assert.equal(sanitizeHtml('
Whee
Again
Wowcool', { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ])}), '
Whee

Again

Wowcool
');
  });
  it('should reject hrefs that are not relative, ftp, http, https or mailto', function() {
    assert.equal(sanitizeHtml('googlehttps googleftpmailtorelativejavascript'), 'googlehttps googleftpmailtorelativejavascript');
  });
  it('should cope identically with capitalized attributes and tags and should tolerate capitalized schemes', function() {
    assert.equal(sanitizeHtml('googlehttps googleftpmailtorelativejavascript'), 'googlehttps googleftpmailtorelativejavascript');
  });
  it('should drop the content of script elements', function() {
    assert.equal(sanitizeHtml('
Paragraph
'), '
Paragraph
');
  });
  it('should drop the content of style elements', function() {
    assert.equal(sanitizeHtml('
Paragraph
'), '
Paragraph
');
  });
  it('should preserve entities as such', function() {
    assert.equal(sanitizeHtml('<Kapow!>'), '<Kapow!>');
  });
  it('should dump comments', function() {
    assert.equal(sanitizeHtml('
Whee
'), '
Whee
');
  });
  it('should dump a sneaky encoded javascript url', function() {
    assert.equal(sanitizeHtml('Hax'), 'Hax');
  });
  it('should dump an uppercase javascript url', function() {
    assert.equal(sanitizeHtml('Hax'), 'Hax');
  });
  it('should dump character codes 1-32 before testing scheme', function() {
    assert.equal(sanitizeHtml('Hax'), 'Hax');
  });
  it('should dump character codes 1-32 even when escaped with padding rather than trailing ;', function() {
    assert.equal(sanitizeHtml('Hax'), 'Hax');
  });
  it('should still like nice schemes', function() {
    assert.equal(sanitizeHtml('Hi'), 'Hi');
  });
  it('should still like nice relative URLs', function() {
    assert.equal(sanitizeHtml('Hi'), 'Hi');
  });
  it('should replace ol to ul', function() {
    assert.equal(sanitizeHtml('

Hello world

', { transformTags: {ol: 'ul'} }), '

Hello world

');
  });
  it('should replace ol to ul and add class attribute with foo value', function() {
    assert.equal(sanitizeHtml('

Hello world

', { transformTags: {ol: sanitizeHtml.simpleTransform('ul', {class: 'foo'})}, allowedAttributes: { ul: ['class'] } }), '

Hello world

');
  });
  it('should replace ol to ul, left attributes foo and bar untouched, remove baz attribute and add class attributte with foo value', function() {
    assert.equal(sanitizeHtml('

Hello world

', { transformTags: {ol: sanitizeHtml.simpleTransform('ul', {class: 'foo'})}, allowedAttributes: { ul: ['foo', 'bar', 'class'] } }), '

Hello world

');
  });
  it('should replace ol to ul and replace all attributes to class attribute with foo value', function() {
    assert.equal(sanitizeHtml('

Hello world

', { transformTags: {ol: sanitizeHtml.simpleTransform('ul', {class: 'foo'}, false)}, allowedAttributes: { ul: ['foo', 'bar', 'class'] } }), '

Hello world

');
  });
  it('should replace ol to ul and add attribute class with foo value and attribute bar with bar value', function() {
    assert.equal(sanitizeHtml('

Hello world

', { transformTags: {ol: function(tagName, attribs){
      attribs.class = 'foo';
      attribs.bar = 'bar';
      return {
        tagName: 'ul',
        attribs: attribs
      }
    }}, allowedAttributes: { ul: ['bar', 'class'] } }), '

Hello world

');
  });

  it('should skip an empty link', function() {
     assert.strictEqual(
     sanitizeHtml('
This is
Linux
', {
             exclusiveFilter: function (frame) {
                 return frame.tag === 'a' && !frame.text.trim();
             }
         }),
         '
This is
Linux
'
        );
    });

    it("Should expose a node's inner text and inner HTML to the filter", function() {
        assert.strictEqual(
            sanitizeHtml('
12
3
4
', {
                exclusiveFilter : function(frame) {
                    if (frame.tag === 'p') {
                        assert.strictEqual(frame.text, '124');
                    } else if (frame.tag === 'a') {
                        assert.strictEqual(frame.text, '3');
                        return true;
                    } else if (frame.tag === 'br') {
                        assert.strictEqual(frame.text, '');
                    } else {
                        assert.fail('p, a, br', frame.tag);
                    }
                    return false;
                }
            }),
            '
124
'
        );
    });

  it('Should collapse nested empty elements', function() {
        assert.strictEqual(
            sanitizeHtml('

', {
                    exclusiveFilter : function(frame) {
                        return (frame.tag === 'a' || frame.tag === 'p' ) && !frame.text.trim();
                    }
                }),
            ''
        );
  });
  it('Exclusive filter should not affect elements which do not match the filter condition', function () {
      assert.strictEqual(
          sanitizeHtml('I love Linux OS',
              {
                  exclusiveFilter: function (frame) {
                      return (frame.tag === 'a') && !frame.text.trim();
                  }
              }),
          'I love Linux OS'
      );
  });
  it('should disallow data URLs with default allowedSchemes', function() {
    assert.equal(
      sanitizeHtml(
        // teeny-tiny valid transparent GIF in a data URL
        '',
        {
          allowedTags: [ 'img' ]
        }
      ),
      ''
    );
  });
  it('should allow data URLs with custom allowedSchemes', function() {
    assert.equal(
      sanitizeHtml(
        // teeny-tiny valid transparent GIF in a data URL
        '',
        {
          allowedTags: [ 'img', 'p' ],
          allowedSchemes: [ 'data', 'http' ]
        }
      ),
      ''
    );
  });
  it('should allow specific classes when whitelisted with allowedClasses', function() {
    assert.equal(
      sanitizeHtml(
        '
whee
',
        {
          allowedTags: [ 'p' ],
          allowedClasses: {
            p: [ 'nifty' ]
          }
        }
      ),
      '
whee
'
    );
  });
  it('should not act weird when the class attribute is empty', function() {
    assert.equal(
      sanitizeHtml(
        '
whee
',
        {
          allowedTags: [ 'p' ],
          allowedClasses: {
            p: [ 'nifty' ]
          }
        }
      ),
      '
whee
'
    );
  });
  it('should not crash on bad markup', function() {
    assert.equal(
      sanitizeHtml(
        "<p a"
      ),
      ''
    );
  });
});

<commit_msg>unit tests for comments in URLs but also to make sure we don't squash legitimate uses of :<commit_after>var assert = require("assert");
describe('sanitizeHtml', function() {
  var sanitizeHtml;
  it('should be successfully initialized', function() {
    sanitizeHtml = require('../index.js');
  });
  it('should pass through simple well-formed whitelisted markup', function() {
    assert.equal(sanitizeHtml('

Hello there

'), '

Hello there

');
  });
  it('should respect text nodes at top level', function() {
    assert.equal(sanitizeHtml('Blah blah blah
Whee!
'), 'Blah blah blah
Whee!
');
  });
  it('should reject markup not whitelisted without destroying its text', function() {
    assert.equal(sanitizeHtml('
<wiggly>Hello</wiggly>
'), '
Hello
');
  });
  it('should accept a custom list of allowed tags', function() {
    assert.equal(sanitizeHtml('<blue><red><green>Cheese</green></red></blue>', { allowedTags: [ 'blue', 'green' ] }), '<blue><green>Cheese</green></blue>');
  });
  it('should reject attributes not whitelisted', function() {
    assert.equal(sanitizeHtml('foo'), 'foo');
  });
  it('should accept a custom list of allowed attributes per element', function() {
    assert.equal(sanitizeHtml('foo', { allowedAttributes: { a: [ 'href', 'whizbang' ] } } ), 'foo');
  });
  it('should clean up unclosed img tags and p tags', function() {
    assert.equal(sanitizeHtml('
Whee
Again
Wowcool', { allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ])}), '
Whee

Again

Wowcool
');
  });
  it('should reject hrefs that are not relative, ftp, http, https or mailto', function() {
    assert.equal(sanitizeHtml('googlehttps googleftpmailtorelativejavascript'), 'googlehttps googleftpmailtorelativejavascript');
  });
  it('should cope identically with capitalized attributes and tags and should tolerate capitalized schemes', function() {
    assert.equal(sanitizeHtml('googlehttps googleftpmailtorelativejavascript'), 'googlehttps googleftpmailtorelativejavascript');
  });
  it('should drop the content of script elements', function() {
    assert.equal(sanitizeHtml('
Paragraph
'), '
Paragraph
');
  });
  it('should drop the content of style elements', function() {
    assert.equal(sanitizeHtml('
Paragraph
'), '
Paragraph
');
  });
  it('should preserve entities as such', function() {
    assert.equal(sanitizeHtml('<Kapow!>'), '<Kapow!>');
  });
  it('should dump comments', function() {
    assert.equal(sanitizeHtml('
Whee
'), '
Whee
');
  });
  it('should dump a sneaky encoded javascript url', function() {
    assert.equal(sanitizeHtml('Hax'), 'Hax');
  });
  it('should dump an uppercase javascript url', function() {
    assert.equal(sanitizeHtml('Hax'), 'Hax');
  });
  it('should dump a javascript URL with a comment in the middle (probably only respected by browsers in XML data islands, but just in case someone enables those)', function() {
    assert.equal(sanitizeHtml('Hax'), 'Hax');
  });
  it('should not mess up a hashcode with a : in it', function() {
    assert.equal(sanitizeHtml('Hi'), 'Hi');
  });
  it('should dump character codes 1-32 before testing scheme', function() {
    assert.equal(sanitizeHtml('Hax'), 'Hax');
  });
  it('should dump character codes 1-32 even when escaped with padding rather than trailing ;', function() {
    assert.equal(sanitizeHtml('Hax'), 'Hax');
  });
  it('should still like nice schemes', function() {
    assert.equal(sanitizeHtml('Hi'), 'Hi');
  });
  it('should still like nice relative URLs', function() {
    assert.equal(sanitizeHtml('Hi'), 'Hi');
  });
  it('should replace ol to ul', function() {
    assert.equal(sanitizeHtml('

Hello world

', { transformTags: {ol: 'ul'} }), '

Hello world

');
  });
  it('should replace ol to ul and add class attribute with foo value', function() {
    assert.equal(sanitizeHtml('

Hello world

', { transformTags: {ol: sanitizeHtml.simpleTransform('ul', {class: 'foo'})}, allowedAttributes: { ul: ['class'] } }), '

Hello world

');
  });
  it('should replace ol to ul, left attributes foo and bar untouched, remove baz attribute and add class attributte with foo value', function() {
    assert.equal(sanitizeHtml('

Hello world

', { transformTags: {ol: sanitizeHtml.simpleTransform('ul', {class: 'foo'})}, allowedAttributes: { ul: ['foo', 'bar', 'class'] } }), '

Hello world

');
  });
  it('should replace ol to ul and replace all attributes to class attribute with foo value', function() {
    assert.equal(sanitizeHtml('

Hello world

', { transformTags: {ol: sanitizeHtml.simpleTransform('ul', {class: 'foo'}, false)}, allowedAttributes: { ul: ['foo', 'bar', 'class'] } }), '

Hello world

');
  });
  it('should replace ol to ul and add attribute class with foo value and attribute bar with bar value', function() {
    assert.equal(sanitizeHtml('

Hello world

', { transformTags: {ol: function(tagName, attribs){
      attribs.class = 'foo';
      attribs.bar = 'bar';
      return {
        tagName: 'ul',
        attribs: attribs
      }
    }}, allowedAttributes: { ul: ['bar', 'class'] } }), '

Hello world

');
  });

  it('should skip an empty link', function() {
     assert.strictEqual(
     sanitizeHtml('
This is
Linux
', {
             exclusiveFilter: function (frame) {
                 return frame.tag === 'a' && !frame.text.trim();
             }
         }),
         '
This is
Linux
'
        );
    });

    it("Should expose a node's inner text and inner HTML to the filter", function() {
        assert.strictEqual(
            sanitizeHtml('
12
3
4
', {
                exclusiveFilter : function(frame) {
                    if (frame.tag === 'p') {
                        assert.strictEqual(frame.text, '124');
                    } else if (frame.tag === 'a') {
                        assert.strictEqual(frame.text, '3');
                        return true;
                    } else if (frame.tag === 'br') {
                        assert.strictEqual(frame.text, '');
                    } else {
                        assert.fail('p, a, br', frame.tag);
                    }
                    return false;
                }
            }),
            '
124
'
        );
    });

  it('Should collapse nested empty elements', function() {
        assert.strictEqual(
            sanitizeHtml('

', {
                    exclusiveFilter : function(frame) {
                        return (frame.tag === 'a' || frame.tag === 'p' ) && !frame.text.trim();
                    }
                }),
            ''
        );
  });
  it('Exclusive filter should not affect elements which do not match the filter condition', function () {
      assert.strictEqual(
          sanitizeHtml('I love Linux OS',
              {
                  exclusiveFilter: function (frame) {
                      return (frame.tag === 'a') && !frame.text.trim();
                  }
              }),
          'I love Linux OS'
      );
  });
  it('should disallow data URLs with default allowedSchemes', function() {
    assert.equal(
      sanitizeHtml(
        // teeny-tiny valid transparent GIF in a data URL
        '',
        {
          allowedTags: [ 'img' ]
        }
      ),
      ''
    );
  });
  it('should allow data URLs with custom allowedSchemes', function() {
    assert.equal(
      sanitizeHtml(
        // teeny-tiny valid transparent GIF in a data URL
        '',
        {
          allowedTags: [ 'img', 'p' ],
          allowedSchemes: [ 'data', 'http' ]
        }
      ),
      ''
    );
  });
  it('should allow specific classes when whitelisted with allowedClasses', function() {
    assert.equal(
      sanitizeHtml(
        '
whee
',
        {
          allowedTags: [ 'p' ],
          allowedClasses: {
            p: [ 'nifty' ]
          }
        }
      ),
      '
whee
'
    );
  });
  it('should not act weird when the class attribute is empty', function() {
    assert.equal(
      sanitizeHtml(
        '
whee
',
        {
          allowedTags: [ 'p' ],
          allowedClasses: {
            p: [ 'nifty' ]
          }
        }
      ),
      '
whee
'
    );
  });
  it('should not crash on bad markup', function() {
    assert.equal(
      sanitizeHtml(
        "<p a"
      ),
      ''
    );
  });
});

<|endoftext|>


<commit_before>const utils = require('./utils')

process.chdir(path.join(__dirname, ".."));

[
  "build_js",
  "build_css",
  "build_doc",
].forEach(task => utils.npm_run(task));
<commit_msg>Fix a stupod problem<commit_after>const path = require('path')
const utils = require('./utils')

process.chdir(path.join(__dirname, ".."));

[
  "build_js",
  "build_css",
  "build_doc",
].forEach(task => utils.npm_run(task));
<|endoftext|>


<commit_before>$(function() {

    function initialize() {
        var markerTemplate,
            mapDiv = document.getElementById('map-canvas'),
            map,
            markers = [];

        // Get one metadata point to see if they have coordinates
        var metaJsonUrls = _.map($('a.meta'), function(a) {
            return $(a).attr('href');
        });
        var metaJsonUrl = metaJsonUrls.shift().replace('.html', '.json');

        function mapMetadata(metadata) {
            var latitude = metadata.latitude,
                longitude = metadata.longitude,
            latlng;

            latlng = new google.maps.LatLng(
                Number(latitude),
                Number(longitude)
            );

            markers.push(new google.maps.Marker({
                position: latlng,
                map: map,
                title: '{{metadata.id}}'
            }));

            map.setCenter(latlng);

        }

        $.getJSON(metaJsonUrl, function(data) {
            var fetchers = [];

            if (data.metadata.latitude && data.metadata.longitude) {
                $(mapDiv).removeClass('hidden');
                map = new google.maps.Map(mapDiv, {
                    zoom: 11
                })
                $.get(baseurl + '/static/templates/partials/markerLabel/index.html', function(response) {
                    markerTemplate = response;
                    mapMetadata(data.metadata);
                    _.each(metaJsonUrls, function(htmlUrl) {
                        var jsonUrl = htmlUrl.replace('.html', '.json');
                        fetchers.push(function(callback) {
                            $.getJSON(jsonUrl, function(data) {
                                if (data && data.metadata) {
                                    mapMetadata(data.metadata);
                                }
                                callback();
                            });
                        });
                    });
                    async.parallel(fetchers);
                });

            }
        });

    }
    google.maps.event.addDomListener(window, 'load', initialize);

        //$.get('{{ baseurl }}/static/templates/partials/markerLabel/index.html', function(response) {
        //        markerTemplate = response;
        //
        //        var latitude = {{metadata.latitude}},
        //            longitude = {{metadata.longitude}},
        //    latlng, marker, markerData = {};
        //
        //    latlng = new google.maps.LatLng(
        //        Number(latitude),
        //        Number(longitude)
        //    );
        //
        //    marker = new google.maps.Marker({
        //        position: latlng,
        //        map: map,
        //        animation: google.maps.Animation.DROP,
        //        title: '{{metadata.id}}'
        //    });
        //
        //    map.setCenter(latlng);
        //
        //});
        //
        //}

});<commit_msg>Small perf improvement to stream maps.<commit_after>$(function() {

    function initialize() {
        var mapDiv = document.getElementById('map-canvas'),
            map,
            markers = [];

        // Get one metadata point to see if they have coordinates
        var metaJsonUrls = _.map($('a.meta'), function(a) {
            return $(a).attr('href');
        });
        var metaJsonUrl = metaJsonUrls.shift().replace('.html', '.json');

        function mapMetadata(metadata, center) {
            var latitude = metadata.latitude,
                longitude = metadata.longitude,
                latlng;

            latlng = new google.maps.LatLng(
                Number(latitude),
                Number(longitude)
            );

            markers.push(new google.maps.Marker({
                position: latlng,
                map: map,
                title: '{{metadata.id}}'
            }));

            if (center) {
                map.setCenter(latlng);
            }

        }

        $.getJSON(metaJsonUrl, function(data) {
            var fetchers = [];

            if (data.metadata.latitude && data.metadata.longitude) {

                $(mapDiv).removeClass('hidden');
                map = new google.maps.Map(mapDiv, {
                    zoom: 11
                });

                mapMetadata(data.metadata, true);
                _.each(metaJsonUrls, function(htmlUrl) {
                    var jsonUrl = htmlUrl.replace('.html', '.json');
                    fetchers.push(function(callback) {
                        $.getJSON(jsonUrl, function(data) {
                            if (data && data.metadata) {
                                mapMetadata(data.metadata);
                            }
                            callback();
                        });
                    });
                });
                async.parallel(fetchers);

            }
        });

    }
    google.maps.event.addDomListener(window, 'load', initialize);

        //$.get('{{ baseurl }}/static/templates/partials/markerLabel/index.html', function(response) {
        //        markerTemplate = response;
        //
        //        var latitude = {{metadata.latitude}},
        //            longitude = {{metadata.longitude}},
        //    latlng, marker, markerData = {};
        //
        //    latlng = new google.maps.LatLng(
        //        Number(latitude),
        //        Number(longitude)
        //    );
        //
        //    marker = new google.maps.Marker({
        //        position: latlng,
        //        map: map,
        //        animation: google.maps.Animation.DROP,
        //        title: '{{metadata.id}}'
        //    });
        //
        //    map.setCenter(latlng);
        //
        //});
        //
        //}

});<|endoftext|>


<commit_before>// ------------------------------------------------------------------------------------
//
// Fading through all content inside the class 'divfader'
//
// ------------------------------------------------------------------------------------
// ----------------------- INSTRUCTIONS -----------------------------------------------
// For the script to work properly, use class "divfader" as container.
// Place divs/objects you want to include in the slider in class "divfader-content".
// Controls/dots will be created in class "divfader-controller".
// For next/previous-controls, use class "divfader-next" and "divfader-previous".
// ------------------------------------------------------------------------------------

// Playback variables
var autoplay = true;
var showControls = true;
var fadeTimer = 400;
var delay = 2000;

var content = $('.divfader-content').children().hide();
var controls;
var	current = content.length-1;
var timeout;

// ------------------------
// Initialization
// ------------------------
// Onload
$(function() {
	if (showControls) {
		initializeControls();
	}

	if (autoplay) cycle();
	else showSlide(0);
});

// Initialize controls (dots)
function initializeControls() {
	// Add divfader-controller to DOM (if it doesn't exist)
	if (!$('.divfader').children().hasClass('divfader-controller')) {
		$('.divfader').append('

');
	}

	// Add controls to DOM
	for (n = 0; n < content.length; n++) {
		$('.divfader-controller').append('

');
	}

	// Save controls
	controls = $('.divfader-controller').children();
}

// ------------------------
// Actions
// ------------------------
// Controller clicked (dot)
$('.divfader-controller').on('click',function(event){
	abortCycle();
    showSlide($(event.target).index(), true);
});

// Next clicked
$('.divfader-next').on('click',function(event){
	abortCycle();
    nextSlide(true);
});

// Previous clicked
$('.divfader-previous').on('click',function(event){
	abortCycle();
    previousSlide(true);
});

// Cycle through slides
function cycle() {
	// Fade in next slide, recursively
    nextSlide();
    if (autoplay) {
    	timeout = setTimeout(cycle, delay+fadeTimer);
    }
}

// ------------------------
// Playback functions
// ------------------------
// Show specific slide
// Responsive will ensure that controls are updated instantly
function showSlide(slideId, responsive) {
	// Stop all other animations
	content.stop();

	// Responsive controls
	if (responsive) setActiveControl(slideId);

	// Fade out previous slide
	slide = content.eq(current);
	slide.fadeOut(fadeTimer, function() {
		current = slideId;

		// Update controls normally
		if (!responsive) setActiveControl(slideId);

		// Fade in
		slide = content.eq(slideId);
	    slide.fadeIn(fadeTimer);
	});
}

// Show next slide
// Responsive will ensure that controls are updated instantly
function nextSlide(responsive) {
	showSlide((current+1) % content.length, responsive);
}

// Show previous slide
// Responsive will ensure that controls are updated instantly
function previousSlide(responsive) {
	showSlide((current-1) % content.length, responsive);
}

// Set active control (dot)
function setActiveControl(id) {
	if (showControls){
		controls.removeClass("divfader-control-active").addClass("divfader-control");
		controls.eq(id).removeClass("divfader-control").addClass("divfader-control-active");
	}
}

// Abort autoplay cycle
function abortCycle() {
	autoplay = false;
	clearTimeout(timeout);
}
<commit_msg>Fix for #2<commit_after>// ------------------------------------------------------------------------------------
//
// Fading through all content inside the class 'divfader'
//
// ------------------------------------------------------------------------------------
// ----------------------- INSTRUCTIONS -----------------------------------------------
// For the script to work properly, use class "divfader" as container.
// Place divs/objects you want to include in the slider in class "divfader-content".
// Controls/dots will be created in class "divfader-controller".
// For next/previous-controls, use class "divfader-next" and "divfader-previous".
// ------------------------------------------------------------------------------------

// Playback variables
var autoplay = true;
var showControls = true;
var fadeTimer = 400;
var delay = 2000;

var content = $('.divfader-content').children().hide();
var controls;
var	current = content.length-1;
var timeout;

// ------------------------
// Initialization
// ------------------------
// Onload
$(function() {
	if (showControls) {
		initializeControls();
	}

	if (autoplay) cycle();
	else showSlide(0);
});

// Initialize controls (dots)
function initializeControls() {
	// Add divfader-controller to DOM (if it doesn't exist)
	if (!$('.divfader').children().hasClass('divfader-controller')) {
		$('.divfader').append('

');
	}

	// Add controls to DOM
	for (n = 0; n < content.length; n++) {
		$('.divfader-controller').append('

');
	}

	// Save controls
	controls = $('.divfader-controller').children();
}

// ------------------------
// Actions
// ------------------------
// Controller clicked (dot)
$('.divfader-controller').on('click', '*', function(event){
	abortCycle();
    showSlide($(event.target).index(), true);
});

// Next clicked
$('.divfader-next').on('click',function(event){
	abortCycle();
    nextSlide(true);
});

// Previous clicked
$('.divfader-previous').on('click',function(event){
	abortCycle();
    previousSlide(true);
});

// Cycle through slides
function cycle() {
	// Fade in next slide, recursively
    nextSlide();
    if (autoplay) {
    	timeout = setTimeout(cycle, delay+fadeTimer);
    }
}

// ------------------------
// Playback functions
// ------------------------
// Show specific slide
// Responsive will ensure that controls are updated instantly
function showSlide(slideId, responsive) {
	// Stop all other animations
	content.stop();

	// Responsive controls
	if (responsive) setActiveControl(slideId);

	// Fade out previous slide
	slide = content.eq(current);
	slide.fadeOut(fadeTimer, function() {
		current = slideId;

		// Update controls normally
		if (!responsive) setActiveControl(slideId);

		// Fade in
		slide = content.eq(slideId);
	    slide.fadeIn(fadeTimer);
	});
}

// Show next slide
// Responsive will ensure that controls are updated instantly
function nextSlide(responsive) {
	showSlide((current+1) % content.length, responsive);
}

// Show previous slide
// Responsive will ensure that controls are updated instantly
function previousSlide(responsive) {
	showSlide((current-1) % content.length, responsive);
}

// Set active control (dot)
function setActiveControl(id) {
	if (showControls){
		controls.removeClass("divfader-control-active").addClass("divfader-control");
		controls.eq(id).removeClass("divfader-control").addClass("divfader-control-active");
	}
}

// Abort autoplay cycle
function abortCycle() {
	autoplay = false;
	clearTimeout(timeout);
}
<|endoftext|>


<commit_before>import { getToggleDM } from '../getSettings.js';

const deleteCmd = (stopClient, msg, cmd, subcmd, thirdcmd, admin, mod, thisGuild, stopList, deleteList, isStopped, isDeleted, richEmbed) => {
  const reserved = ['help', 'info', 'updates', 'stop', 'delete', 'go', 'set', 'fish', 'inv', 'prefix', 'video'];
  if (!subcmd) return;
  if (reserved.indexOf(subcmd) !== -1) {
    msg.channel.send({
      embed: richEmbed.setColor('#ff0000').setDescription(`This word is reserved for bot functionality and cannot be deleted.`)
    });
    return;
  } else if (subcmd === 'list') {
    if (deleteList.length !== 0) {
      getToggleDM(stopClient, msg).then(enabled => {
        if (enabled) {
          msg.member.createDM()
            .then(channel => {
              channel.send('These words are currently being deleted: `' + deleteList.join(', ') + '`');
            });
        } else {
          msg.channel.send('These words are currently being deleted: `' + deleteList.join(', ') + '`');
        }
      });
    } else {
      msg.channel.send('There are no words on the delete list.')
    }
  } else if (!isNaN(subcmd)) {
    let limit = parseInt(subcmd) + 1;
    if (limit >= 100) {
      msg.channel.send({
        embed: richEmbed.setColor('#ff0000').setDescription(`Number of messages must be under 100.`)
      });
      return;
    }
    msg.channel.fetchMessages({limit: limit})
      .then((latestMessages) => {
        let mentions = msg.mentions.users;
        let mentionsNum = msg.mentions.users.array().length;
        if (mentionsNum === 0) msg.channel.bulkDelete(latestMessages);
        else {
          let latestByUser = latestMessages.filter((message) => message.author === mentions.first());
          msg.channel.bulkDelete(latestByUser);
        }
      })
      .catch(err => console.log(err));
  } else if (subcmd && isNaN(subcmd)) {
    if (admin) {
      if (isDeleted) {
        msg.channel.send('`' + subcmd + '`' + ' is already on the list of words to delete.');
      } else if (isStopped) {
        msg.channel.send('`' + subcmd + '`' + ' is already on the list of words to stop.');
      } else {
        stopClient.query(`UPDATE word_lists SET deletelist = deletelist || '{${subcmd.toLowerCase()}}' WHERE serverid=${thisGuild}`);
        msg.channel.send('`' + subcmd + '`' + ' will be deleted every time it appears.');
      }
    } else if (!admin) {
      msg.reply('you can\'t use this command.');
    }
  } else {
    return;
  }
}

export default deleteCmd;
<commit_msg>Fix permissions for bulk deletion<commit_after>import { getToggleDM } from '../getSettings.js';

const deleteCmd = (stopClient, msg, cmd, subcmd, thirdcmd, admin, mod, thisGuild, stopList, deleteList, isStopped, isDeleted, richEmbed) => {
  const reserved = ['help', 'info', 'updates', 'stop', 'delete', 'go', 'set', 'fish', 'inv', 'prefix', 'video'];
  if (!subcmd) return;
  if (reserved.indexOf(subcmd) !== -1) {
    msg.channel.send({
      embed: richEmbed.setColor('#ff0000').setDescription(`This word is reserved for bot functionality and cannot be deleted.`)
    });
    return;
  } else if (subcmd === 'list') {
    if (deleteList.length !== 0) {
      getToggleDM(stopClient, msg).then(enabled => {
        if (enabled) {
          msg.member.createDM()
            .then(channel => {
              channel.send('These words are currently being deleted: `' + deleteList.join(', ') + '`');
            });
        } else {
          msg.channel.send('These words are currently being deleted: `' + deleteList.join(', ') + '`');
        }
      });
    } else {
      msg.channel.send('There are no words on the delete list.')
    }
  } else if (!isNaN(subcmd) && mod) {
    let limit = parseInt(subcmd) + 1;
    if (limit >= 100) {
      msg.channel.send({
        embed: richEmbed.setColor('#ff0000').setDescription(`Number of messages must be under 100.`)
      });
      return;
    }
    msg.channel.fetchMessages({limit: limit})
      .then((latestMessages) => {
        let mentions = msg.mentions.users;
        let mentionsNum = msg.mentions.users.array().length;
        if (mentionsNum === 0) msg.channel.bulkDelete(latestMessages);
        else {
          let latestByUser = latestMessages.filter((message) => message.author === mentions.first());
          msg.channel.bulkDelete(latestByUser);
        }
      })
      .catch(err => console.log(err));
  } else if (subcmd && isNaN(subcmd)) {
    if (admin) {
      if (isDeleted) {
        msg.channel.send('`' + subcmd + '`' + ' is already on the list of words to delete.');
      } else if (isStopped) {
        msg.channel.send('`' + subcmd + '`' + ' is already on the list of words to stop.');
      } else {
        stopClient.query(`UPDATE word_lists SET deletelist = deletelist || '{${subcmd.toLowerCase()}}' WHERE serverid=${thisGuild}`);
        msg.channel.send('`' + subcmd + '`' + ' will be deleted every time it appears.');
      }
    } else if (!admin) {
      msg.reply('you can\'t use this command.');
    }
  } else {
    return;
  }
}

export default deleteCmd;
<|endoftext|>


<commit_before>'use strict';

let express = require('express'),
    config = require('./config/config'),
    mongoose = require('mongoose');

let app = express();

// Load process.env
let envConf = require('./config/local.env.default.js');

for (let key in envConf) {
    if (envConf.hasOwnProperty(key)){
        process.env[key] = envConf[key];
    }
}

require('./config/express')(app, config);

mongoose.connect('mongodb://' + process.env.MONGO_HOST + ':' +
    process.env.MONGO_PORT + '/' + process.env.MONGO_DB);

let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log('Database connected');
});

app.use('/web', express.static('../app'));

app.listen(8080, function() {
    console.log('Server listening on port 8080 !');
});<commit_msg>Fix rename error<commit_after>'use strict';

let express = require('express'),
    config = require('./config/config'),
    mongoose = require('mongoose');

let app = express();

// Load process.env
let envConf = require('./config/local.env.js');

for (let key in envConf) {
    if (envConf.hasOwnProperty(key)){
        process.env[key] = envConf[key];
    }
}

require('./config/express')(app, config);

mongoose.connect('mongodb://' + process.env.MONGO_HOST + ':' +
    process.env.MONGO_PORT + '/' + process.env.MONGO_DB);

let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log('Database connected');
});

app.use('/web', express.static('../app'));

app.listen(8080, function() {
    console.log('Server listening on port 8080 !');
});<|endoftext|>


<commit_before>var assert = require('assert');
var urljoin = require('../');

describe('urljoin.js', function() {
    it('handle hosts', function() {
        assert.equal(
            urljoin('http://abc.com', '/git/'),
            urljoin('http://abc.com/', '/git/')
        );
        assert.equal(
            urljoin('http://abc.com/', '/git/'),
            'http://abc.com/git/'
        );

        assert.equal(
            urljoin('http://abc.com', ''),
            'http://abc.com/'
        );
    });

    it('handle query strings', function() {
        assert.equal(
            urljoin('/abc/', 'index.php?a=b'),
            '/abc/index.php?a=b'
        );
    });

    it('handle repeating slashes', function() {
        assert.equal(
            urljoin('http://abc.com//', '/team'),
            'http://abc.com/team'
        );
    });

    it('handle preceding slashes', function() {
        assert.equal(
            urljoin('/git/', '/repos/aaron/test.git'),
            '/git/repos/aaron/test.git'
        );
    });

    it('handle trailing slashes', function() {
        assert.equal(
            urljoin('/git/', 'test/'),
            '/git/test/'
        );

        assert.equal(
            urljoin('/git/', '/test/'),
            '/git/test/'
        );
    });

    it('handle relative', function() {
        assert.equal(
            urljoin('http://abc.com/forums/', '../about'),
            'http://abc.com/about'
        );

        assert.equal(
            urljoin('/git/', '../about'),
            '/about'
        );
    })
})<commit_msg>Tidy up test/test.js<commit_after>var assert = require('assert');
var urljoin = require('../');

describe('urljoin.js', function() {
    it('handle hosts', function() {
        assert.equal(
            urljoin('http://abc.com', '/git/'),
            urljoin('http://abc.com/', '/git/')
        );
        assert.equal(
            urljoin('http://abc.com/', '/git/'),
            'http://abc.com/git/'
        );

        assert.equal(
            urljoin('http://abc.com', ''),
            'http://abc.com/'
        );
    });

    it('handle query strings', function() {
        assert.equal(
            urljoin('/abc/', 'index.php?a=b'),
            '/abc/index.php?a=b'
        );
    });

    it('handle repeating slashes', function() {
        assert.equal(
            urljoin('http://abc.com//', '/team'),
            'http://abc.com/team'
        );
    });

    it('handle preceding slashes', function() {
        assert.equal(
            urljoin('/git/', '/repos/aaron/test.git'),
            '/git/repos/aaron/test.git'
        );
    });

    it('handle trailing slashes', function() {
        assert.equal(
            urljoin('/git/', 'test/'),
            '/git/test/'
        );

        assert.equal(
            urljoin('/git/', '/test/'),
            '/git/test/'
        );
    });

    it('handle relative', function() {
        assert.equal(
            urljoin('http://abc.com/forums/', '../about'),
            'http://abc.com/about'
        );

        assert.equal(
            urljoin('/git/', '../about'),
            '/about'
        );
    });
});
<|endoftext|>


<commit_before>// for debugging and tweaking from the console
var MAPS = {};
(function() {

    // returns the map provider for a given TileStache layer name
    function getProvider(layer) {
        return new MM.StamenTileLayer(layer);
    }

    function init() {

        var providerLabel = document.getElementById("current-provider"),
            currentProvider = "toner",
            mapsByProvider = MAPS.byProvider = {};

        // our main map
        var main = MAPS.main = new MM.Map("map-main", getProvider(currentProvider), null, [new MM.DragHandler(), new MM.DoubleClickHandler()]);

        mapsByProvider[currentProvider] = main;

        // keep a reference to the sub-map wrapper to figure out
        // positioning stuff
        var wrapper = MAPS.wrapper = document.getElementById("maps-sub"),
            subs = MAPS.sub = [],
            // then grab all the sub-map element references
            subParents = wrapper.querySelectorAll(".map");
        // create a map for each sub-map element
        for (var i = 0; i < subParents.length; i++) {
            var el = subParents[i],
                // the provider is based on the data-provider HTML attribute
                provider = el.getAttribute("data-provider"),
                // FIXME: these maps are not interactive
                map = new MM.Map(el, getProvider(provider), null, [new MM.DragHandler()]);
            map.addCallback("panned", function(_map, offset) {
                if (!main.panning) {
                    _map.panning = true;
                    main.panBy(offset[0], offset[1]);
                    _map.panning = false;
                }
            });
            mapsByProvider[provider] = map;
            subs.push(map);
        }

        // sync sub-maps to the main map's center using their
        // relative positions on screen
        function updateSubMaps() {
            var mainWidth = main.dimensions.x,
                wrapperWidth = wrapper.offsetWidth,
                wrapperTop = wrapper.offsetTop,
                offsetX = mainWidth - (mainWidth - wrapperWidth) / 2;
            for (var i = 0; i < subs.length; i++) {
                var sub = subs[i],
                    point = new MM.Point(0, 0);
                point.x = offsetX - sub.dimensions.x / 2;
                point.y = wrapperTop + sub.parent.offsetTop + sub.dimensions.y / 2;
                sub.setCenterZoom(main.pointLocation(point), main.getZoom());
            }
        }

        // zoom click handlers
        MM.addEvent(document.getElementById("zoom-in"), "click", function() {
            main.zoomIn();
            return false;
        });
        MM.addEvent(document.getElementById("zoom-out"), "click", function() {
            main.zoomOut();
            return false;
        });

        // pan the sub-maps when the main map is panned
        main.addCallback("panned", function(_map, offset) {
            if (main.panning) return;
            main.panning = true;
            for (var i = 0; i < subs.length; i++) {
                var sub = subs[i];
                if (!sub.panning) {
                    sub.panBy(offset[0], offset[1]);
                }
            }
            main.panning = false;
        });

        // and for all other map redraw events, re-sync them
        main.addCallback("zoomed", updateSubMaps);
        main.addCallback("extentset", updateSubMaps);
        main.addCallback("centered", updateSubMaps);

        // set the initial map position
        main.setCenterZoom(new MM.Location(37.7719, -122.3926), 12);

        // and set up listening for the browser's location hash
        var hasher = new ProviderHash(main, currentProvider, function(provider) {
            if (!provider || !(provider in mapsByProvider)) {
                return false;
            }
            // if the provider has changed...
            if (provider != currentProvider) {
                // grab the provider from the corresponding map
                var source = mapsByProvider[provider],
                    target = main;
                // swap layers
                source.setLayerAt(0, getProvider(currentProvider));
                target.setLayerAt(0, getProvider(provider));

                // update the link in the clicked sub-map
                var link = source.parent.querySelector("h3 a");
                link.innerHTML = currentProvider.substr(0, 1).toUpperCase() + currentProvider.substr(1);
                link.href = "#" + currentProvider;

                // update the selected provider label text
                providerLabel.innerHTML = provider;

                // swap the map references in mapsByProvider
                mapsByProvider[provider] = target;
                mapsByProvider[currentProvider] = source;
                // and, finally, update currentProvider
                currentProvider = provider;
            }
            return true;
        });

        // set up form element references
        var searchForm = document.getElementById("search"),
            searchInput = document.getElementById("search-location"),
            searchButton = document.getElementById("search-submit");
        // listen for the submit event
        MM.addEvent(searchForm, "submit", function(e) {
            // remember the old search text
            var oldSearchText = searchButton.getAttribute("value");
            // put the button into its submitting state
            searchButton.setAttribute("value", "Finding...");
            searchButton.setAttribute("class", "btn disabled");
            // set up a function to rever the form to its original state
            // (which executes whether there was an error or not)
            function revert() {
                searchButton.setAttribute("class", "btn");
                searchButton.setAttribute("value", oldSearchText);
            }

            var query = searchInput.value;
            MapQuest.geocode(query, function(results) {
                revert();
                // console.log("search results:", results);
                // TODO: find the most relevant result?
                var result = results[0].locations[0],
                    loc = result.displayLatLng,
                    zoom = map.getZoom();
                switch (result.geocodeQuality) {
                    case "CITY":
                        zoom = 11;
                        break;
                    case "STATE":
                        zoom = 7;
                        break;
                }
                main.setCenterZoom(new MM.Location(loc.lat, loc.lng), zoom);
                // FIXME: offset the map so its center is
                // to the left of the sub-maps?
                // main.panBy(-(main.dimensions.x - wrapper.offsetWidth) / 2, 0);
            }, function(error) {
                revert();
                console.error("search error:", error);
            });

            // cancel the submit event
            return MM.cancelEvent(e);
        });

        // create static mini-maps for each of these elements
        var minis = document.querySelectorAll("#content .map");
        MAPS.minis = [];
        for (var i = 0; i < minis.length; i++) {
            var el = minis[i],
                provider = getProvider(el.getAttribute("data-provider")),
                center = parseCenter(el.getAttribute("data-center")),
                zoom = parseInt(el.getAttribute("data-zoom")),
                map = new MM.Map(el, provider, null, []);
            map.setCenterZoom(center, zoom);
            MAPS.minis.push(map);
        }
    }

    // parse a string into an MM.Location instance
    function parseCenter(str) {
        var parts = str.split(/,\s*/),
            lat = parseFloat(parts[0]),
            lon = parseFloat(parts[1]);
        return new MM.Location(lat, lon);
    }

    // quick and dirty MQ search API
    var MapQuest = {
        // XXX: this is a Slow Tusnami key registered on the shawn@stamen.com
        // MapQuest developer account
        key: decodeURIComponent("Fmjtd%7Cluua216ynl%2Cbg%3Do5-h4rxg"),
        geocode: function(query, success, error) {
            var data;
            if (typeof query === "string") {
                data = {location: query};
            } else {
                data = query;
            }
            data.inFormat = "kvp";
            data.thumbMaps = false;
            data.key = MapQuest.key;
            data.outFormat = "json";
            return reqwest({
                url: "http://www.mapquestapi.com/geocoding/v1/address?callback=?",
                type: "jsonp",
                jsonpCallback: "callback",
                data: data,
                success: function(response) {
                    var results = response.results;
                    if (results && results.length) {
                        success.call(null, results);
                    } else {
                        error.call(null, "No results");
                    }
                },
                error: error
            });
        }
    };

    /**
     * The ProviderHash is a class that looks for a provider name at the beginning
     * of the hash and calls the supplied setProvider(provider) function whenever it
     * changes.
     *
     * One feature of this parser is that it substitutes the center and zoom back in
     * if the hash changes to just "#provider", so you can link to new providers by
     * setting a link's href to simply "#provider" and ProviderHash will update the
     * hash accordingly.
     *
     * setProvider(provider) should accept a string and return true if the supplied
     * provider name was valid, or return false in any other case.
     *
     * Note also that ProviderHash requires a valid providerName in the constructor
     * to correctly set the initial hash value.
     */
    var ProviderHash = function(map, providerName, setProvider) {
        this.providerName = providerName;
        this.setProvider = setProvider;
        MM.Hash.call(this, map);
    };

    ProviderHash.prototype = {
        // the currently selected provider name
        providerName: null,

        /**
         * Our parseHash() function looks for a provider name in the beginning of
         * the URL.
         */
        parseHash: function(hash) {
            var parts = hash.split("/");
            if (parts.length > 0) {
                var provider = parts.shift();
                var parsed = parts.length
                    ? MM.Hash.prototype.parseHash.call(this, parts.join("/"))
                    : {center: this.map.getCenter(), zoom: this.map.getZoom()};
                if (parsed) {
                    // console.log("parsed hash:", provider, parsed);
                    var didSetProvider = this.setProvider.call(this.map, provider);
                    if (didSetProvider) {
                        this.providerName = provider;
                        return parsed;
                    } else {
                        return false;
                    }
                } else {
                    // console.log("parse error:", hash, parts, this.providerName);
                }
                return parsed;
            } else {
                // console.warn("(zero length, unable to parse");
                return false;
            }
        },

        /**
         * Our formatHash() function inserts the provider name as the first
         * slash-delimited element in the URL.
         */
        formatHash: function(hash) {
            var format = MM.Hash.prototype.formatHash.call(this, hash);
            return "#" + this.providerName + "/" + format.substr(1);
        }
    };

    MM.extend(ProviderHash, MM.Hash);

    try {

        init();

    } catch (e) {
        console.error(e);
    }

})();
<commit_msg>switched to yahoo place search API<commit_after>// for debugging and tweaking from the console
var MAPS = {};
(function() {

    // returns the map provider for a given TileStache layer name
    function getProvider(layer) {
        return new MM.StamenTileLayer(layer);
    }

    function init() {

        var providerLabel = document.getElementById("current-provider"),
            currentProvider = "toner",
            mapsByProvider = MAPS.byProvider = {};

        // our main map
        var main = MAPS.main = new MM.Map("map-main", getProvider(currentProvider), null, [new MM.DragHandler(), new MM.DoubleClickHandler()]);

        mapsByProvider[currentProvider] = main;

        // keep a reference to the sub-map wrapper to figure out
        // positioning stuff
        var wrapper = MAPS.wrapper = document.getElementById("maps-sub"),
            subs = MAPS.sub = [],
            // then grab all the sub-map element references
            subParents = wrapper.querySelectorAll(".map");
        // create a map for each sub-map element
        for (var i = 0; i < subParents.length; i++) {
            var el = subParents[i],
                // the provider is based on the data-provider HTML attribute
                provider = el.getAttribute("data-provider"),
                // FIXME: these maps are not interactive
                map = new MM.Map(el, getProvider(provider), null, [new MM.DragHandler()]);
            map.addCallback("panned", function(_map, offset) {
                if (!main.panning) {
                    _map.panning = true;
                    main.panBy(offset[0], offset[1]);
                    _map.panning = false;
                }
            });
            mapsByProvider[provider] = map;
            subs.push(map);
        }

        // sync sub-maps to the main map's center using their
        // relative positions on screen
        function updateSubMaps() {
            var mainWidth = main.dimensions.x,
                wrapperWidth = wrapper.offsetWidth,
                wrapperTop = wrapper.offsetTop,
                offsetX = mainWidth - (mainWidth - wrapperWidth) / 2;
            for (var i = 0; i < subs.length; i++) {
                var sub = subs[i],
                    point = new MM.Point(0, 0);
                point.x = offsetX - sub.dimensions.x / 2;
                point.y = wrapperTop + sub.parent.offsetTop + sub.dimensions.y / 2;
                sub.setCenterZoom(main.pointLocation(point), main.getZoom());
            }
        }

        // zoom click handlers
        MM.addEvent(document.getElementById("zoom-in"), "click", function() {
            main.zoomIn();
            return false;
        });
        MM.addEvent(document.getElementById("zoom-out"), "click", function() {
            main.zoomOut();
            return false;
        });

        // pan the sub-maps when the main map is panned
        main.addCallback("panned", function(_map, offset) {
            if (main.panning) return;
            main.panning = true;
            for (var i = 0; i < subs.length; i++) {
                var sub = subs[i];
                if (!sub.panning) {
                    sub.panBy(offset[0], offset[1]);
                }
            }
            main.panning = false;
        });

        // and for all other map redraw events, re-sync them
        main.addCallback("zoomed", updateSubMaps);
        main.addCallback("extentset", updateSubMaps);
        main.addCallback("centered", updateSubMaps);

        // set the initial map position
        main.setCenterZoom(new MM.Location(37.7719, -122.3926), 12);

        // and set up listening for the browser's location hash
        var hasher = new ProviderHash(main, currentProvider, function(provider) {
            if (!provider || !(provider in mapsByProvider)) {
                return false;
            }
            // if the provider has changed...
            if (provider != currentProvider) {
                // grab the provider from the corresponding map
                var source = mapsByProvider[provider],
                    target = main;
                // swap layers
                source.setLayerAt(0, getProvider(currentProvider));
                target.setLayerAt(0, getProvider(provider));

                // update the link in the clicked sub-map
                var link = source.parent.querySelector("h3 a");
                link.innerHTML = currentProvider.substr(0, 1).toUpperCase() + currentProvider.substr(1);
                link.href = "#" + currentProvider;

                // update the selected provider label text
                providerLabel.innerHTML = provider;

                // swap the map references in mapsByProvider
                mapsByProvider[provider] = target;
                mapsByProvider[currentProvider] = source;
                // and, finally, update currentProvider
                currentProvider = provider;
            }
            return true;
        });

        // set up form element references
        var searchForm = document.getElementById("search"),
            searchInput = document.getElementById("search-location"),
            searchButton = document.getElementById("search-submit");
        // listen for the submit event
        MM.addEvent(searchForm, "submit", function(e) {
            // remember the old search text
            var oldSearchText = searchButton.getAttribute("value");
            // put the button into its submitting state
            searchButton.setAttribute("value", "Finding...");
            searchButton.setAttribute("class", "btn disabled");
            // set up a function to rever the form to its original state
            // (which executes whether there was an error or not)
            function revert() {
                searchButton.setAttribute("class", "btn");
                searchButton.setAttribute("value", oldSearchText);
            }

            var query = searchInput.value;
            YahooPlaceSearch.geocode(query, function(places) {
                revert();
                // console.log("search results:", results);
                // TODO: find the most relevant result?
                try {
                    var result = places.place[0],
                        northeast = result.boundingBox.northEast,
                        southwest = result.boundingBox.southWest;
                    main.setExtent([
                        new MM.Location(northeast.latitude, northeast.longitude),
                        new MM.Location(southwest.latitude, southwest.longitude)
                    ]);
                } catch (e) {
                    alert('Sorry, something went wrong when searching for "' + query + '".');
                }
                // main.panBy(-(main.dimensions.x - wrapper.offsetWidth) / 2, 0);
            }, function(error) {
                revert();
                alert('Sorry, we couldn\'t find "' + query + '".');
            });

            // cancel the submit event
            return MM.cancelEvent(e);
        });

        // create static mini-maps for each of these elements
        var minis = document.querySelectorAll("#content .map");
        MAPS.minis = [];
        for (var i = 0; i < minis.length; i++) {
            var el = minis[i],
                provider = getProvider(el.getAttribute("data-provider")),
                center = parseCenter(el.getAttribute("data-center")),
                zoom = parseInt(el.getAttribute("data-zoom")),
                map = new MM.Map(el, provider, null, []);
            map.setCenterZoom(center, zoom);
            MAPS.minis.push(map);
        }
    }

    // parse a string into an MM.Location instance
    function parseCenter(str) {
        var parts = str.split(/,\s*/),
            lat = parseFloat(parts[0]),
            lon = parseFloat(parts[1]);
        return new MM.Location(lat, lon);
    }

    /**
     * The ProviderHash is a class that looks for a provider name at the beginning
     * of the hash and calls the supplied setProvider(provider) function whenever it
     * changes.
     *
     * One feature of this parser is that it substitutes the center and zoom back in
     * if the hash changes to just "#provider", so you can link to new providers by
     * setting a link's href to simply "#provider" and ProviderHash will update the
     * hash accordingly.
     *
     * setProvider(provider) should accept a string and return true if the supplied
     * provider name was valid, or return false in any other case.
     *
     * Note also that ProviderHash requires a valid providerName in the constructor
     * to correctly set the initial hash value.
     */
    var ProviderHash = function(map, providerName, setProvider) {
        this.providerName = providerName;
        this.setProvider = setProvider;
        MM.Hash.call(this, map);
    };

    ProviderHash.prototype = {
        // the currently selected provider name
        providerName: null,

        /**
         * Our parseHash() function looks for a provider name in the beginning of
         * the URL.
         */
        parseHash: function(hash) {
            var parts = hash.split("/");
            if (parts.length > 0) {
                var provider = parts.shift();
                var parsed = parts.length
                    ? MM.Hash.prototype.parseHash.call(this, parts.join("/"))
                    : {center: this.map.getCenter(), zoom: this.map.getZoom()};
                if (parsed) {
                    // console.log("parsed hash:", provider, parsed);
                    var didSetProvider = this.setProvider.call(this.map, provider);
                    if (didSetProvider) {
                        this.providerName = provider;
                        return parsed;
                    } else {
                        return false;
                    }
                } else {
                    // console.log("parse error:", hash, parts, this.providerName);
                }
                return parsed;
            } else {
                // console.warn("(zero length, unable to parse");
                return false;
            }
        },

        /**
         * Our formatHash() function inserts the provider name as the first
         * slash-delimited element in the URL.
         */
        formatHash: function(hash) {
            var format = MM.Hash.prototype.formatHash.call(this, hash);
            return "#" + this.providerName + "/" + format.substr(1);
        }
    };

    MM.extend(ProviderHash, MM.Hash);

    try {

        init();

    } catch (e) {
        console.error(e);
    }

})();

var YahooPlaceSearch = {
    appid: "1DiQEyLV34HbAVHyl0iWC5tAZ8wpLMPzIeFE9QsTukhx6H.Cn9bM70c_5dYgh7cR8w--",
    url: "http://where.yahooapis.com/v1/places.q({q});count=1?callback=?",
    geocode: function(query, success, error) {
        var data = {};
        data.appid = YahooPlaceSearch.appid;
        data.select = "long";
        data.format = "json";
        return reqwest({
            url: YahooPlaceSearch.url.replace("{q}", encodeURIComponent(query)),
            type: "jsonp",
            jsonpCallback: "callback",
            data: data,
            success: function(response) {
                var results = response.places;
                if (results) {
                    success.call(null, results);
                } else {
                    error.call(null, "No results", response);
                }
            },
            error: error
        });
    }
};

// quick and dirty MQ search API
var MapQuest = {
    // XXX: this is a Slow Tusnami key registered on the shawn@stamen.com
    // MapQuest developer account
    key: decodeURIComponent("Fmjtd%7Cluua216ynl%2Cbg%3Do5-h4rxg"),
    geocode: function(query, success, error) {
        var data;
        if (typeof query === "string") {
            data = {location: query};
        } else {
            data = query;
        }
        data.inFormat = "kvp";
        data.thumbMaps = false;
        data.key = MapQuest.key;
        data.outFormat = "json";
        return reqwest({
            url: "http://www.mapquestapi.com/geocoding/v1/address?callback=?",
            type: "jsonp",
            jsonpCallback: "callback",
            data: data,
            success: function(response) {
                var results = response.results;
                if (results && results.length) {
                    success.call(null, results);
                } else {
                    error.call(null, "No results");
                }
            },
            error: error
        });
    }
};
<|endoftext|>


<commit_before>Package.describe({
  name: 'templating-tools',
  version: '0.0.1',
  // Brief, one-line summary of the package.
  summary: '',
  // URL to the Git repository containing the source code for this package.
  git: '',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.use([
    'underscore',
    'ecmascript',
    'spacebars-compiler',

    // minifiers is a weak dependency of spacebars-compiler; adding it here
    // ensures that the output is minified.  (Having it as a weak dependency means
    // that we don't ship uglify etc with built apps just because
    // boilerplate-generator uses spacebars-compiler.)
    // XXX maybe uglify should be applied by this plugin instead of via magic
    // weak dependency.
    'minifiers'
  ]);

  api.addFiles([
    'templating-tools.js',
    'html-scanner.js',
    'compile-tags-with-spacebars.js',
    'throw-compile-error.js',
    'code-generation.js'
  ]);

  api.export('TemplatingTools');
});

Package.onTest(function(api) {
  api.use([
    'tinytest',
    'templating-tools',
    'ecmascript'
  ]);

  api.addFiles('html-scanner-tests.js', 'server');
});
<commit_msg>Add metadata to templating-tools<commit_after>Package.describe({
  name: 'templating-tools',
  version: '0.0.1',
  // Brief, one-line summary of the package.
  summary: 'Tools to scan HTML and compile tags when building a templating package',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/meteor/meteor',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.use([
    'underscore',
    'ecmascript',
    'spacebars-compiler',

    // minifiers is a weak dependency of spacebars-compiler; adding it here
    // ensures that the output is minified.  (Having it as a weak dependency means
    // that we don't ship uglify etc with built apps just because
    // boilerplate-generator uses spacebars-compiler.)
    // XXX maybe uglify should be applied by this plugin instead of via magic
    // weak dependency.
    'minifiers'
  ]);

  api.addFiles([
    'templating-tools.js',
    'html-scanner.js',
    'compile-tags-with-spacebars.js',
    'throw-compile-error.js',
    'code-generation.js'
  ]);

  api.export('TemplatingTools');
});

Package.onTest(function(api) {
  api.use([
    'tinytest',
    'templating-tools',
    'ecmascript'
  ]);

  api.addFiles('html-scanner-tests.js', 'server');
});
<|endoftext|>


<commit_before>import axios from 'axios'

export const REGISTER_USER = 'REGISTER_USER'
export const LOGIN = 'LOGIN'
export const SEARCH_BOOKS = 'SEARCH_BOOKS'
export const ROOT_URL = 'http://localhost:3000'

export function registerUser(user) {
	const url = `${ROOT_URL}/register`
	const request = axios.post(url, user)

	return{
		type: REGISTER_USER,
		payload: request
	}
}

export function login(user) {
	const url = `${ROOT_URL}/login`
	const request = axios.post(url, user)

	return{
		type: LOGIN,
		payload: request
	}
}

export function searchBooks(searchTerm) {
	const url = `https://www.googleapis.com/books/v1/volumes?q=${searchTerm}&maxResults=20`
	const request = axios.get(url)

	return {
		type: SEARCH_BOOKS,
		payload: request
	}
}<commit_msg>built addToWishlist action creator<commit_after>import axios from 'axios'

export const REGISTER_USER = 'REGISTER_USER'
export const LOGIN = 'LOGIN'
export const SEARCH_BOOKS = 'SEARCH_BOOKS'
export const ADD_TO_WISHLIST = 'ADD_TO_WISHLIST'
export const ROOT_URL = 'http://localhost:3000'

export function registerUser(user) {
	const url = `${ROOT_URL}/register`
	const request = axios.post(url, user)

	return{
		type: REGISTER_USER,
		payload: request
	}
}

export function login(user) {
	const url = `${ROOT_URL}/login`
	const request = axios.post(url, user)

	return{
		type: LOGIN,
		payload: request
	}
}

export function searchBooks(searchTerm) {
	const url = `https://www.googleapis.com/books/v1/volumes?q=${searchTerm}&maxResults=20`
	const request = axios.get(url)

	return {
		type: SEARCH_BOOKS,
		payload: request
	}
}

export function addToWishlist(book) {
	return {
		type: ADD_TO_WISHLIST,
		payload: book
	}
}<|endoftext|>


<commit_before>const path = require('path')
const express = require('express')
const passport = require('./passport')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const auth = require('./lib/auth')
const api = require('./routes/index')
const usersDb = './db/users'

const skEventSearch = require('./routes/skEvents')
const skGetAreaID = require('./routes/skMetro')
const index = require('./routes/index')
const spotify = require('./routes/spotify')
const home = require('./routes/home')

const spotifyLib = require('./lib/spotify')

const app = express()

// How to set this?!?!
// setInterval(function() {
//   spotifyConnection = spotifyLib.setConnection('test')
// }, 60*1000*60)

app.set('JWT_SECRET', process.env.JWT_SECRET)

app.use(cookieParser())
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, '../public')))

passport(app)

// routes here
app.use('/', index)
app.use('/home', home )
app.use('/api/v1/events', skEventSearch)
app.use('/api/v1/metros', skGetAreaID)
app.use('/api/v1/spotify', spotify)

module.exports = (connection, isTest) => {
  isTest
  ? app.set('spotifyToken', 'testtoken')
  : spotifyLib.getToken()
    .then((token) => {
      app.set('spotifyToken', token)
    })
  app.set('connection', connection)
  return app
}
<commit_msg>stashing<commit_after>const path = require('path')
const express = require('express')
const passport = require('./passport')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const auth = require('./lib/auth')
const api = require('./routes/index')
const usersDb = './db/users'

const skEventSearch = require('./routes/skEvents')
const skGetAreaID = require('./routes/skMetro')
const index = require('./routes/index')
const spotify = require('./routes/spotify')
const home = require('./routes/home')

const spotifyLib = require('./lib/spotify')

const app = express()

// let spotifyConnection = null
//
// setInterval(function() {
//   spotifyConnection = spotifyLib.setConnection('test')
// }, 60*1000*60)

app.set('JWT_SECRET', process.env.JWT_SECRET)

app.use(cookieParser())
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, '../public')))

passport(app)

// routes here
app.use('/', index)
app.use('/home', home )
app.use('/api/v1/events', skEventSearch)
app.use('/api/v1/metros', skGetAreaID)
app.use('/api/v1/spotify', spotify)

module.exports = (connection, isTest) => {
  isTest
  ? app.set('spotifyToken', 'testtoken')
  : spotifyLib.getToken()
    .then((token) => {
      app.set('spotifyToken', token)
    })
  app.set('connection', connection)
  return app
}
<|endoftext|>


<commit_before>import moment from 'moment'
import chalk from 'chalk'
import format from '../time'
import pad from 'pad'

export {write as write}
export {getOutputs as getOutputs}

function write(entry) {
  const {detailed} = getOutputs(entry)

  console.log(detailed)
}

function getOutputs(entry) {
  const timePattern = new RegExp(/\s*/.source + entry.time + /\s*/.source, 'g')
  const id = `${chalk.gray(pad(entry._id, 10))}`
  const date = `${chalk.yellow(pad(moment(entry.from).format('ddd MMM DD'),9))}`
  const time = entry.time
  const duration = chalk.green(format(entry.duration.minutes))
  const msg = entry.message
    .replace(/\s*#\w+\s*/g, '')
    .replace(timePattern, '')
  const tags = chalk.cyan([...entry.tags].join(' '))

  const detailed = `${id} ${date} ${time} ${duration} ${msg} ${tags}`
  const simple = `${id} ${time} ${duration} ${msg} ${tags}`

  return {id, date, duration, msg, tags, detailed, simple}
}
<commit_msg>display time in normalized format<commit_after>import moment from 'moment'
import chalk from 'chalk'
import format from '../time'
import pad from 'pad'

export {write as write}
export {getOutputs as getOutputs}

function write(entry) {
  const {detailed} = getOutputs(entry)

  console.log(detailed)
}

function getOutputs(entry) {
  const timePattern = new RegExp(/\s*/.source + entry.time + /\s*/.source, 'g')
  const id = `${chalk.gray(pad(entry._id, 10))}`
  const date = `${chalk.yellow(pad(moment(entry.from).format('ddd MMM DD'),9))}`
  const timeFrom = moment(entry.from)
  const timeTo = moment(entry.to)
  const time = `${timeFrom.format('hh:mma')}-${timeTo.format('hh:mma')}`
  const duration = chalk.green(format(entry.duration.minutes))
  const msg = entry.message
    .replace(/\s*#\w+\s*/g, '')
    .replace(timePattern, '')
  const tags = chalk.cyan([...entry.tags].join(' '))

  const detailed = `${id} ${date} ${time} ${duration} ${msg} ${tags}`
  const simple = `${id} ${time} ${duration} ${msg} ${tags}`

  return {id, date, duration, msg, tags, detailed, simple}
}
<|endoftext|>


<commit_before>const fs = require("fs");

const files = new Map([
  ["./node_modules/three/examples/jsm/loaders/GLTFLoader.js", "./loader/_GLTFLoader.js"],
  ["./node_modules/three/examples/jsm/loaders/DRACOLoader.js", "./loader/_DRACOLoader.js"],
]);

for (const [source, destination] of files) {
  fs.copyFileSync(source, destination);
  const data = fs.readFileSync(destination, "utf-8");
  const newValue = data.replace("../../../build/three.module.js", "../../../three/src/Three.js");
  fs.writeFileSync(destination, newValue, "utf-8");
}
<commit_msg>update copy loader paths<commit_after>const fs = require("fs");

const files = new Map([
  ["./node_modules/three/examples/jsm/loaders/GLTFLoader.js", "./node_modules/@damienmortini/three/loader/_GLTFLoader.js"],
  ["./node_modules/three/examples/jsm/loaders/DRACOLoader.js", "./node_modules/@damienmortini/three/loader/_DRACOLoader.js"],
]);

for (const [source, destination] of files) {
  fs.copyFileSync(source, destination);
  const data = fs.readFileSync(destination, "utf-8");
  const newValue = data.replace("../../../build/three.module.js", "../../../three/src/Three.js");
  fs.writeFileSync(destination, newValue, "utf-8");
}
<|endoftext|>


<commit_before>const pkg = require("../package.json");
const solcpkg = require("solc/package.json");
const Web3 = require("web3");

const info = () => {
  let bundleVersion;
  // NOTE: Webpack will replace BUNDLE_VERSION with a string.
  if (typeof BUNDLE_VERSION != "undefined") {
    bundleVersion = BUNDLE_VERSION;
  }

  return {
    core: pkg.version,
    bundle: bundleVersion,
    solc: solcpkg.version
  };
};

const logTruffle = (logger = console, versionInformation) => {
  const bundle = versionInformation.bundle
    ? `v${versionInformation.bundle}`
    : "(unbundled)";
  logger.log(`Truffle ${bundle} (core: ${versionInformation.core})`);
};

const logNode = (logger = console) => {
  logger.log(`Node ${process.version}`);
};

const logSolidity = (logger = console, versionInformation, config) => {
  let solcVersion;
  if (
    config &&
    config.compilers &&
    config.compilers.solc &&
    config.compilers.solc.version
  ) {
    solcVersion = config.compilers.solc.version;
    logger.log(`Solidity - ${solcVersion} (solc-js)`);
  } else {
    const versionInformation = info();
    solcVersion = versionInformation.solc;
    logger.log(`Solidity v${solcVersion} (solc-js)`);
  }
};

const logWeb3 = (logger = console) => {
  logger.log(`Web3.js v${Web3.version}`);
};

const logAll = (logger = console, config) => {
  const versionInformation = info();
  logTruffle(logger, versionInformation);
  logSolidity(logger, versionInformation, config);
  logNode(logger);
  logWeb3(logger);
};

const logTruffleAndNode = (logger = console) => {
  const versionInformation = info();
  logTruffle(logger, versionInformation);
  logNode(logger);
};

module.exports = {
  logAll,
  info,
  logTruffleAndNode
};
<commit_msg>Remove requiring of Web3 while fetching version information<commit_after>const pkg = require("../package.json");
const solcpkg = require("solc/package.json");

const info = () => {
  let bundleVersion;
  // NOTE: Webpack will replace BUNDLE_VERSION with a string.
  if (typeof BUNDLE_VERSION != "undefined") {
    bundleVersion = BUNDLE_VERSION;
  }

  return {
    core: pkg.version,
    bundle: bundleVersion,
    solc: solcpkg.version
  };
};

const logTruffle = (logger = console, versionInformation) => {
  const bundle = versionInformation.bundle
    ? `v${versionInformation.bundle}`
    : "(unbundled)";
  logger.log(`Truffle ${bundle} (core: ${versionInformation.core})`);
};

const logNode = (logger = console) => {
  logger.log(`Node ${process.version}`);
};

const logSolidity = (logger = console, versionInformation, config) => {
  let solcVersion;
  if (
    config &&
    config.compilers &&
    config.compilers.solc &&
    config.compilers.solc.version
  ) {
    solcVersion = config.compilers.solc.version;
    logger.log(`Solidity - ${solcVersion} (solc-js)`);
  } else {
    const versionInformation = info();
    solcVersion = versionInformation.solc;
    logger.log(`Solidity v${solcVersion} (solc-js)`);
  }
};

const logWeb3 = (logger = console) => {
  const web3Version = pkg.dependencies.web3;
  logger.log(`Web3.js v${web3Version}`);
};

const logAll = (logger = console, config) => {
  const versionInformation = info();
  logTruffle(logger, versionInformation);
  logSolidity(logger, versionInformation, config);
  logNode(logger);
  logWeb3(logger);
};

const logTruffleAndNode = (logger = console) => {
  const versionInformation = info();
  logTruffle(logger, versionInformation);
  logNode(logger);
};

module.exports = {
  logAll,
  info,
  logTruffleAndNode
};
<|endoftext|>


<commit_before>import axios from 'axios'

export const REGISTER_USER = 'REGISTER_USER'
export const LOGIN = 'LOGIN'
export const ROOT_URL = 'http://localhost:3000'

export function registerUser(user) {
	const url = `${ROOT_URL}/register`
	const request = axios.post(url, user)

	return{
		type: REGISTER_USER,
		payload: request
	}
}

export function login(user) {
	const url = `${ROOT_URL}/login`
	const request = axios.post(url, user)

	return{
		type: LOGIN,
		payload: request
	}
}<commit_msg>added searchBooks action creator<commit_after>import axios from 'axios'

export const REGISTER_USER = 'REGISTER_USER'
export const LOGIN = 'LOGIN'
export const SEARCH_BOOKS = 'SEARCH_BOOKS'
export const ROOT_URL = 'http://localhost:3000'

export function registerUser(user) {
	const url = `${ROOT_URL}/register`
	const request = axios.post(url, user)

	return{
		type: REGISTER_USER,
		payload: request
	}
}

export function login(user) {
	const url = `${ROOT_URL}/login`
	const request = axios.post(url, user)

	return{
		type: LOGIN,
		payload: request
	}
}

export function searchBooks(searchTerm) {
	return {
		type: SEARCH_BOOKS,
		payload: searchTerm
	}
}<|endoftext|>


<commit_before>/* Base URL for canvas/bCourses API requests. */
var canvasBaseURL = "https://bcourses.berkeley.edu/api/v1";

function requestParams(p) {
    var baseQuery =  { 'per_page': '100' };
    var qs = _.extend({}, baseQuery, p);
    var options = {
        headers: {
            Authorization: 'Bearer ' + Meteor.user().canvasToken
        },
        params: qs,
        npmRequestOptions: {
            json: true,
            useQueryString: true
        }
    }
    return options;
}

/* Check if an object in arr has value for field. */
function findObjectByField(arr, field, value) {
    for (var i = 0; i < arr.length; i += 1) {
        if (arr[i][field] == value) {
            return i;
        }
    }
    return -1;
}

function coursePath(id) {
    return canvasBaseURL + "/courses"+ (id ? "/" + id : '');
}

function canvasStaff(cId) {
    var taParam = requestParams({enrollment_type:'ta',
                    'include[]': ['email', 'avatar_url'] });
    var instParam = requestParams({enrollment_type:'teacher',
                    'include[]': ['email', 'avatar_url'] });
    var tas = Meteor.http.get(coursePath(cId) + "/users", taParam);
    tas = tas.content;
    for (var i=0; i < tas.length; i += 1) {
        tas[i].enrollment_type = "TA";
    }
    var inst = Meteor.http.get(coursePath(cId) + "/users", instParam);
    inst = inst.content;
    for (var i=0; i < inst.length; i += 1) {
        inst[i].enrollment_type = "Instructor";
    }
    var all = [].concat(tas, inst)
    var sorted = all.sort(function(a, b) {
        a = a.sortable_name.toLowerCase();
        b = b.sortable_name.toLowerCase();
        if (a > b) { return 1; }
        if (a < b) { return -1; }
        return 0;
    });
    return sorted;
}

Meteor.methods({
    getCourses: function() {
        var result = Meteor.http.get(coursePath(),
                requestParams({'include[]':'term'})).content;
        var myCourseIds = Meteor.user().courses;
        if (myCourseIds) {
            var myCourses = Courses.find({'id' : { $in : myCourseIds }});
            myCourses = myCourses.fetch();
            for (var i = 0; i < myCourses.length; i += 1) {
                var index = findObjectByField(result, 'id', myCourses[i].id);
                if (index != -1) {
                    result[index] = myCourses[i];
                }
            }
        }
        return result;
    },
    getAssignmentList: function(cId) {
        var result = Meteor.http.get(coursePath(cId) + "/assignments", requestParams()).content;
        return result;
    },
    getAssignment: function(cId, assignmentId) {
        var result = Meteor.http.get(coursePath(cId) + "/assignments/" + assignmentId, requestParams()).content;
        return result;
    },
    getStaff: canvasStaff,
    getSubmissions: function(cId, aId) {
        var result = Meteor.http.get(coursePath(cId) + "/assignments/" + aId + "/submissions", requestParams({"include[]": "user"}));
        return result.content;
    },
    addCourse: function(course) {
        console.log('ADDING COURSE');
        console.log(course);

        var course = {
            id: course.id,
            bcourses: course,
            staff: []
        };
        var courseDB = Courses.find({'id': course.id});
        if (courseDB.fetch().length == 0) {
            Courses.insert(course);
        }
        Meteor.users.update({ '_id':Meteor.userId() },
                            { $addToSet: { 'courses': course.id } });
        return course;
    }
});
<commit_msg>console logs<commit_after>/* Base URL for canvas/bCourses API requests. */
var canvasBaseURL = "https://bcourses.berkeley.edu/api/v1";

function requestParams(p) {
    var baseQuery =  { 'per_page': '100' };
    var qs = _.extend({}, baseQuery, p);
    var options = {
        headers: {
            Authorization: 'Bearer ' + Meteor.user().canvasToken
        },
        params: qs,
        npmRequestOptions: {
            json: true,
            useQueryString: true
        }
    }
    return options;
}

/* Check if an object in arr has value for field. */
function findObjectByField(arr, field, value) {
    for (var i = 0; i < arr.length; i += 1) {
        if (arr[i][field] == value) {
            return i;
        }
    }
    return -1;
}

function coursePath(id) {
    return canvasBaseURL + "/courses"+ (id ? "/" + id : '');
}

function canvasStaff(cId) {
    var taParam = requestParams({enrollment_type:'ta',
                    'include[]': ['email', 'avatar_url'] });
    var instParam = requestParams({enrollment_type:'teacher',
                    'include[]': ['email', 'avatar_url'] });
    var tas = Meteor.http.get(coursePath(cId) + "/users", taParam);
    tas = tas.content;
    for (var i=0; i < tas.length; i += 1) {
        tas[i].enrollment_type = "TA";
    }
    var inst = Meteor.http.get(coursePath(cId) + "/users", instParam);
    inst = inst.content;
    for (var i=0; i < inst.length; i += 1) {
        inst[i].enrollment_type = "Instructor";
    }
    var all = [].concat(tas, inst)
    var sorted = all.sort(function(a, b) {
        a = a.sortable_name.toLowerCase();
        b = b.sortable_name.toLowerCase();
        if (a > b) { return 1; }
        if (a < b) { return -1; }
        return 0;
    });
    return sorted;
}

Meteor.methods({
    getCourses: function() {
        var result = Meteor.http.get(coursePath(),
                requestParams({'include[]':'term'})).content;
        var myCourseIds = Meteor.user().courses;
        console.log(myCourseIds);
        if (myCourseIds) {
            var myCourses = Courses.find({'id' : { $in : myCourseIds }});
            myCourses = myCourses.fetch();
            for (var i = 0; i < myCourses.length; i += 1) {
                var index = findObjectByField(result, 'id', myCourses[i].id);
                if (index != -1) {
                    result[index] = myCourses[i];
                }
            }
        }
        return result;
    },
    getAssignmentList: function(cId) {
        var result = Meteor.http.get(coursePath(cId) + "/assignments", requestParams()).content;
        return result;
    },
    getAssignment: function(cId, assignmentId) {
        var result = Meteor.http.get(coursePath(cId) + "/assignments/" + assignmentId, requestParams()).content;
        return result;
    },
    getStaff: canvasStaff,
    getSubmissions: function(cId, aId) {
        var result = Meteor.http.get(coursePath(cId) + "/assignments/" + aId + "/submissions", requestParams({"include[]": "user"}));
        return result.content;
    },
    addCourse: function(course) {
        console.log('ADDING COURSE');
        console.log(course);

        var course = {
            id: course.id,
            bcourses: course,
            staff: []
        };
        var courseDB = Courses.find({'id': course.id});
        if (courseDB.fetch().length == 0) {
            Courses.insert(course);
        }
        Meteor.users.update({ '_id':Meteor.userId() },
                            { $addToSet: { 'courses': course.id } });
        return course;
    }
});
<|endoftext|>


<commit_before>'use strict';

var assert = require("assert");
var fs = require('fs');
var path = require('path');
var middleware = require('../index.js');

//Helper Functions
function getManifest(server, callback) {
  var buf = [];
  var ccHeader = null;
  var ctHeader = null;

  var mockResponse = {
    end: function(s) {
      if (typeof s === 'string') {
        buf.push(s);
      }
      try {
        assert.equal(ccHeader, 'no-cache', 'Cache-Control header should be no-cache');
        assert.equal(ctHeader, 'text/cache-manifest', 'Content-Type header should be text/cache-manifest');
        var manifest = parseManifest(buf.join(''));
        callback(null, manifest);
      } catch(err) {
        callback(err);
      }
    },
    write: function(s) {
      if (typeof s === 'string') {
        buf.push(s);
      }
    },
    set: function(name, value) {
      if (name === 'Cache-Control') {
        ccHeader = value;
      } else if (name === 'Content-Type') {
        ctHeader = value;
      }
    }
  };

  server(null, mockResponse);
}

function parseManifest(body) {
  var manifest = { CACHE: [], COMMENTS: [] };
  var lines = body.split('\n');
  assert.equal(lines[0], 'CACHE MANIFEST', 'First line should be CACHE MANIFEST');
  var section = 'CACHE';
  for (var i = 1; i < lines.length; i++) {
    var line = lines[i];
    assert.equal(line.trim(), line, 'No extra whitespace expected in cache manifest');
    if (line.length === 0) {
      //Blank line
      section = null;
    } else if (line.startsWith('#')) {
      //Comment
      manifest['COMMENTS'].push(line.substr(1));
    } else if (section === null) {
      //New section header
      assert(line.endsWith(':'), 'Cache section lines should end with :');
      section = line.substr(0, line.length - 1);
      if (section !== 'CACHE') {
        assert(!(section in manifest), 'Multiple copies of section header ' + section + ' found in manifest');
        manifest[section] = [];
      }
    } else {
      //Inside of an existing section
      manifest[section].push(line);
    }
  }

  assert.deepEqual(manifest['CACHE'].slice().sort(), manifest['CACHE'], 'Cache entries should be soted');

  return manifest;
}

function addFile(path) {

}

function touchFile(path) {

}

function delFile(path) {

}

function addDir(path) {

}

function rmDir(path) {

}

function assertInManifest(server, line) {

}

function assertManifestChanged(server) {

}

function assertManifestNotChanged(server) {

}

var CONFIG = [{
    file: 'test_files/some_files',
    url: 'some'
  }, {
    file: 'test_files/more_files',
    url: 'test_files/more_files'
  }, {
    file: 'test_files/hello.txt',
    url: 'hello.txt'
  }
];

var INITIAL_FILES = [
  'test_files/hello.txt',
  'test_files/some_files/a.txt',
  'test_files/some_files/b.txt',
  'test_files/some_files/nested/x.txt',
  'test_files/some_files/nested/y.txt',
  'test_files/more_files/1.txt',
  'test_files/more_files/2.txt'
];

var INITIAL_URLS = [
  '/hello.txt',
  '/some/a.txt',
  '/some/b.txt',
  '/some/nested/x.txt',
  '/some/nested/y.txt',
  '/test_files/more_files/1.txt',
  '/test_files/more_files/2.txt'
];

//Tests
describe('Init', function() {
  it('should initialize properly', function (done) {
    middleware.generator(CONFIG, null, function(server) {
      server.stop();
      done();
    });
  });
});

describe('Check filesystem', function() {
  it('Should contain expected files', function(done) {
    var count = 0;
    for(var i = 0; i < INITIAL_FILES.length; i++) {
      var path = INITIAL_FILES[i];
      fs.stat(path, function(err, stat) {
        count++;
        try {
          assert.equal(err, null, 'Error getting fs stat for ' + path);
          assert(stat.isFile(), 'Missing initial file ' + path);
          if (count === INITIAL_FILES.length) {
            done();
          }
        } catch(err) {
          done(err);
        }
      });
    }
  });
});

describe('Check initial data', function() {
  it('Should contain expected elements', function (done) {
    middleware.generator(CONFIG, null, function(server) {
      getManifest(server, function(err, manifest) {
        if (err) {
          done(err);
          server.stop();
          return;
        }
        try {
          assert.deepEqual(manifest['NETWORK'], ['*'], 'Network section doesn\'t hold expected value'); //TODO: pull this from opts
          assert.deepEqual(manifest['CACHE'], INITIAL_URLS, 'Cache section doesn\'t hold expected value(s)');
          done();
        } catch (err) {
          done(err);
        } finally {
          server.stop();
        }
      });
    });
  });

  it('Should contain expected elements with absolute paths', function (done) {
    var absolutePaths = [];
    for (var i = 0; i < CONFIG.length; i++) {
      absolutePaths.push({
        file: path.resolve(process.cwd(), CONFIG[i]['file']),
        url: CONFIG[i]['url']
      });
    }

    middleware.generator(absolutePaths, null, function(server) {
      getManifest(server, function(err, manifest) {
        if (err) {
          done(err);
          server.stop();
          return;
        }
        try {
          assert.deepEqual(manifest['NETWORK'], ['*'], 'Network section doesn\'t hold expected value'); //TODO: pull this from opts
          assert.deepEqual(manifest['CACHE'], INITIAL_URLS, 'Cache section doesn\'t hold expected value(s)');
          done();
        } catch (err) {
          done(err);
        } finally {
          server.stop();
        }
      });
    });
  });
});

//TODO: observe changes to newly created files

//TODO: notice files added to newly created nested directories

//TODO: observe file additions and modifications to those new files

//TODO: notice file deletions

//folder deletions!<commit_msg>Added another TODO<commit_after>'use strict';

var assert = require("assert");
var fs = require('fs');
var path = require('path');
var middleware = require('../index.js');

//Helper Functions
function getManifest(server, callback) {
  var buf = [];
  var ccHeader = null;
  var ctHeader = null;

  var mockResponse = {
    end: function(s) {
      if (typeof s === 'string') {
        buf.push(s);
      }
      try {
        assert.equal(ccHeader, 'no-cache', 'Cache-Control header should be no-cache');
        assert.equal(ctHeader, 'text/cache-manifest', 'Content-Type header should be text/cache-manifest');
        var manifest = parseManifest(buf.join(''));
        callback(null, manifest);
      } catch(err) {
        callback(err);
      }
    },
    write: function(s) {
      if (typeof s === 'string') {
        buf.push(s);
      }
    },
    set: function(name, value) {
      if (name === 'Cache-Control') {
        ccHeader = value;
      } else if (name === 'Content-Type') {
        ctHeader = value;
      }
    }
  };

  server(null, mockResponse);
}

function parseManifest(body) {
  var manifest = { CACHE: [], COMMENTS: [] };
  var lines = body.split('\n');
  assert.equal(lines[0], 'CACHE MANIFEST', 'First line should be CACHE MANIFEST');
  var section = 'CACHE';
  for (var i = 1; i < lines.length; i++) {
    var line = lines[i];
    assert.equal(line.trim(), line, 'No extra whitespace expected in cache manifest');
    if (line.length === 0) {
      //Blank line
      section = null;
    } else if (line.startsWith('#')) {
      //Comment
      manifest['COMMENTS'].push(line.substr(1));
    } else if (section === null) {
      //New section header
      assert(line.endsWith(':'), 'Cache section lines should end with :');
      section = line.substr(0, line.length - 1);
      if (section !== 'CACHE') {
        assert(!(section in manifest), 'Multiple copies of section header ' + section + ' found in manifest');
        manifest[section] = [];
      }
    } else {
      //Inside of an existing section
      manifest[section].push(line);
    }
  }

  assert.deepEqual(manifest['CACHE'].slice().sort(), manifest['CACHE'], 'Cache entries should be soted');

  return manifest;
}

function addFile(path) {

}

function touchFile(path) {

}

function delFile(path) {

}

function addDir(path) {

}

function rmDir(path) {

}

function assertInManifest(server, line) {

}

function assertManifestChanged(server) {

}

function assertManifestNotChanged(server) {

}

var CONFIG = [{
    file: 'test_files/some_files',
    url: 'some'
  }, {
    file: 'test_files/more_files',
    url: 'test_files/more_files'
  }, {
    file: 'test_files/hello.txt',
    url: 'hello.txt'
  }
];

var INITIAL_FILES = [
  'test_files/hello.txt',
  'test_files/some_files/a.txt',
  'test_files/some_files/b.txt',
  'test_files/some_files/nested/x.txt',
  'test_files/some_files/nested/y.txt',
  'test_files/more_files/1.txt',
  'test_files/more_files/2.txt'
];

var INITIAL_URLS = [
  '/hello.txt',
  '/some/a.txt',
  '/some/b.txt',
  '/some/nested/x.txt',
  '/some/nested/y.txt',
  '/test_files/more_files/1.txt',
  '/test_files/more_files/2.txt'
];

//Tests
describe('Init', function() {
  it('should initialize properly', function (done) {
    middleware.generator(CONFIG, null, function(server) {
      server.stop();
      done();
    });
  });
});

describe('Check filesystem', function() {
  it('Should contain expected files', function(done) {
    var count = 0;
    for(var i = 0; i < INITIAL_FILES.length; i++) {
      var path = INITIAL_FILES[i];
      fs.stat(path, function(err, stat) {
        count++;
        try {
          assert.equal(err, null, 'Error getting fs stat for ' + path);
          assert(stat.isFile(), 'Missing initial file ' + path);
          if (count === INITIAL_FILES.length) {
            done();
          }
        } catch(err) {
          done(err);
        }
      });
    }
  });
});

describe('Check initial data', function() {
  it('Should contain expected elements', function (done) {
    middleware.generator(CONFIG, null, function(server) {
      getManifest(server, function(err, manifest) {
        if (err) {
          done(err);
          server.stop();
          return;
        }
        try {
          assert.deepEqual(manifest['NETWORK'], ['*'], 'Network section doesn\'t hold expected value'); //TODO: pull this from opts
          assert.deepEqual(manifest['CACHE'], INITIAL_URLS, 'Cache section doesn\'t hold expected value(s)');
          done();
        } catch (err) {
          done(err);
        } finally {
          server.stop();
        }
      });
    });
  });

  it('Should contain expected elements with absolute paths', function (done) {
    var absolutePaths = [];
    for (var i = 0; i < CONFIG.length; i++) {
      absolutePaths.push({
        file: path.resolve(process.cwd(), CONFIG[i]['file']),
        url: CONFIG[i]['url']
      });
    }

    middleware.generator(absolutePaths, null, function(server) {
      getManifest(server, function(err, manifest) {
        if (err) {
          done(err);
          server.stop();
          return;
        }
        try {
          assert.deepEqual(manifest['NETWORK'], ['*'], 'Network section doesn\'t hold expected value'); //TODO: pull this from opts
          assert.deepEqual(manifest['CACHE'], INITIAL_URLS, 'Cache section doesn\'t hold expected value(s)');
          done();
        } catch (err) {
          done(err);
        } finally {
          server.stop();
        }
      });
    });
  });
});

//TODO: observe changes to newly created files

//TODO: notice files added to newly created nested directories

//TODO: observe file additions and modifications to those new files

//TODO: notice file deletions

//TODO: folder deletions!<|endoftext|>