<commit_before>var SignUp = require('../signUp.js');
new SignUp('#signUpScope', '/api/v1/register/');
var TweenLite = require('TweenLite');
require('EasePack');
require('vendor/youtube');

// ANIMATION FOR FRONT PAGE

$( document ).ready(function() {
  $('#logo').removeClass('off');
  $('.youtube').YouTubeModal({autoplay:1, width:640, height:480});
});

(function(){
  if ($(window).scrollTop() > 650) {
      $('.navbar').addClass('off');
  }
  else {
      $('.navbar').removeClass('off');
  }
    setTimeout(arguments.callee, 40);
})();

var waitForFinalEvent = (function () {
  var timers = {};
  return function (callback, ms, uniqueId) {
    if (!uniqueId) {
      uniqueId = 'Don\'t call this twice without a uniqueId';
    }
    if (timers[uniqueId]) {
      clearTimeout (timers[uniqueId]);
    }
    timers[uniqueId] = setTimeout(callback, ms);
  };
})();

(function() {

    var width, height, largeHeader, canvas, ctx, points, target, animateHeader = true;

    // Main
    initHeader();
    initAnimation();
    addListeners();

    function initHeader() {
        width = window.innerWidth;
        height = '800';
        target = {x: width/2, y: height/2};

        largeHeader = document.getElementById('home-hero');

        canvas = $('#demo-canvas')[0];
        canvas.width = width;
        canvas.height = height;
        ctx = canvas.getContext('2d');

        // create points
        points = [];
        for(var x = 0; x < width; x = x + width/20) {
            for(var y = 0; y < height; y = y + height/20) {
                var px = x + Math.random()*width/20;
                var py = y + Math.random()*height/20;
                var p = {x: px, originX: px, y: py, originY: py };
                points.push(p);
            }
        }

        // for each point find the 5 closest points
        for(var i = 0; i < points.length; i++) {
            var closest = [];
            var p1 = points[i];
            for(var j = 0; j < points.length; j++) {
                var p2 = points[j];
                if (p1 !== p2) {
                    var placed = false;
                    for(var k = 0; k < 5; k++) {
                        if(!placed) {
                            if(closest[k] === undefined) {
                                closest[k] = p2;
                                placed = true;
                            }
                        }
                    }

                    for(var m = 0; m < 5; m++) {
                        if(!placed) {
                            if(getDistance(p1, p2) < getDistance(p1, closest[m])) {
                                closest[m] = p2;
                                placed = true;
                            }
                        }
                    }
                }
            }
            p1.closest = closest;
        }

        // assign a circle to each point
        for(var n in points) {
            var c = new Circle(points[n], 2+Math.random()*2, 'rgba(255,255,255,0.3)');
            points[n].circle = c;
        }
    }

    // Event handling
    function addListeners() {
        setPos();
        window.addEventListener('scroll', scrollCheck);
        window.addEventListener('resize', resize);
    }

    function setPos(e) {
        target.x = window.innerWidth/2;
        target.y = 330;
    }

    function scrollCheck() {
        if(document.body.scrollTop > height) animateHeader = false;
        else animateHeader = true;
    }

    function resize() {
        if (window.innerWidth > 990) {
            waitForFinalEvent(function(){
                $('#demo-canvas').remove();
                $('#canvas-container').append('<canvas id="demo-canvas"></canvas>');
                initHeader();
                initAnimation();
            }, 300, 'resize');
        }
    }

    // animation
    function initAnimation() {
        animate();
        for(var i in points) {
            shiftPoint(points[i]);
        }
    }

    function animate() {
        if(animateHeader) {
            ctx.clearRect(0,0,width,height);
            for(var i in points) {
                // detect points in range
                if(Math.abs(getDistance(target, points[i])) < 4000) {
                    points[i].active = 0.3;
                    points[i].circle.active = 0.6;
                } else if(Math.abs(getDistance(target, points[i])) < 20000) {
                    points[i].active = 0.1;
                    points[i].circle.active = 0.3;
                } else if(Math.abs(getDistance(target, points[i])) < 40000) {
                    points[i].active = 0.02;
                    points[i].circle.active = 0.1;
                } else {
                    points[i].active = 0;
                    points[i].circle.active = 0;
                }

                drawLines(points[i]);
                points[i].circle.draw();
            }
        }
        requestAnimationFrame(animate);
    }

    function shiftPoint(p) {
        TweenLite.to(p, 1+1*Math.random(), {x:p.originX-50+Math.random()*100,
            y: p.originY-50+Math.random()*100, ease:Circ.easeInOut,
            onComplete: function() {
                shiftPoint(p);
            }});
    }

    // Canvas manipulation
    function drawLines(p) {
        if(!p.active) return;
        for(var i in p.closest) {
            ctx.beginPath();
            ctx.moveTo(p.x, p.y);
            ctx.lineTo(p.closest[i].x, p.closest[i].y);
            ctx.strokeStyle = 'rgba(156,217,249,'+ p.active+')';
            ctx.stroke();
        }
    }

    function Circle(pos,rad,color) {
        var _this = this;

        // constructor
        (function() {
            _this.pos = pos || null;
            _this.radius = rad || null;
            _this.color = color || null;
        })();

        this.draw = function() {
            if(!_this.active) return;
            ctx.beginPath();
            ctx.arc(_this.pos.x, _this.pos.y, _this.radius, 0, 2 * Math.PI, false);
            ctx.fillStyle = 'rgba(156,217,249,'+ _this.active+')';
            ctx.fill();
        };
    }

    // Util
    function getDistance(p1, p2) {
        return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
    }

})();<commit_msg>Remove unused function<commit_after>var SignUp = require('../signUp.js');
new SignUp('#signUpScope', '/api/v1/register/');
var TweenLite = require('TweenLite');
require('EasePack');
require('vendor/youtube');

// ANIMATION FOR FRONT PAGE

$( document ).ready(function() {
  $('#logo').removeClass('off');
  $('.youtube').YouTubeModal({autoplay:1, width:640, height:480});
});

var waitForFinalEvent = (function () {
  var timers = {};
  return function (callback, ms, uniqueId) {
    if (!uniqueId) {
      uniqueId = 'Don\'t call this twice without a uniqueId';
    }
    if (timers[uniqueId]) {
      clearTimeout (timers[uniqueId]);
    }
    timers[uniqueId] = setTimeout(callback, ms);
  };
})();

(function() {

    var width, height, largeHeader, canvas, ctx, points, target, animateHeader = true;

    // Main
    initHeader();
    initAnimation();
    addListeners();

    function initHeader() {
        width = window.innerWidth;
        height = '800';
        target = {x: width/2, y: height/2};

        largeHeader = document.getElementById('home-hero');

        canvas = $('#demo-canvas')[0];
        canvas.width = width;
        canvas.height = height;
        ctx = canvas.getContext('2d');

        // create points
        points = [];
        for(var x = 0; x < width; x = x + width/20) {
            for(var y = 0; y < height; y = y + height/20) {
                var px = x + Math.random()*width/20;
                var py = y + Math.random()*height/20;
                var p = {x: px, originX: px, y: py, originY: py };
                points.push(p);
            }
        }

        // for each point find the 5 closest points
        for(var i = 0; i < points.length; i++) {
            var closest = [];
            var p1 = points[i];
            for(var j = 0; j < points.length; j++) {
                var p2 = points[j];
                if (p1 !== p2) {
                    var placed = false;
                    for(var k = 0; k < 5; k++) {
                        if(!placed) {
                            if(closest[k] === undefined) {
                                closest[k] = p2;
                                placed = true;
                            }
                        }
                    }

                    for(var m = 0; m < 5; m++) {
                        if(!placed) {
                            if(getDistance(p1, p2) < getDistance(p1, closest[m])) {
                                closest[m] = p2;
                                placed = true;
                            }
                        }
                    }
                }
            }
            p1.closest = closest;
        }

        // assign a circle to each point
        for(var n in points) {
            var c = new Circle(points[n], 2+Math.random()*2, 'rgba(255,255,255,0.3)');
            points[n].circle = c;
        }
    }

    // Event handling
    function addListeners() {
        setPos();
        window.addEventListener('scroll', scrollCheck);
        window.addEventListener('resize', resize);
    }

    function setPos(e) {
        target.x = window.innerWidth/2;
        target.y = 330;
    }

    function scrollCheck() {
        if(document.body.scrollTop > height) animateHeader = false;
        else animateHeader = true;
    }

    function resize() {
        if (window.innerWidth > 990) {
            waitForFinalEvent(function(){
                $('#demo-canvas').remove();
                $('#canvas-container').append('<canvas id="demo-canvas"></canvas>');
                initHeader();
                initAnimation();
            }, 300, 'resize');
        }
    }

    // animation
    function initAnimation() {
        animate();
        for(var i in points) {
            shiftPoint(points[i]);
        }
    }

    function animate() {
        if(animateHeader) {
            ctx.clearRect(0,0,width,height);
            for(var i in points) {
                // detect points in range
                if(Math.abs(getDistance(target, points[i])) < 4000) {
                    points[i].active = 0.3;
                    points[i].circle.active = 0.6;
                } else if(Math.abs(getDistance(target, points[i])) < 20000) {
                    points[i].active = 0.1;
                    points[i].circle.active = 0.3;
                } else if(Math.abs(getDistance(target, points[i])) < 40000) {
                    points[i].active = 0.02;
                    points[i].circle.active = 0.1;
                } else {
                    points[i].active = 0;
                    points[i].circle.active = 0;
                }

                drawLines(points[i]);
                points[i].circle.draw();
            }
        }
        requestAnimationFrame(animate);
    }

    function shiftPoint(p) {
        TweenLite.to(p, 1+1*Math.random(), {x:p.originX-50+Math.random()*100,
            y: p.originY-50+Math.random()*100, ease:Circ.easeInOut,
            onComplete: function() {
                shiftPoint(p);
            }});
    }

    // Canvas manipulation
    function drawLines(p) {
        if(!p.active) return;
        for(var i in p.closest) {
            ctx.beginPath();
            ctx.moveTo(p.x, p.y);
            ctx.lineTo(p.closest[i].x, p.closest[i].y);
            ctx.strokeStyle = 'rgba(156,217,249,'+ p.active+')';
            ctx.stroke();
        }
    }

    function Circle(pos,rad,color) {
        var _this = this;

        // constructor
        (function() {
            _this.pos = pos || null;
            _this.radius = rad || null;
            _this.color = color || null;
        })();

        this.draw = function() {
            if(!_this.active) return;
            ctx.beginPath();
            ctx.arc(_this.pos.x, _this.pos.y, _this.radius, 0, 2 * Math.PI, false);
            ctx.fillStyle = 'rgba(156,217,249,'+ _this.active+')';
            ctx.fill();
        };
    }

    // Util
    function getDistance(p1, p2) {
        return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
    }

})();<|endoftext|>


<commit_before>
import React from 'react'
import ReactDOM from 'react-dom'
import Playground from 'component-playground'
import {Select} from '../../../'

const defaultSelect =
`<select>
  <option>one</option>
  <option>two</option>
  <option>three</option>
</select>`

const _select =
`class App extends React.Component {
  state = {
    selected: -1,
  }

  onChange = (index) => {
    this.setState({
      selected: index
    })
  }

  render () {
    return (

      <Select
        onChange={this.onChange}
        items={['Blue', 'Red', 'Green']}
        selectedIndex={this.state.selected}
      />

    )
  }
}

ReactDOM.render(<App />, mountNode)`

const selectWithScrolling =
`class App extends React.Component {
  state = {
    selected: -1,
  }

  onChange = (index) => {
    this.setState({
      selected: index
    })
  }

  render () {
    return (

      <Select
        onChange={this.onChange}
        items={['Blue', 'Red', 'Green', 'Yellow', 'Orange', 'Black', 'White']}
        selectedIndex={this.state.selected}
      />

    )
  }
}

ReactDOM.render(<App />, mountNode)`

const selectWithLabel =
`class App extends React.Component {
  state = {
    selected: -1,
  }

  onChange = (index) => {
    this.setState({
      selected: index
    })
  }

  render () {
    return (

      <Select
        label='Some label'
        onChange={this.onChange}
        items={['Blue', 'Red', 'Green']}
        selectedIndex={this.state.selected}
      />

    )
  }
}

ReactDOM.render(<App />, mountNode)`

export default class SelectRoute extends React.Component {

  state = {
    selected: -1,
    selectedWithScrolling: -1
  }

  onChange = (index) => {
    this.setState({
      selected: index
    })
  }

  onChangeWithScrolling = (index) => {
    this.setState({
      selectedWithScrolling: index
    })
  }

  render () {
    return (

Default select

          <Playground
            codeText={defaultSelect}
            scope={{React}}
          />

Select

          <Playground
            docClass={Select}
            noRender={false}
            codeText={_select}
            scope={{React, ReactDOM, Select}}
          />

Select with scrolling

          <Playground
            docClass={Select}
            noRender={false}
            codeText={selectWithScrolling}
            scope={{React, ReactDOM, Select}}
          />

Select with label

          <Playground
            docClass={Select}
            noRender={false}
            codeText={selectWithLabel}
            scope={{React, ReactDOM, Select}}
          />

    )
  }
}
<commit_msg>rename variable<commit_after>
import React from 'react'
import ReactDOM from 'react-dom'
import Playground from 'component-playground'
import {Select} from '../../../'

const defaultSelect =
`<select>
  <option>one</option>
  <option>two</option>
  <option>three</option>
</select>`

const selectComponent =
`class App extends React.Component {
  state = {
    selected: -1,
  }

  onChange = (index) => {
    this.setState({
      selected: index
    })
  }

  render () {
    return (

      <Select
        onChange={this.onChange}
        items={['Blue', 'Red', 'Green']}
        selectedIndex={this.state.selected}
      />

    )
  }
}

ReactDOM.render(<App />, mountNode)`

const selectWithScrolling =
`class App extends React.Component {
  state = {
    selected: -1,
  }

  onChange = (index) => {
    this.setState({
      selected: index
    })
  }

  render () {
    return (

      <Select
        onChange={this.onChange}
        items={['Blue', 'Red', 'Green', 'Yellow', 'Orange', 'Black', 'White']}
        selectedIndex={this.state.selected}
      />

    )
  }
}

ReactDOM.render(<App />, mountNode)`

const selectWithLabelComponent =
`class App extends React.Component {
  state = {
    selected: -1,
  }

  onChange = (index) => {
    this.setState({
      selected: index
    })
  }

  render () {
    return (

      <Select
        label='Some label'
        onChange={this.onChange}
        items={['Blue', 'Red', 'Green']}
        selectedIndex={this.state.selected}
      />

    )
  }
}

ReactDOM.render(<App />, mountNode)`

export default class SelectRoute extends React.Component {

  state = {
    selected: -1,
    selectedWithScrolling: -1
  }

  onChange = (index) => {
    this.setState({
      selected: index
    })
  }

  onChangeWithScrolling = (index) => {
    this.setState({
      selectedWithScrolling: index
    })
  }

  render () {
    return (

Default select

          <Playground
            codeText={defaultSelect}
            scope={{React}}
          />

Select

          <Playground
            docClass={Select}
            noRender={false}
            codeText={selectComponent}
            scope={{React, ReactDOM, Select}}
          />

Select with scrolling

          <Playground
            docClass={Select}
            noRender={false}
            codeText={selectWithScrolling}
            scope={{React, ReactDOM, Select}}
          />

Select with label

          <Playground
            docClass={Select}
            noRender={false}
            codeText={selectWithLabelComponent}
            scope={{React, ReactDOM, Select}}
          />

    )
  }
}
<|endoftext|>


<commit_before>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'Inkbunny',
    version:'0.1',
    prepareImgLinks:function (callback) {
        var res = [];

        //  TODO
        //  change to full size image, not screen
        //  hoverzooming updated submissions in user's new submissions notifications will screw up indexing
        //  add same multipage handling for keypress

        //find all submission links
        $('a[href*="s/"]').filter(function() {
            return /s\/\d+(-p\d+)?(-latest)?(-?#pictop)?\/?$/.test($(this).attr('href'));
        }).one('mouseover', function() {
            var link = $(this),
                url = link.attr('href');

            //follow a submission link
            $.ajax(url).done(function(response) {
                //console.log("url: " + url);

                //get the submission's src
                var img = $('img[src*="files/screen/"]', response).first();
                //console.log(img);

                if (img.length) {
                    link.data().hoverZoomSrc = [img.attr('src')];
                } else {
                    var thumbSrc = link.find('img').attr('src');
                    if (!(/_noncustom\.\w+$/.test(thumbSrc)))
                        link.data().hoverZoomSrc = [thumbSrc.replace(/thumbnails\/\w+/, 'thumbnails/huge')];
                    else
                        link.data().hoverZoomSrc = [thumbSrc];
                }
                link.data().hoverZoomCaption = $(response).text().replace(/^\s*(.*) <[\s\S]*/, '$1');

                //console.log(link.data());
                //console.log("mainSrc: " + img.attr('src'));

                //check if the submission has other pages. these are found in links
                //that contain the base url and have an img child
                var multipageContainer = $('#files_area ~ div', response),
                    firstPage = url.replace(/^(.*s\/\d+).*$/, '$1'),
                    multipageLinks = $('a[href*="' + firstPage + '"]:has(img)', multipageContainer);

                /* console.log("firstPage: " + firstPage);
                console.log("multipageLinks:");
                console.log(multipageLinks); */

                //submission has multiple pages
                if (multipageLinks.length) {
                    //console.log("multipageLinks URLs:");

                    link.data().hoverZoomGallerySrc = [];
                    link.data().hoverZoomGalleryCaption = [];

                    var startIndex = url.replace(/^(.*s\/\d+)-p(\d+)?.*$/, '$2');
                    startIndex = (startIndex === url) ? 0 : parseInt(startIndex) - 1;
                    link.data().hoverZoomGalleryIndex = startIndex;

                    var i = 0, loopData = {
                        start: mod(startIndex - 2, multipageLinks.length),
                        end: mod(startIndex + 2, multipageLinks.length) };
                    link.on('wheel', {arg1: loopData, arg2: multipageLinks}, onMouseWheel);
                    multipageLinks.each(function() {
                        var multipageLink = $(this).attr('href');
                        //console.log(multipageLink);

                        link.data().hoverZoomGallerySrc.push([]);
                        link.data().hoverZoomGalleryCaption.push(link.data().hoverZoomCaption);

                        if (multipageLinks.length > 4) {
                            if (inCircularRange(loopData.start, loopData.end, i)) {
                                prepareMultipageSrcAsync(link, multipageLink, i);
                            } else {
                                /* multipageLink.on('updateRange', function() {
                                    if (!inCircularRange(start, end, i) &&
                                            galleryIndexNearEdge(start, end,
                                                link.data().hoverZoomGalleryIndex,
                                                multipageLinks.length)) {
                                        prepareMultipageSrcAsync(link, multipageLink, start, end, i);
                                        multipageLink.off('updateRange');
                                    }
                                }); */

                            }

                            /* var promise = new Promise(function(resolve, reject) {
                                if (Math.abs(i - start) < 3) {
                                    resolve(i, -1);
                                } else if (Math.abs(end - i) < 3) {
                                    resolve(i, 1);
                                }
                            });

                            promise.then(function(index, dir) {
                                if (dir === -1)
                                    console.log("Load more images from start");
                                else if (dir === 1)
                                    console.log("Load more images from end");

                            }); */
                        } else {
                            prepareMultipageSrcAsync(link, multipageLink, i);
                        }

                        i++;
                    });
                }
                link.addClass('hoverZoomLink');
                //callback($([link]));
                res.push(link);
                hoverZoom.displayPicFromElement(link);
            });
        });

        function prepareMultipageSrcAsync(origLink, multipageLink, i) {
            $.ajax(multipageLink).done(function(nestedResponse) {
                var multipageImg = $('img[src*="files/screen/"]', nestedResponse).first();
                if (multipageImg.length) {
                    origLink.data().hoverZoomGallerySrc[i] = [multipageImg.attr('src')];
                } else {
                    var thumbSrc = origLink.find('img').attr('src');
                    if (/\/images78\/overlays/.test(thumbSrc))
                        origLink.data().hoverZoomGallerySrc[i] = [thumbSrc];
                    else if (!(/_noncustom\.\w+$/.test(thumbSrc)))
                        origLink.data().hoverZoomGallerySrc[i] = [thumbSrc.replace(/thumbnails\/\w+/, 'thumbnails/huge')];
                }

                /* console.log("multipage ajax");
                console.log("i = " + i);
                console.log("original link: " + link.attr('href'));
                console.log("multipageLink: " + multipageLink);
                console.log("multipageImg: " + multipageImg);
                console.log(link.data()); */
                //callback($([link]));

                /* var wheelEvent = $.Event("wheel");
                wheelEvent.deltaY = 0;
                $(document).trigger(wheelEvent); */
            });
        }

        function mod(m, n) {
            return ((m % n) + n) % n;
        }

        function inCircularRange(start, end, i) {
            if (start <= end)
                return (i >= start && i <= end);
            else
                return (i >= start || i <= end);
        }

        function galleryIndexNearEdge(start, end, galleryIndex, galleryLength) {
            return inCircularRange(end, mod(start + 2, galleryLength), galleryIndex) ||
                inCircularRange(mod(end - 2, galleryLength), start, galleryIndex);
        }

        function onMouseWheel(event) {
            var loopData = event.data.arg1,
                multipageLinks = event.data.arg2,
                totalLinks = multipageLinks.length,
                link = hoverZoom.currentLink,
                data = link.data(),
                rot = (event.originalEvent.wheelDeltaY > 0) ? -1 : 1,
                nextIndex = mod(data.hoverZoomGalleryIndex + rot, totalLinks),
                loadIndex = mod(data.hoverZoomGalleryIndex + 3 * rot, totalLinks);
            console.log("start: " + loopData.start);
            console.log("end: " + loopData.end);

            if (!data.hoverZoomGallerySrc[nextIndex].length) {
                data.hoverZoomGalleryIndex = mod(data.hoverZoomGalleryIndex - rot, totalLinks);
                return;
            }

            if (data.hoverZoomGallerySrc && data.hoverZoomGallerySrc.length > 1) {
                console.log("scrolling to " + nextIndex + " from " + data.hoverZoomGalleryIndex);
                console.log("load " + loadIndex + "?");

                if (!inCircularRange(loopData.start, loopData.end, loadIndex) &&
                        galleryIndexNearEdge(loopData.start, loopData.end, nextIndex, totalLinks)) {
                    console.log("doing ajax");

                    prepareMultipageSrcAsync(link, multipageLinks[loadIndex].href, loadIndex);
                    if (rot === -1)
                        loopData.start = mod(loopData.start - 1, totalLinks);
                    else
                        loopData.end = mod(loopData.end + 1, totalLinks);
                } else if (Math.abs(loopData.end - loopData.start) === 1) {
                    link.off('wheel');
                }
            }
        }

        //console.log(res);
        callback($(res));
    }
});<commit_msg>Added keyboard support for multipage submissions<commit_after>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'Inkbunny',
    version:'0.1',
    prepareImgLinks:function (callback) {
        var res = [];

        //  TODO
        //  change to full size image, not screen
        //  hoverzooming updated submissions in user's new submissions notifications will screw up indexing

        //find all submission links
        $('a[href*="s/"]').filter(function() {
            return /s\/\d+(-p\d+)?(-latest)?(-?#pictop)?\/?$/.test($(this).attr('href'));
        }).one('mouseover', function() {
            var link = $(this),
                url = link.attr('href');

            //follow a submission link
            $.ajax(url).done(function(response) {
                //console.log("url: " + url);

                //get the submission's src
                var img = $('img[src*="files/screen/"]', response).first();
                //console.log(img);

                if (img.length) {
                    link.data().hoverZoomSrc = [img.attr('src')];
                } else {
                    var thumbSrc = link.find('img').attr('src');
                    if (!(/_noncustom\.\w+$/.test(thumbSrc)))
                        link.data().hoverZoomSrc = [thumbSrc.replace(/thumbnails\/\w+/, 'thumbnails/huge')];
                    else
                        link.data().hoverZoomSrc = [thumbSrc];
                }
                link.data().hoverZoomCaption = $(response).text().replace(/^\s*(.*) <[\s\S]*/, '$1');

                //console.log(link.data());
                //console.log("mainSrc: " + img.attr('src'));

                //check if the submission has other pages. these are found in links
                //that contain the base url and have an img child
                var multipageContainer = $('#files_area ~ div', response),
                    firstPage = url.replace(/^(.*s\/\d+).*$/, '$1'),
                    multipageLinks = $('a[href*="' + firstPage + '"]:has(img)', multipageContainer);

                /* console.log("firstPage: " + firstPage);
                console.log("multipageLinks:");
                console.log(multipageLinks); */

                //submission has multiple pages
                if (multipageLinks.length) {
                    //console.log("multipageLinks URLs:");

                    link.data().hoverZoomGallerySrc = [];
                    link.data().hoverZoomGalleryCaption = [];

                    var startIndex = url.replace(/^(.*s\/\d+)-p(\d+)?.*$/, '$2');
                    startIndex = (startIndex === url) ? 0 : parseInt(startIndex) - 1;
                    link.data().hoverZoomGalleryIndex = startIndex;

                    var i = 0, loopData = {
                        start: mod(startIndex - 2, multipageLinks.length),
                        end: mod(startIndex + 2, multipageLinks.length) };
                    link.on('wheel', {arg1: loopData, arg2: multipageLinks}, onMouseWheel);
                    link.hover(function() {
                        link.focus();
                    }, function() {
                        link.blur();
                    }).on('keydown', {arg1: loopData, arg2: multipageLinks}, onKeyDown);
                    link.focus();
                    multipageLinks.each(function() {
                        var multipageLink = $(this).attr('href');
                        //console.log(multipageLink);

                        link.data().hoverZoomGallerySrc.push([]);
                        link.data().hoverZoomGalleryCaption.push(link.data().hoverZoomCaption);

                        if (multipageLinks.length > 4) {
                            if (inCircularRange(loopData.start, loopData.end, i)) {
                                prepareMultipageSrcAsync(link, multipageLink, i);
                            }
                        } else {
                            prepareMultipageSrcAsync(link, multipageLink, i);
                        }

                        i++;
                    });
                }
                link.addClass('hoverZoomLink');
                res.push(link);
                hoverZoom.displayPicFromElement(link);
            });
        });

        function prepareMultipageSrcAsync(origLink, multipageLink, i) {
            $.ajax(multipageLink).done(function(nestedResponse) {
                var multipageImg = $('img[src*="files/screen/"]', nestedResponse).first();
                if (multipageImg.length) {
                    origLink.data().hoverZoomGallerySrc[i] = [multipageImg.attr('src')];
                } else {
                    var thumbSrc = origLink.find('img').attr('src');
                    if (/\/images78\/overlays/.test(thumbSrc))
                        origLink.data().hoverZoomGallerySrc[i] = [thumbSrc];
                    else if (!(/_noncustom\.\w+$/.test(thumbSrc)))
                        origLink.data().hoverZoomGallerySrc[i] = [thumbSrc.replace(/thumbnails\/\w+/, 'thumbnails/huge')];
                }
            });
        }

        function mod(m, n) {
            return ((m % n) + n) % n;
        }

        function inCircularRange(start, end, i) {
            if (start <= end)
                return (i >= start && i <= end);
            else
                return (i >= start || i <= end);
        }

        function galleryIndexNearEdge(start, end, galleryIndex, galleryLength) {
            return inCircularRange(end, mod(start + 2, galleryLength), galleryIndex) ||
                inCircularRange(mod(end - 2, galleryLength), start, galleryIndex);
        }

        function onMouseWheel(event) {
            var loopData = event.data.arg1,
                multipageLinks = event.data.arg2;

            if (event.originalEvent.wheelDeltaY > 0)
                multipageSrcHelper(loopData, multipageLinks, -1);
            else if (event.originalEvent.wheelDeltaY < 0)
                multipageSrcHelper(loopData, multipageLinks, 1);
        }

        function onKeyDown(event) {
            var loopData = event.data.arg1,
                multipageLinks = event.data.arg2;

            if (event.which == options.prevImgKey)
                multipageSrcHelper(loopData, multipageLinks, -1);
            else if (event.which == options.nextImgKey)
                multipageSrcHelper(loopData, multipageLinks, 1);
        }

        function multipageSrcHelper(loopData, multipageLinks, rot) {
            var totalLinks = multipageLinks.length,
                link = hoverZoom.currentLink,
                data = link.data(),
                nextIndex = mod(data.hoverZoomGalleryIndex + rot, totalLinks),
                loadIndex = mod(data.hoverZoomGalleryIndex + 3 * rot, totalLinks);
            console.log("start: " + loopData.start);
            console.log("end: " + loopData.end);

            if (!data.hoverZoomGallerySrc[nextIndex].length) {
                data.hoverZoomGalleryIndex = mod(data.hoverZoomGalleryIndex - rot, totalLinks);
                return;
            }

            if (data.hoverZoomGallerySrc && data.hoverZoomGallerySrc.length > 1) {
                console.log("scrolling to " + nextIndex + " from " + data.hoverZoomGalleryIndex);
                console.log("load " + loadIndex + "?");

                if (!inCircularRange(loopData.start, loopData.end, loadIndex) &&
                        galleryIndexNearEdge(loopData.start, loopData.end, nextIndex, totalLinks)) {
                    console.log("doing ajax");

                    prepareMultipageSrcAsync(link, multipageLinks[loadIndex].href, loadIndex);
                    if (rot === -1)
                        loopData.start = mod(loopData.start - 1, totalLinks);
                    else if (rot === 1)
                        loopData.end = mod(loopData.end + 1, totalLinks);
                } else if (Math.abs(loopData.end - loopData.start) === 1) {
                    link.off();
                }
            }
        }

        callback($(res));
    }
});<|endoftext|>


<commit_before>/**
* nodejs-piwik-api
**/

var http = require("http");
var url = require("url");

var PiwikAPI = function() {
	this.configure = this.configure.bind(this);
	this.get = this.get.bind(this);
};

PiwikAPI.prototype.configure = function(options) {
	if(!options) {
		console.log("Merci de spécifier des options");
		process.exit(1);
	}
	if(!options.url) {
		console.log("Please enter a valid url");
		process.exit(1);
	}
	if(options.url.indexOf("http://") < 0) {
		options.url = "http://" + options.url;
	}
	var u = url.parse(options.url);
	this.host = u.hostname || "";
	this.path = u.path || "";
	this.port = u.port || "";
	this.token = options.defaultToken || "anonymous";
}

PiwikAPI.prototype.get = function(options, vars, cb) {
	// options
	if(!options) {
		options = {};
	}
	var method = options.method;
	var token = options.token || this.token;

	// variables
	if(!vars) {
		vars = {};
	}
	var ch = "";
	for(key in vars) {
		var value = vars[key];
		if(Object.prototype.toString.call(value) === '[object Array]') {
			// array
			var tab = value;
			for(k in tab) {
				ch += "&" + key + "[]=" + encodeURIComponent(tab[k]);
			}
		} else if(Object.prototype.toString.call(value) === '[object Object]') {
			// object
			var tab = value;
			for(k in tab) {
				ch += "&" + key + "[" + k + "]=" + encodeURIComponent(tab[k]);
			}
		} else {
			// string
			ch += "&" + key + "=" + encodeURIComponent(value);
		}
	}
	// get
	var path = this.path + "?module=API&method=" + method + "&format=json&token_auth=" + token + ch;
	http.get({host: this.host, port: this.port, path: path}, function(response) {
		var str = "";
		response.on("data", function(chunk) {
			str += chunk;
		});
		response.on("end", function() {
			str = JSON.parse(str);
			cb(str);
		});
	});
};

module.exports = new PiwikAPI;<commit_msg>Update piwik-api.js<commit_after>/**
* nodejs-piwik-api
**/

var http = require("http");
var url = require("url");

var PiwikAPI = function() {
	this.configure = this.configure.bind(this);
	this.get = this.get.bind(this);
};

PiwikAPI.prototype.configure = function(options) {
	if(!options) {
		console.log("Merci de spécifier des options");
		process.exit(1);
	}
	if(!options.url) {
		console.log("Please enter a valid url");
		process.exit(1);
	}
	if(options.url.indexOf("http://") < 0) {
		options.url = "http://" + options.url;
	}
	var u = url.parse(options.url);
	this.host = u.hostname || "";
	this.path = u.path || "";
	this.port = options.port || "";
	this.token = options.defaultToken || "anonymous";
}

PiwikAPI.prototype.get = function(options, vars, cb) {
	// options
	if(!options) {
		options = {};
	}
	var method = options.method;
	var token = options.token || this.token;

	// variables
	if(!vars) {
		vars = {};
	}
	var ch = "";
	for(key in vars) {
		var value = vars[key];
		if(Object.prototype.toString.call(value) === '[object Array]') {
			// array
			var tab = value;
			for(k in tab) {
				ch += "&" + key + "[]=" + encodeURIComponent(tab[k]);
			}
		} else if(Object.prototype.toString.call(value) === '[object Object]') {
			// object
			var tab = value;
			for(k in tab) {
				ch += "&" + key + "[" + k + "]=" + encodeURIComponent(tab[k]);
			}
		} else {
			// string
			ch += "&" + key + "=" + encodeURIComponent(value);
		}
	}
	// get
	var path = this.path + "?module=API&method=" + method + "&format=json&token_auth=" + token + ch;
	http.get({host: this.host, port: this.port, path: path}, function(response) {
		var str = "";
		response.on("data", function(chunk) {
			str += chunk;
		});
		response.on("end", function() {
			str = JSON.parse(str);
			cb(str);
		});
	});
};

module.exports = new PiwikAPI;
<|endoftext|>


<commit_before>var _ = require('underscore');

var socketio = {};
var config, player;

// called when partyplay is started to initialize the plugin
// do any necessary initialization here
socketio.init = function(_player, callback, errCallback) {
    player = _player;
    config = _player.config;

    if(!player.expressServer) {
        errCallback('module must be initialized after expressjs module!');
    } else {
        socketio.io = require('socket.io')(player.expressServer);
        socketio.io.on('connection', function(socket) {
            if(player.nowPlaying) {
                socket.emit('playback', {
                    songID: player.nowPlaying.songID,
                    format: player.nowPlaying.format,
                    backendName: player.nowPlaying.backendName,
                    duration: player.nowPlaying.duration,
                    position: new Date() - player.nowPlaying.playbackStart
                });
            }
            socket.emit('queue', [player.nowPlaying, player.queue]);
        });

        player.socketio = socketio;

        console.log('listening on port ' + (process.env.PORT || 8080));
        callback();
    }
};

// updates to queue
socketio.onSongChange = function(player) {
    socketio.io.emit('playback', {
        songID: player.nowPlaying.songID,
        format: player.nowPlaying.format,
        backendName: player.nowPlaying.backendName,
        duration: player.nowPlaying.duration
    });
};

socketio.postSongQueued = function(player) {
    socketio.io.emit('queue', [player.nowPlaying, player.queue]);
};
socketio.onNextSongPrepareError = socketio.postSongQueued;
socketio.onSongPrepareError = socketio.postSongQueued;
socketio.onSongEnd = socketio.postSongQueued;

module.exports = socketio;
<commit_msg>emit queue onSongChange, not onSongEnd (queue hasn't updated then yet)<commit_after>var _ = require('underscore');

var socketio = {};
var config, player;

// called when partyplay is started to initialize the plugin
// do any necessary initialization here
socketio.init = function(_player, callback, errCallback) {
    player = _player;
    config = _player.config;

    if(!player.expressServer) {
        errCallback('module must be initialized after expressjs module!');
    } else {
        socketio.io = require('socket.io')(player.expressServer);
        socketio.io.on('connection', function(socket) {
            if(player.nowPlaying) {
                socket.emit('playback', {
                    songID: player.nowPlaying.songID,
                    format: player.nowPlaying.format,
                    backendName: player.nowPlaying.backendName,
                    duration: player.nowPlaying.duration,
                    position: new Date() - player.nowPlaying.playbackStart
                });
            }
            socket.emit('queue', [player.nowPlaying, player.queue]);
        });

        player.socketio = socketio;

        console.log('listening on port ' + (process.env.PORT || 8080));
        callback();
    }
};

// updates to queue
socketio.onSongChange = function(player) {
    socketio.io.emit('playback', {
        songID: player.nowPlaying.songID,
        format: player.nowPlaying.format,
        backendName: player.nowPlaying.backendName,
        duration: player.nowPlaying.duration
    });
    socketio.io.emit('queue', [player.nowPlaying, player.queue]);
};

socketio.postSongQueued = function(player) {
    socketio.io.emit('queue', [player.nowPlaying, player.queue]);
};
socketio.onNextSongPrepareError = socketio.postSongQueued;
socketio.onSongPrepareError = socketio.postSongQueued;

module.exports = socketio;
<|endoftext|>


<commit_before>var events = require('events'),
    Stream = require('stream').Stream,
    parsing = require('./parsing'),
    proto = require('./proto');

exports.emptyCache = parsing.emptyCache;
exports.set = parsing.set; // a function
exports.parseTemplate = parsing.parseTemplate;

var util = require('util');
function info(/*, objs */) {
  var args = Array.prototype.slice.call(arguments, 0);
  var strings = args.map(function(arg) {
    if (typeof(arg) == 'string')
      return arg;
    return util.inspect(arg, false, null);
  });
  console.log(strings.join(' '));
}

// todo:
//   implement ability to add templates asap-ly, so that the first one
//   can start rendering without its yield being specified yet

exports.render = function(output, templates /*, context, asap, callback*/) {
  // @output: a stream
  // @templates: an array of strings (coerces naked string to 1-array)
  // @context: a string or an array of strings
  // @callback: function(err) { }
  // @asap: boolean that determines how to handle missing variables.
  var args = Array.prototype.slice.call(arguments);
  // pop from the right
  var callback = typeof(args[args.length - 1]) === 'function' ? args.pop() : function() {};
  var asap = typeof(args[args.length - 1]) === 'boolean' ? args.pop() : false;
  var context = args.length > 2 ? args.pop() : {};
  var renderer = new StreamRenderer(context, asap, callback);
  renderer.stream.pipe(output);
  if (templates)
    renderer.start(templates);
  return renderer;
};

exports.renderString = function(names, context, callback) {
  // callback signature: function(err, string)
  // can I force it to be sync? callback is okay too, if not
  var renderer = new StringRenderer(context, false, callback);
  renderer.start(names);
  return renderer;
};

function escapeHtml(s) {
  return s.replace(/[&<>"]/g, function(s) {
    switch (s) {
      case '<': return '<';
      case '>': return '>';
      case '&': return '&';
      case '"': return '"';
      default: return s;
    }
  });
}

function dottedEval(context, expression) {
  // handles strings that occur in context or dotted paths that traverse a context object
  if (expression == '.') return context['.']; // for those embedded sections (silly Mu spec, should be _)

  var parts = expression.split('.');
  for (var i = 0, part; (part = parts[i]) !== undefined; i++) {
    context = context[part];
    if (context === undefined || context === null) break;
  }
  return context;
}

function expressionEval(context, expression) {
  // expression can be a function call, a boolean, or a simple string.
  var m;
  if (m = expression.match(/^(\S+)\s*([!=<>]+)\s*(\S+)$/)) {
    // booleans: ==, ===, !=, !==, <, <=, >, >=
    var left = dottedEval(context, m[1]);
    var op = m[2];
    var right = dottedEval(context, m[3]);
    if (op === '==') return left == right;
    else if (op === '===') return left === right;
    else if (op === '!=') return left != right;
    else if (op === '!==') return left !== right;
    else if (op === '<') return left < right;
    else if (op === '<=') return left <= right;
    else if (op === '>') return left > right;
    else if (op === '>=') return left >= right;
    else throw new Error("Unrecognized operator: " + op);
  }
  else if (m = expression.match(/^(\S+)\((\S*)\)$/)) {
    // functions.
    // open parens indicates function application,
    //   the entire following conditional is for functional application.
    // close_parens_index should be append_to_top.length - 1

    // String.substring takes two indices (not a length)
    // var argument_part = new_node.val.substring(open_parens_index + 1, close_parens_index);
    // trim whitespace/quotes since arguments can only be strings or ints anyway. At least, for now.
    // (todo: let them embed commas in strings)
    // console.log('\nm:', m[1], '(', m[2], ')', context);
    var func = dottedEval(context, m[1]) || eval(m[1]);
    var args = m[2].split(',').map(function(raw) {
      var val = raw.replace(/^\s+|\s+$/g, '');
      if (val.match(/^('|").*\1$/)) { // string literal
        val = val.slice(1, -1);
      }
      else if (val.match(/^-?\d+$/)) { // integer literal
        val = parseInt(val, 10);
      }
      else if (val.match(/^-?\d+\.\d+$/)) { // float literal
        val = parseFloat(val);
      }
      else if (val.match(/^\w+$/)) { // variable reference
        val = dottedEval(context, val);
      }
      return val;
    });

    return func.apply(null, args);
  }
  else {
    return dottedEval(context, expression);
  }
}

var Renderer = function(context, asap, callback) {
  this.initialize(context, asap, callback);
};
Renderer.prototype = new events.EventEmitter();
Renderer.prototype.initialize = function(context, asap, callback) {
  this.context = context;
  this.asap = asap;
  this.callback = callback;

  this.template_stack = [];
};

Renderer.prototype.extendContext = function(obj, val) {
  if (val !== undefined) {
    this.context[obj] = val;
  }
  else {
    for (var attr in obj) {
      this.context[attr] = obj[attr];
    }
  }
  this.emit('bump');
  return this; // chainable
};
Renderer.prototype.extendTemplateStack = function(templates) {
  Array.prototype.push[Array.isArray(templates) ? 'apply' : 'call'](this.template_stack, templates);
  this.emit('bump');
  return this; // chainable
};
Renderer.prototype.force = function() {
  // use force to quit waiting for new context variables, and simply leave gaps for missing context variables, where possible
  this.asap = false;
  this.emit('bump');
  return this; // chainable
};
Renderer.prototype.start = function(templates, context, asap) { // aka render_global
  this.extendTemplateStack(templates);

  if (context !== undefined) {
    this.extendContext(context);
  }
  if (asap !== undefined) {
    this.asap = asap;
  }
  var renderer = this;
  var template_name = renderer.template_stack.shift();
  parsing.hitCache(template_name, function(err, tokens) {
    if (err) console.error(err);
    renderer.renderTokens(tokens, renderer.context, function(err) {
      renderer.outputEnd(err);
    });
  });
  return this;
};
Renderer.prototype.sectionRender = function(node, item, context, callback) {
  // for an object with properties, we DO NOT expose it as _, which causes problems with circularity.
  // to comply with mu, and for the sake of concision, we expose its properties nakedly.
  // however, if there is a sub name, we box it as that.
  var local_item = item;
  if (typeof(item) !== 'object' || node.sub) {
    // for strings, numbers, booleans, etc. ... or boxed objects
    local_item = {};
    local_item[node.sub || '.'] = item;
  }
  // else {proto.extend(item, local_item); }
  // proto.extend(item, context);
  proto.push(local_item, context);
  // so now it's item = {cool: 'stuff',
  //   __proto__: {original_context_var: 192, __proto__: {}.__proto__}}

  this.renderTokens(node.block, local_item, function() {
    proto.pop(local_item);
    callback();
  });
};

Renderer.prototype.renderTokens = function(tokens, context, callback) {
  var renderer = this, i = 0;
  (function next() {
    var node = tokens[i++];
    if (node === undefined) {
      // we're done! (with this scope, at least)
      return callback(undefined);
    }
    else if (node.t === 'raw') {
      renderer.outputWrite(node.val);
      next();
    }
    else if (node.t === 'partial') {
      // xxx: what about partials with context lookups (variables) for names?
      // xxx: or partials with yields?
      parsing.hitCache(node.val, function(err, tokens) {
        renderer.renderTokens(tokens, context, next);
      });
    }
    else if (node.t === 'yield') {
      (function bump() {
        var next_template = renderer.template_stack.shift(); // pop left
        if (next_template) {
          parsing.hitCache(next_template, function(err, tokens) {
            renderer.renderTokens(tokens, context, next);
          });
        }
        else {
          // no more templates on the template stack.
          if (renderer.asap) {
            renderer.once('bump', bump); // wait
          }
          else {
            // console.error('Cannot yield nothing. Wait, yes I can.');
            next();
          }
        }
      })();
    }
    else {
      (function bump() {
        var value = expressionEval(context, node.val);
        if (typeof(value) === 'function') {
          value = value();
        }

        if (value === undefined && renderer.asap) {
          // this.asap can be true if we want to wait,
          // and false if we merely want to ignore the missing contxt variables.
          renderer.once('bump', bump); // wait
        }
        else {
          if (value === undefined || value === null) value = '';

          if (node.t == 'section' || node.t == '!section') {
            if (!node.block) throw new Error("Cannot have empty block: " + node.block);
            if (Array.isArray(value) && !value.length) value = false; // hack for sake of Mu spec.
            var sub = node.t == '!section' ? !value : value;
            if (sub) {
              if (Array.isArray(value)) {
                var j = 0;
                (function next2() {
                  var top = value[j++];
                  if (top)
                    renderer.sectionRender(node, top, context, next2);
                  else
                    next();
                })();
              }
              else {
                renderer.sectionRender(node, value, context, next);
              }
            }
            else {
              next();
            }
          }
          else if (node.t == 'unescaped') {
            renderer.outputWrite(value.toString());
            next();
          }
          else { // (node.t == 'escaped')
            renderer.outputWrite(escapeHtml(value.toString()));
            next();
          }
        }
      })();
    }
    // } catch (err) {
    //   // renderer.outputError(err);
    //   console.error('Amulet error:', err.name, '-->', err.message);
    //   console.dir(err);
    //   console.trace();
    //   next();
    // }
  })();
};

var StreamRenderer = function(context, asap, callback) {
  this.initialize(context, asap, callback);
  this.stream = new Stream();
};
StreamRenderer.prototype = new Renderer();
StreamRenderer.prototype.outputWrite = function(string) {
  this.stream.emit('data', string);
};
StreamRenderer.prototype.outputEnd = function(err) {
  this.stream.emit('end');
  this.callback(err);
};

var StringRenderer = function(context, asap, callback) {
  this.initialize(context, asap, callback);
  this.string = '';
};
StringRenderer.prototype = new Renderer();
StringRenderer.prototype.outputWrite = function(string) {
  this.string += string;
};
StringRenderer.prototype.outputEnd = function(err) {
  this.callback(err, this.string);
};

// exports.StreamRenderer = StreamRenderer;
// exports.StringRenderer = StringRenderer;
<commit_msg>Use binding for expressionEval function application if available.<commit_after>var events = require('events'),
    Stream = require('stream').Stream,
    parsing = require('./parsing'),
    proto = require('./proto');

exports.emptyCache = parsing.emptyCache;
exports.set = parsing.set; // a function
exports.parseTemplate = parsing.parseTemplate;

var util = require('util');
function info(/*, objs */) {
  var args = Array.prototype.slice.call(arguments, 0);
  var strings = args.map(function(arg) {
    if (typeof(arg) == 'string')
      return arg;
    return util.inspect(arg, false, null);
  });
  console.log(strings.join(' '));
}

// todo:
//   implement ability to add templates asap-ly, so that the first one
//   can start rendering without its yield being specified yet

exports.render = function(output, templates /*, context, asap, callback*/) {
  // @output: a stream
  // @templates: an array of strings (coerces naked string to 1-array)
  // @context: a string or an array of strings
  // @callback: function(err) { }
  // @asap: boolean that determines how to handle missing variables.
  var args = Array.prototype.slice.call(arguments);
  // pop from the right
  var callback = typeof(args[args.length - 1]) === 'function' ? args.pop() : function() {};
  var asap = typeof(args[args.length - 1]) === 'boolean' ? args.pop() : false;
  var context = args.length > 2 ? args.pop() : {};
  var renderer = new StreamRenderer(context, asap, callback);
  renderer.stream.pipe(output);
  if (templates)
    renderer.start(templates);
  return renderer;
};

exports.renderString = function(names, context, callback) {
  // callback signature: function(err, string)
  // can I force it to be sync? callback is okay too, if not
  var renderer = new StringRenderer(context, false, callback);
  renderer.start(names);
  return renderer;
};

function escapeHtml(s) {
  return s.replace(/[&<>"]/g, function(s) {
    switch (s) {
      case '<': return '<';
      case '>': return '>';
      case '&': return '&';
      case '"': return '"';
      default: return s;
    }
  });
}

function dottedEval(context, expression) {
  // handles strings that occur in context or dotted paths that traverse a context object
  if (expression == '.') return context['.']; // for those embedded sections (silly Mustache spec, should be _)

  var parts = expression.split('.');
  for (var i = 0, part; (part = parts[i]) !== undefined; i++) {
    context = context[part];
    if (context === undefined || context === null) break;
  }
  return context;
}

function expressionEval(context, expression) {
  // expression can be a function call, a boolean, or a simple string.
  var m;
  if (m = expression.match(/^(\S+)\s*([!=<>]+)\s*(\S+)$/)) {
    // booleans: ==, ===, !=, !==, <, <=, >, >=
    var left = dottedEval(context, m[1]);
    var op = m[2];
    var right = dottedEval(context, m[3]);
    if (op === '==') return left == right;
    else if (op === '===') return left === right;
    else if (op === '!=') return left != right;
    else if (op === '!==') return left !== right;
    else if (op === '<') return left < right;
    else if (op === '<=') return left <= right;
    else if (op === '>') return left > right;
    else if (op === '>=') return left >= right;
    else throw new Error("Unrecognized operator: " + op);
  }
  else if (m = expression.match(/^(\S+)\((\S*)\)$/)) {
    // functions.
    // open parens indicates function application,
    //   the entire following conditional is for functional application.
    // close_parens_index should be append_to_top.length - 1

    // String.substring takes two indices (not a length)
    // var argument_part = new_node.val.substring(open_parens_index + 1, close_parens_index);
    // trim whitespace/quotes since arguments can only be strings or ints anyway. At least, for now.
    // (todo: let them embed commas in strings)
    // if m[1] == 'receipt.total.substr'
    //    `func` should be the substr, and
    //    `binding` should be receipt.total
    var func = dottedEval(context, m[1]) || eval(m[1]);
    // we get the binding by doing a plain old dottedEval but with everything short of the last period
    var binding_str = m[1].replace(/(^|\.)[^.]+$/, '');
    var binding = dottedEval(context, binding_str) || null;
    var args = m[2].split(',').map(function(raw) {
      var val = raw.replace(/^\s+|\s+$/g, ''); // trim
      if (val.match(/^('|").*\1$/)) { // string literal
        val = val.slice(1, -1);
      }
      else if (val.match(/^-?\d+$/)) { // integer literal
        val = parseInt(val, 10);
      }
      else if (val.match(/^-?\d+\.\d+$/)) { // float literal
        val = parseFloat(val);
      }
      else if (val.match(/^\w+$/)) { // variable reference
        val = dottedEval(context, val);
      }
      return val;
    });

    return func.apply(binding, args);
  }
  else {
    return dottedEval(context, expression);
  }
}

var Renderer = function(context, asap, callback) {
  this.initialize(context, asap, callback);
};
Renderer.prototype = new events.EventEmitter();
Renderer.prototype.initialize = function(context, asap, callback) {
  this.context = context;
  this.asap = asap;
  this.callback = callback;

  this.template_stack = [];
};

Renderer.prototype.extendContext = function(obj, val) {
  if (val !== undefined) {
    this.context[obj] = val;
  }
  else {
    for (var attr in obj) {
      this.context[attr] = obj[attr];
    }
  }
  this.emit('bump');
  return this; // chainable
};
Renderer.prototype.extendTemplateStack = function(templates) {
  Array.prototype.push[Array.isArray(templates) ? 'apply' : 'call'](this.template_stack, templates);
  this.emit('bump');
  return this; // chainable
};
Renderer.prototype.force = function() {
  // use force to quit waiting for new context variables, and simply leave gaps for missing context variables, where possible
  this.asap = false;
  this.emit('bump');
  return this; // chainable
};
Renderer.prototype.start = function(templates, context, asap) { // aka render_global
  this.extendTemplateStack(templates);

  if (context !== undefined) {
    this.extendContext(context);
  }
  if (asap !== undefined) {
    this.asap = asap;
  }
  var renderer = this;
  var template_name = renderer.template_stack.shift();
  parsing.hitCache(template_name, function(err, tokens) {
    if (err) console.error(err);
    renderer.renderTokens(tokens, renderer.context, function(err) {
      renderer.outputEnd(err);
    });
  });
  return this;
};
Renderer.prototype.sectionRender = function(node, item, context, callback) {
  // for an object with properties, we DO NOT expose it as _, which causes problems with circularity.
  // to comply with mu, and for the sake of concision, we expose its properties nakedly.
  // however, if there is a sub name, we box it as that.
  var local_item = item;
  if (typeof(item) !== 'object' || node.sub) {
    // for strings, numbers, booleans, etc. ... or boxed objects
    local_item = {};
    local_item[node.sub || '.'] = item;
  }
  // else {proto.extend(item, local_item); }
  // proto.extend(item, context);
  proto.push(local_item, context);
  // so now it's item = {cool: 'stuff',
  //   __proto__: {original_context_var: 192, __proto__: {}.__proto__}}

  this.renderTokens(node.block, local_item, function() {
    proto.pop(local_item);
    callback();
  });
};

Renderer.prototype.renderTokens = function(tokens, context, callback) {
  var renderer = this, i = 0;
  (function next() {
    var node = tokens[i++];
    if (node === undefined) {
      // we're done! (with this scope, at least)
      return callback(undefined);
    }
    else if (node.t === 'raw') {
      renderer.outputWrite(node.val);
      next();
    }
    else if (node.t === 'partial') {
      // xxx: what about partials with context lookups (variables) for names?
      // xxx: or partials with yields?
      parsing.hitCache(node.val, function(err, tokens) {
        renderer.renderTokens(tokens, context, next);
      });
    }
    else if (node.t === 'yield') {
      (function bump() {
        var next_template = renderer.template_stack.shift(); // pop left
        if (next_template) {
          parsing.hitCache(next_template, function(err, tokens) {
            renderer.renderTokens(tokens, context, next);
          });
        }
        else {
          // no more templates on the template stack.
          if (renderer.asap) {
            renderer.once('bump', bump); // wait
          }
          else {
            // console.error('Cannot yield nothing. Wait, yes I can.');
            next();
          }
        }
      })();
    }
    else {
      (function bump() {
        var value = expressionEval(context, node.val);
        if (typeof(value) === 'function') {
          value = value();
        }

        if (value === undefined && renderer.asap) {
          // this.asap can be true if we want to wait,
          // and false if we merely want to ignore the missing contxt variables.
          renderer.once('bump', bump); // wait
        }
        else {
          if (value === undefined || value === null) value = '';

          if (node.t == 'section' || node.t == '!section') {
            if (!node.block) throw new Error("Cannot have empty block: " + node.block);
            if (Array.isArray(value) && !value.length) value = false; // hack for sake of Mu spec.
            var sub = node.t == '!section' ? !value : value;
            if (sub) {
              if (Array.isArray(value)) {
                var j = 0;
                (function next2() {
                  var top = value[j++];
                  if (top)
                    renderer.sectionRender(node, top, context, next2);
                  else
                    next();
                })();
              }
              else {
                renderer.sectionRender(node, value, context, next);
              }
            }
            else {
              next();
            }
          }
          else if (node.t == 'unescaped') {
            renderer.outputWrite(value.toString());
            next();
          }
          else { // (node.t == 'escaped')
            renderer.outputWrite(escapeHtml(value.toString()));
            next();
          }
        }
      })();
    }
    // } catch (err) {
    //   // renderer.outputError(err);
    //   console.error('Amulet error:', err.name, '-->', err.message);
    //   console.dir(err);
    //   console.trace();
    //   next();
    // }
  })();
};

var StreamRenderer = function(context, asap, callback) {
  this.initialize(context, asap, callback);
  this.stream = new Stream();
};
StreamRenderer.prototype = new Renderer();
StreamRenderer.prototype.outputWrite = function(string) {
  this.stream.emit('data', string);
};
StreamRenderer.prototype.outputEnd = function(err) {
  this.stream.emit('end');
  this.callback(err);
};

var StringRenderer = function(context, asap, callback) {
  this.initialize(context, asap, callback);
  this.string = '';
};
StringRenderer.prototype = new Renderer();
StringRenderer.prototype.outputWrite = function(string) {
  this.string += string;
};
StringRenderer.prototype.outputEnd = function(err) {
  this.callback(err, this.string);
};

// exports.StreamRenderer = StreamRenderer;
// exports.StringRenderer = StringRenderer;
<|endoftext|>


<commit_before>/* jshint node:true, unused:true */
"use strict";

var rest = require('restler');
var Q    = require('q');

var restler_q = ['request', 'get','patch','post','put','del','head','json','postJson','putJson'].reduce(function(memo, method) {
  var underlying = rest[method];
  if(underlying) {
    memo[method] = wrapMethod(underlying);
    memo.spread[method] = wrapMethod(underlying, true);
  }
  return memo;
}, {
  spread: {},
  Request: rest.Request,
  parsers: rest.parsers,
  file: rest.file,
  data: rest.data,
  Service: Service,
  service: service
});

module.exports = restler_q;

function wrap(r, spread) {
  var defer = Q.defer();

  r.on('success', function(result, response) {
    if(spread) return defer.resolve([ result, response ]);

    defer.resolve(result);
  });

  r.on('fail', function(err, response) {
    if(spread) err.response = response;

    defer.reject(err);
  });

  r.on('error', function(err, response) {
    if(spread) err.response = response;

    defer.reject(err);
  });

  r.on('abort', function() {
    defer.reject(new Error('Operation aborted'));
  });

  return defer.promise;
}

function wrapMethod(method, spread) {
  return function() {
    var request = method.apply(rest, arguments);
    return wrap(request, spread);
  };
}

function mixin(target, source) {
  source = source || {};
  Object.keys(source).forEach(function(key) {
    target[key] = source[key];
  });

  return target;
}

function Service(defaults) {
    defaults = defaults || {};
    if (defaults.baseURL) {
        this.baseURL = defaults.baseURL;
        delete defaults.baseURL;
    }
    this.defaults = defaults;
}

var url = require('url');

mixin(Service.prototype, {
    request: function(path, options) {
        return restler_q.request(this._url(path), this._withDefaults(options));
    },
    get: function(path, options) {
        return restler_q.get(this._url(path), this._withDefaults(options));
    },
    head: function(path, options) {
        return restler_q.head(this._url(path), this._withDefaults(options));
    },
    patch: function(path, options) {
        return restler_q.patch(this._url(path), this._withDefaults(options));
    },
    put: function(path, options) {
        return restler_q.put(this._url(path), this._withDefaults(options));
    },
    post: function(path, options) {
        return restler_q.post(this._url(path), this._withDefaults(options));
    },
    json: function(path, options) {
        return restler_q.json(this._url(path), this._withDefaults(options));
    },
    postJson: function(path, options) {
        return restler_q.postJson(this._url(path), this._withDefaults(options));
    },
    putJson: function(path, options) {
        return restler_q.putJson(this._url(path), this._withDefaults(options));
    },
    del: function(path, options) {
        return restler_q.del(this._url(path), this._withDefaults(options));
    },
    _url: function(path) {
        if (this.baseURL){
            return url.resolve(this.baseURL, path);
        }
        else {
            return path;
        }
    },
    _withDefaults: function(options) {
        var opts = mixin({}, this.defaults);
        return mixin(opts, options);
    }
});

function service(constructor, defaults, methods) {
  constructor.prototype = new Service(defaults || {});
  mixin(constructor.prototype, methods);
  return constructor;
}
<commit_msg>Handle timeout error condition properly.<commit_after>/* jshint node:true, unused:true */
"use strict";

var url = require('url');

var rest = require('restler');
var Q    = require('q');

var restler_q = ['request', 'get','patch','post','put','del','head','json','postJson','putJson'].reduce(function(memo, method) {
    var underlying = rest[method];
    if(underlying) {
        memo[method] = wrapMethod(underlying);
        memo.spread[method] = wrapMethod(underlying, true);
    }
    return memo;
}, {
    spread: {},
    Request: rest.Request,
    parsers: rest.parsers,
    file: rest.file,
    data: rest.data,
    Service: Service,
    service: service
});

module.exports = restler_q;

function wrap(r, spread) {
    var defer = Q.defer();

    r.on('success', function(result, response) {
        if(spread) { return defer.resolve([ result, response ]); }
        defer.resolve(result);
    });

    r.on('timeout', function(ms) {
        var err = new Error('ETIMEDOUT');
        err.code = 'ETIMEDOUT';
        err.errno = 'ETIMEDOUT';
        err.syscall = 'connect';
        err.timeout = ms;
        err.url = url.format(r.url);
        defer.reject(err);
    });

    r.on('fail', function(err, response) {
        if(spread) { err.response = response; }
        err.url = url.format(r.url);
        defer.reject(err);
    });

    r.on('error', function(err, response) {
        if(spread) { err.response = response; }
        err.url = url.format(r.url);
        defer.reject(err);
    });

    r.on('abort', function() {
        var err = new Error('Operation aborted');
        err.url = url.format(r.url);
        defer.reject(err);
    });

    return defer.promise;
}

function wrapMethod(method, spread) {
    return function() {
        var request = method.apply(rest, arguments);
        return wrap(request, spread);
    };
}

function mixin(target, source) {
    source = source || {};
    Object.keys(source).forEach(function(key) {
        target[key] = source[key];
    });

    return target;
}

function Service(defaults) {
    defaults = defaults || {};
    if (defaults.baseURL) {
        this.baseURL = defaults.baseURL;
        delete defaults.baseURL;
    }
    this.defaults = defaults;
}

var url = require('url');

mixin(Service.prototype, {
    request: function(path, options) {
        return restler_q.request(this._url(path), this._withDefaults(options));
    },
    get: function(path, options) {
        return restler_q.get(this._url(path), this._withDefaults(options));
    },
    head: function(path, options) {
        return restler_q.head(this._url(path), this._withDefaults(options));
    },
    patch: function(path, options) {
        return restler_q.patch(this._url(path), this._withDefaults(options));
    },
    put: function(path, options) {
        return restler_q.put(this._url(path), this._withDefaults(options));
    },
    post: function(path, options) {
        return restler_q.post(this._url(path), this._withDefaults(options));
    },
    json: function(path, options) {
        return restler_q.json(this._url(path), this._withDefaults(options));
    },
    postJson: function(path, options) {
        return restler_q.postJson(this._url(path), this._withDefaults(options));
    },
    putJson: function(path, options) {
        return restler_q.putJson(this._url(path), this._withDefaults(options));
    },
    del: function(path, options) {
        return restler_q.del(this._url(path), this._withDefaults(options));
    },
    _url: function(path) {
        if (this.baseURL){
            return url.resolve(this.baseURL, path);
        }
        else {
            return path;
        }
    },
    _withDefaults: function(options) {
        var opts = mixin({}, this.defaults);
        return mixin(opts, options);
    }
});

function service(constructor, defaults, methods) {
    constructor.prototype = new Service(defaults || {});
    mixin(constructor.prototype, methods);
    return constructor;
}
<|endoftext|>


<commit_before>pathSum.js
<commit_msg>add desc<commit_after>// Given a binary tree and a sum,
// determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

// For example:
// Given the below binary tree and sum = 22,
//               5
//              / \
//             4   8
//            /   / \
//           11  13  4
//          /  \      \
//         7    2      1
// return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

// Input: Array, Integer
// ex. [5,4,8,11,13,4,7,2,1]
// 22

// Output: Boolean
// ex. false
<|endoftext|>


<commit_before>var React = require('react-native');

var {
  StyleSheet,
  ScrollView,
  Text,
  View,
  TouchableHighlight,
  Component,
  Image,
} = React;

var styles = StyleSheet.create({
  container: {
    top: 40,
    flex: 1,
  },
  rowContainer: {
    flexDirection: 'column',
    flex: 1,
    padding: 10
  },
  image: {
    width: 150,
    height: 150
  },
  imageSquare: {
    width: 150,
    height: 150
  },
  name: {
    color: '#48BBEC',
    fontSize: 18,
    paddingBottom: 5
  },
});

class GroupMembers extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      image_url: ''
    };
  }

  render(){
    var members = this.props.members;
    var list = members.map((member, index) => {
    var profilePic = members[index].image_url ? <Image style={styles.image} source={members[index].image_url} /> : <Text style={styles.imageSquare}> No Picture yet </Text>;
      return (
        <View key={index}>
          <View style={styles.rowContainer}>
            {profilePic}
            <Text style={styles.name}> {members[index].username} </Text>
          </View>
        </View>
      )
    });
    return (
      <ScrollView style={styles.container}>
        {list}
      </ScrollView>
    )
  }
};

module.exports = GroupMembers;
<commit_msg>Fix URI source on GroupMembers<commit_after>var React = require('react-native');

var {
  StyleSheet,
  ScrollView,
  Text,
  View,
  TouchableHighlight,
  Component,
  Image,
} = React;

var styles = StyleSheet.create({
  container: {
    top: 40,
    flex: 1,
  },
  rowContainer: {
    flexDirection: 'column',
    flex: 1,
    padding: 10
  },
  image: {
    width: 150,
    height: 150
  },
  imageSquare: {
    width: 150,
    height: 150
  },
  name: {
    color: '#48BBEC',
    fontSize: 18,
    paddingBottom: 5
  },
});

class GroupMembers extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      image_url: ''
    };
  }

  render(){
    var members = this.props.members;
    var list = members.map((member, index) => {
    var profilePic = members[index].image_url ? <Image style={styles.image} source={{uri: members[index].image_url}} /> : <Text style={styles.imageSquare}> No Picture yet </Text>;
      return (
        <View key={index}>
          <View style={styles.rowContainer}>
            {profilePic}
            <Text style={styles.name}> {members[index].username} </Text>
          </View>
        </View>
      )
    });
    return (
      <ScrollView style={styles.container}>
        {list}
      </ScrollView>
    )
  }
};

module.exports = GroupMembers;
<|endoftext|>


<commit_before>!function(exports) {
  'use strict';

  var Component = exports.Component;

  /*
   * Constructor
   * -----------
   */

  var SceneNode = Component.extend(function SceneNode(x, y, z) {
    Component.call(this);
    this.x = x || 0;
    this.y = y || 0;
    this.z = z || 0;

    this._parent = null;
    this._children = [];
    this._initialized = false;
    this._destroyed = false;

    this.components = [];
  });

  /*
   * Lifecycle Methods
   * -----------------
   */

  SceneNode.prototype.init = function() {
    this._initialized = true;
    this._destroyed = false;
    each(this.components, fireInit);
    each(this._children, fireInit);
  };

  SceneNode.prototype.destroy = function() {
    this._destroyed = true;
    this._initialized = false;
    each(this._children, fireDestroy);
    each(this.components, fireDestroy);
  };

  /*
   * Tick Methods
   * ------------
   */

  SceneNode.prototype.before = function(delta, x, y, z) {
    each(this.components, fireNext);
    each(this._children, fireNext);
    // inefficient: allocates before method each time
    runMethods(this, method('before'), delta, x, y, z);
  };

  SceneNode.prototype.update = nodeMethod(method('update'));

  SceneNode.prototype.after = function(delta, x, y, z) {
    // inefficient: allocates after method each time
    runMethods(this, method('after'), delta, x, y, z);
    each(this._children, fireEnd);
    each(this.components, fireEnd);
  };

  /*
   * Render Methods
   * --------------
   */

  SceneNode.prototype.preprocess = nodeMethod(method('preprocess'));
  SceneNode.prototype.render = nodeMethod(method('render'));
  SceneNode.prototype.postprocess = nodeMethod(method('postprocess'));

  /*
   * Coordinate Methods
   * ------------------
   */

  SceneNode.prototype.xAbsolute = absoluteCoordMethod('x', 'xAbsolute');
  SceneNode.prototype.yAbsolute = absoluteCoordMethod('y', 'yAbsolute');
  SceneNode.prototype.zAbsolute = absoluteCoordMethod('z', 'zAbsolute');

  /*
   * Child Methods
   * -------------
   */

  SceneNode.prototype.add = function(child) {
    if(child) {
      this._children.push(child);
      child._parent = this;
      if(this._initialized && !this._destroyed) child.init();
    }
  };

  SceneNode.prototype.remove = function(child) {
    for(var curr, index = 0; curr = this._children[index]; index++) {
      if(curr === child) {
        this._children.splice(index, 1);
        curr._parent = null;
        if(this._initialized && !this._destroyed) curr.destroy();
        return true;
      }
    }
    return false;
  };

  /*
   * Private Methods
   * ---------------
   */

  function nodeMethod(fn) {
    return function(delta, x, y, z) { runMethods(this, fn, delta, x, y, z); };
  }

  function runMethods(node, fn, delta, x, y, z) {
    each4args(node.components, fn, delta, x, y, z);
    each4args(node._children, fn, delta, x, y, z);
  }

  function absoluteCoordMethod(coord, methodName) {
    return function() {
      return this[coord] + this._parent ? this._parent[methodName]() : 0;
    };
  }

  /*
   * Helper Functions
   * ----------------
   */

  /*
   * ### each4args ###
   *
   * Kludgy, but using `apply` is slow and this is called quite a bit. Does
   * exactly what you'd expect: acts like an `each` function that also takes
   * four additional args to pass to the callback.
   */

  function each4args(arr, callback, a1, a2, a3, a4) {
    for(var index = 0, length = arr.length; index < length; index++) {
      callback(arr[index], a1, a2, a3, a4);
    }
  }

  function each(arr, fn) {
    for(var i = 0, l = arr.length; i < l; i++) {
      fn(arr[i]);
    }
  }

  function fireEnd(c) { c.end.fire(); }
  function fireNext(c) { c.next.fire(); }
  function fireInit(c) { c.init(); }
  function fireDestroy(c) { c.destroy(); }

  function method(name) {
    return function(obj, delta, x, y, z) { obj[name](delta, x, y, z); };
  }

  /*
   * Exports
   * -------
   */

  exports.SceneNode = SceneNode;

}(seine);
<commit_msg>Fix position arg passing.<commit_after>!function(exports) {
  'use strict';

  var Component = exports.Component;

  /*
   * Constructor
   * -----------
   */

  var SceneNode = Component.extend(function SceneNode(x, y, z) {
    Component.call(this);
    this.x = x || 0;
    this.y = y || 0;
    this.z = z || 0;

    this._parent = null;
    this._children = [];
    this._initialized = false;
    this._destroyed = false;

    this.components = [];
  });

  /*
   * Lifecycle Methods
   * -----------------
   */

  SceneNode.prototype.init = function() {
    this._initialized = true;
    this._destroyed = false;
    each(this.components, fireInit);
    each(this._children, fireInit);
  };

  SceneNode.prototype.destroy = function() {
    this._destroyed = true;
    this._initialized = false;
    each(this._children, fireDestroy);
    each(this.components, fireDestroy);
  };

  /*
   * Tick Methods
   * ------------
   */

  SceneNode.prototype.before = function(delta, x, y, z) {
    each(this.components, fireNext);
    each(this._children, fireNext);
    // inefficient: allocates before method each time
    runMethods(this, method('before'), delta, this.x + x, this.y + y, this.z + z);
  };

  SceneNode.prototype.update = nodeMethod(method('update'));

  SceneNode.prototype.after = function(delta, x, y, z) {
    // inefficient: allocates after method each time
    runMethods(this, method('after'), delta, this.x + x, this.y + y, this.z + z);
    each(this._children, fireEnd);
    each(this.components, fireEnd);
  };

  /*
   * Render Methods
   * --------------
   */

  SceneNode.prototype.preprocess = nodeMethod(method('preprocess'));
  SceneNode.prototype.render = nodeMethod(method('render'));
  SceneNode.prototype.postprocess = nodeMethod(method('postprocess'));

  /*
   * Coordinate Methods
   * ------------------
   */

  SceneNode.prototype.xAbsolute = absoluteCoordMethod('x', 'xAbsolute');
  SceneNode.prototype.yAbsolute = absoluteCoordMethod('y', 'yAbsolute');
  SceneNode.prototype.zAbsolute = absoluteCoordMethod('z', 'zAbsolute');

  /*
   * Child Methods
   * -------------
   */

  SceneNode.prototype.add = function(child) {
    if(child) {
      this._children.push(child);
      child._parent = this;
      if(this._initialized && !this._destroyed) child.init();
    }
  };

  SceneNode.prototype.remove = function(child) {
    for(var curr, index = 0; curr = this._children[index]; index++) {
      if(curr === child) {
        this._children.splice(index, 1);
        curr._parent = null;
        if(this._initialized && !this._destroyed) curr.destroy();
        return true;
      }
    }
    return false;
  };

  /*
   * Private Methods
   * ---------------
   */

  function nodeMethod(fn) {
    return function(delta, x, y, z) {
      runMethods(this, fn, delta, this.x + x, this.y + y, this.z + z);
    };
  }

  function runMethods(node, fn, delta, x, y, z) {
    each4args(node.components, fn, delta, x, y, z);
    each4args(node._children, fn, delta, x, y, z);
  }

  function absoluteCoordMethod(coord, methodName) {
    return function() {
      return this[coord] + this._parent ? this._parent[methodName]() : 0;
    };
  }

  /*
   * Helper Functions
   * ----------------
   */

  /*
   * ### each4args ###
   *
   * Kludgy, but using `apply` is slow and this is called quite a bit. Does
   * exactly what you'd expect: acts like an `each` function that also takes
   * four additional args to pass to the callback.
   */

  function each4args(arr, callback, a1, a2, a3, a4) {
    for(var index = 0, length = arr.length; index < length; index++) {
      callback(arr[index], a1, a2, a3, a4);
    }
  }

  function each(arr, fn) {
    for(var i = 0, l = arr.length; i < l; i++) {
      fn(arr[i]);
    }
  }

  function fireEnd(c) { c.end.fire(); }
  function fireNext(c) { c.next.fire(); }
  function fireInit(c) { c.init(); }
  function fireDestroy(c) { c.destroy(); }

  function method(name) {
    return function(obj, delta, x, y, z) { obj[name](delta, x, y, z); };
  }

  /*
   * Exports
   * -------
   */

  exports.SceneNode = SceneNode;

}(seine);
<|endoftext|>


<commit_before>var Utils          = require("./utils")
  , DAOFactory   = require("./dao-factory")
  , DataTypes      = require('./data-types')
  , DAOFactoryManager   = require("./dao-factory-manager")
  , Migrator       = require("./migrator")
  , QueryInterface = require("./query-interface")

module.exports = (function() {
  var Sequelize = function(database, username, password, options) {
    this.options = Utils._.extend({
      dialect: 'mysql',
      host: 'localhost',
      port: 3306,
      define: {},
      query: {},
      sync: {}
    }, options || {})

    if(this.options.logging === true) {
      console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log')
      this.options.logging = console.log
    }

    this.config = {
      database: database,
      username: username,
      password: (( (["", null, false].indexOf(password) > -1) || (typeof password == 'undefined')) ? null : password),
      host    : this.options.host,
      port    : this.options.port
    }

    var ConnectorManager = require("./dialects/" + this.options.dialect + "/connector-manager")

    this.daoFactoryManager     = new DAOFactoryManager(this)
    this.connectorManager = new ConnectorManager(this, this.config)
  }

  Sequelize.Utils = Utils
  Sequelize.Utils._.map(DataTypes, function(sql, accessor) { Sequelize[accessor] = sql})

  Sequelize.prototype.getQueryInterface = function() {
    this.queryInterface = this.queryInterface || new QueryInterface(this)
    return this.queryInterface
  }

  Sequelize.prototype.getMigrator = function(options, force) {
    if(force)
      this.migrator = new Migrator(this, options)
    else
      this.migrator = this.migrator || new Migrator(this, options)

    return this.migrator
  }

  Sequelize.prototype.define = function(daoName, attributes, options) {
    options = options || {}

    if(this.options.define)
      options = Sequelize.Utils.merge(options, this.options.define)

    var factory = new DAOFactory(daoName, attributes, options)

    this.daoFactoryManager.addDAO(factory.init(this.daoFactoryManager))

    return factory
  }

  Sequelize.prototype.import = function(path) {
    var defineCall = require(path)
    return defineCall(this, DataTypes)
  }

  Sequelize.prototype.migrate = function(options) {
    this.getMigrator().migrate(options)
  }

  Sequelize.prototype.query = function(sql, callee, options) {
    options = Utils._.extend(Utils._.clone(this.options.query), options || {})
    options = Utils._.extend(options, {
      logging: this.options.hasOwnProperty('logging') ? this.options.logging : console.log
    })

    return this.connectorManager.query(sql, callee, options)
  }

  Sequelize.prototype.sync = function(options) {
    options = options || {}

    if(this.options.sync)
      options = Sequelize.Utils.merge(options, this.options.sync)

    var self = this

    return new Utils.CustomEventEmitter(function(emitter) {
      var chainer = new Utils.QueryChainer

      self.daoFactoryManager.daos.forEach(function(dao) { chainer.add(dao.sync(options)) })

      chainer
        .run()
        .success(function() { emitter.emit('success', null) })
        .error(function(err) { emitter.emit('failure', err) })
    }).run()
  }

  Sequelize.prototype.drop = function() {
    var self = this

    return new Utils.CustomEventEmitter(function(emitter) {
      var chainer = new Utils.QueryChainer

      self.daoFactoryManager.daos.forEach(function(dao) { chainer.add(dao.drop()) })

      chainer
        .run()
        .success(function() { emitter.emit('success', null) })
        .error(function(err) { emitter.emit('failure', err) })
    }).run()
  }

  return Sequelize
})()
<commit_msg>formatting + logging info<commit_after>var Utils          = require("./utils")
  , DAOFactory   = require("./dao-factory")
  , DataTypes      = require('./data-types')
  , DAOFactoryManager   = require("./dao-factory-manager")
  , Migrator       = require("./migrator")
  , QueryInterface = require("./query-interface")

module.exports = (function() {
  var Sequelize = function(database, username, password, options) {
    this.options = Utils._.extend({
      dialect: 'mysql',
      host: 'localhost',
      port: 3306,
      define: {},
      query: {},
      sync: {}
    }, options || {})

    if(this.options.logging === true) {
      console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log')
      this.options.logging = console.log
    }

    if(this.options.logging == console.log) {
      // using just console.log will break in node < 0.6
      this.options.logging = function(s) { console.log(s) }
    }

    this.config = {
      database: database,
      username: username,
      password: (( (["", null, false].indexOf(password) > -1) || (typeof password == 'undefined')) ? null : password),
      host    : this.options.host,
      port    : this.options.port
    }

    var ConnectorManager = require("./dialects/" + this.options.dialect + "/connector-manager")

    this.daoFactoryManager = new DAOFactoryManager(this)
    this.connectorManager  = new ConnectorManager(this, this.config)
  }

  Sequelize.Utils = Utils
  Sequelize.Utils._.map(DataTypes, function(sql, accessor) { Sequelize[accessor] = sql})

  Sequelize.prototype.getQueryInterface = function() {
    this.queryInterface = this.queryInterface || new QueryInterface(this)
    return this.queryInterface
  }

  Sequelize.prototype.getMigrator = function(options, force) {
    if(force)
      this.migrator = new Migrator(this, options)
    else
      this.migrator = this.migrator || new Migrator(this, options)

    return this.migrator
  }

  Sequelize.prototype.define = function(daoName, attributes, options) {
    options = options || {}

    if(this.options.define)
      options = Sequelize.Utils.merge(options, this.options.define)

    var factory = new DAOFactory(daoName, attributes, options)

    this.daoFactoryManager.addDAO(factory.init(this.daoFactoryManager))

    return factory
  }

  Sequelize.prototype.import = function(path) {
    var defineCall = require(path)
    return defineCall(this, DataTypes)
  }

  Sequelize.prototype.migrate = function(options) {
    this.getMigrator().migrate(options)
  }

  Sequelize.prototype.query = function(sql, callee, options) {
    options = Utils._.extend(Utils._.clone(this.options.query), options || {})
    options = Utils._.extend(options, {
      logging: this.options.hasOwnProperty('logging') ? this.options.logging : console.log
    })

    return this.connectorManager.query(sql, callee, options)
  }

  Sequelize.prototype.sync = function(options) {
    options = options || {}

    if(this.options.sync)
      options = Sequelize.Utils.merge(options, this.options.sync)

    var self = this

    return new Utils.CustomEventEmitter(function(emitter) {
      var chainer = new Utils.QueryChainer

      self.daoFactoryManager.daos.forEach(function(dao) { chainer.add(dao.sync(options)) })

      chainer
        .run()
        .success(function() { emitter.emit('success', null) })
        .error(function(err) { emitter.emit('failure', err) })
    }).run()
  }

  Sequelize.prototype.drop = function() {
    var self = this

    return new Utils.CustomEventEmitter(function(emitter) {
      var chainer = new Utils.QueryChainer

      self.daoFactoryManager.daos.forEach(function(dao) { chainer.add(dao.drop()) })

      chainer
        .run()
        .success(function() { emitter.emit('success', null) })
        .error(function(err) { emitter.emit('failure', err) })
    }).run()
  }

  return Sequelize
})()
<|endoftext|>


<commit_before>//
// Module: Signature
// =================
//
'use strict';

var Signature,
  __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

module.exports = Signature = (function () {

  //
  //
  // Constructor
  // -----------
  //
  function Signature (opts) {

    /* checking the required arguments */
    ['key', 'secret'].forEach(function (item) {
      if (opts[item] == null)
        throw new Error('There\'s a required argument missing: ' + item);
    });

    this.opts = opts;

    /* bindings */
    this.create = __bind(this.create, this);
  }

  //
  //
  // Create a signature ready for consume
  // ------------------------------------
  //
  // #### Arguments
  //
  // + `params` -- params to be sent to transloadit
  // + `opts` -- Array of opts to be handled by the generator
  //   - `expires` -- (Optional) Time in miliseconds for expiration (Default
  //   is 15 minutes or 900000 ms)
  // + `Callback` function -- (Optional)
  //
  // #### Returns
  //
  // A signature, ready to be used with the payload sent to the function.
  //
  // #### Example
  //
  // ```
  // var params = {
  //   'steps': { ... }
  // },
  // opts = {
  //   'expires': '60000'
  // };
  //
  // sig(params, opts);
  // ```
  //
  Signature.prototype.create = function (params, opts, callback) {
    var self = this,
      crypto = require('crypto');

    var expires = opts.expires || 15 * 60000;

    params['auth'] = {
      'key': self.opts.key,
      'expires': (new Date( (new Date()).getTime() + expires )).toUTCString()
    };

    var sig = {
      signature: crypto.createHmac('sha1', self.opts.secret).update(new Buffer(JSON.stringify(params), 'utf-8')).digest('hex'),
      params: params
    };

    if (callback != null)
      return callback(null, sig);

    return sig;
  };

  return Signature;

})();
<commit_msg>trivial update<commit_after>//
// Module: Signature
// =================
//
'use strict';

var Signature,
  __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

module.exports = Signature = (function () {

  //
  //
  // Constructor
  // -----------
  //
  function Signature (opts) {

    /* checking the required arguments */
    ['key', 'secret'].forEach(function (item) {
      if (opts[item] == null)
        throw new Error('There\'s a required argument missing: ' + item);
    });

    this.opts = opts;

    /* bindings */
    this.create = __bind(this.create, this);
  }

  //
  //
  // Create a signature ready for consume
  // ------------------------------------
  //
  // #### Arguments
  //
  // + `params` -- params to be sent to transloadit
  // + `opts` -- Array of opts to be handled by the generator
  //   - `expires` -- (Optional) Time in miliseconds for expiration (Default
  //   is 15 minutes or 900000 ms)
  // + `Callback` function -- (Optional)
  //
  // #### Returns
  //
  // A signature, ready to be used with the payload sent to the function.
  //
  // #### Example
  //
  // ```
  // var params = {
  //   'steps': { ... }
  // },
  // opts = {
  //   'expires': '60000'
  // };
  //
  // sig(params, opts);
  // ```
  //
  // #### Code
  Signature.prototype.create = function (params, opts, callback) {
    var self = this,
      crypto = require('crypto');

    var expires = opts.expires || 15 * 60000;

    params['auth'] = {
      'key': self.opts.key,
      'expires': (new Date( (new Date()).getTime() + expires )).toUTCString()
    };

    var sig = {
      signature: crypto.createHmac('sha1', self.opts.secret).update(new Buffer(JSON.stringify(params), 'utf-8')).digest('hex'),
      params: params
    };

    if (callback != null)
      return callback(null, sig);

    return sig;
  };

  return Signature;

})();
<|endoftext|>


<commit_before>'use strict';

var assign = require('object-assign');
var through = require('through2');
var gs = require('glob-stream');
var File = require('vinyl');
var duplexify = require('duplexify');
var merge = require('merge-stream');
var sourcemaps = require('gulp-sourcemaps');
var filterSince = require('vinyl-filter-since');

var getContents = require('./getContents');
var resolveSymlinks = require('./resolveSymlinks');

function createFile(globFile, enc, cb) {
  cb(null, new File(globFile));
}

function src(glob, opt) {
  var options = assign({
    read: true,
    buffer: true,
    sourcemaps: false,
    passthrough: false
  }, opt);
  var pass, inputPass;

  if (!isValidGlob(glob)) {
    throw new Error('Invalid glob argument: ' + glob);
  }
  // return dead stream if empty array
  if (Array.isArray(glob) && glob.length === 0) {
    pass = through.obj();
    if (!options.passthrough) {
      process.nextTick(pass.end.bind(pass));
    }
    return pass;
  }

  var globStream = gs.create(glob, options);

  var outputStream = globStream
    .pipe(resolveSymlinks())
    .pipe(through.obj(createFile));

  if (options.since != null) {
    outputStream = outputStream
      .pipe(filterSince(options.since));
  }

  if (options.read !== false) {
    outputStream = outputStream
      .pipe(getContents(options));
  }

  if (options.passthrough === true) {
    inputPass = through.obj();
    outputStream = duplexify.obj(inputPass, merge(outputStream, inputPass));
  }
  if (options.sourcemaps === true) {
    outputStream = outputStream
      .pipe(sourcemaps.init({loadMaps: true}));
  }
  return outputStream;
}

function isValidGlob(glob) {
  if (typeof glob === 'string') {
    return true;
  }
  if (!Array.isArray(glob)) {
    return false;
  }
  if (glob.length !== 0) {
    return glob.every(isValidGlob);
  }
  return true;
}

module.exports = src;
<commit_msg>Fix: Re-emit errors on output stream to propagate singular glob errors<commit_after>'use strict';

var assign = require('object-assign');
var through = require('through2');
var gs = require('glob-stream');
var File = require('vinyl');
var duplexify = require('duplexify');
var merge = require('merge-stream');
var sourcemaps = require('gulp-sourcemaps');
var filterSince = require('vinyl-filter-since');

var getContents = require('./getContents');
var resolveSymlinks = require('./resolveSymlinks');

function createFile(globFile, enc, cb) {
  cb(null, new File(globFile));
}

function src(glob, opt) {
  var options = assign({
    read: true,
    buffer: true,
    sourcemaps: false,
    passthrough: false
  }, opt);
  var pass, inputPass;

  if (!isValidGlob(glob)) {
    throw new Error('Invalid glob argument: ' + glob);
  }
  // return dead stream if empty array
  if (Array.isArray(glob) && glob.length === 0) {
    pass = through.obj();
    if (!options.passthrough) {
      process.nextTick(pass.end.bind(pass));
    }
    return pass;
  }

  var globStream = gs.create(glob, options);

  var outputStream = globStream
    .pipe(resolveSymlinks())
    .pipe(through.obj(createFile));

  if (options.since != null) {
    outputStream = outputStream
      .pipe(filterSince(options.since));
  }

  if (options.read !== false) {
    outputStream = outputStream
      .pipe(getContents(options));
  }

  if (options.passthrough === true) {
    inputPass = through.obj();
    outputStream = duplexify.obj(inputPass, merge(outputStream, inputPass));
  }
  if (options.sourcemaps === true) {
    outputStream = outputStream
      .pipe(sourcemaps.init({loadMaps: true}));
  }
  globStream.on('error', outputStream.emit.bind(outputStream, 'error'));
  return outputStream;
}

function isValidGlob(glob) {
  if (typeof glob === 'string') {
    return true;
  }
  if (!Array.isArray(glob)) {
    return false;
  }
  if (glob.length !== 0) {
    return glob.every(isValidGlob);
  }
  return true;
}

module.exports = src;
<|endoftext|>


<commit_before>'use strict'
const {inspect} = require('util')
const jtry = require('just-try')

const chaintry = (act, onerror, ...fnlist) =>
  jtry(act, fnlist.length ? () => jtry(onerror, fnlist) : onerror)

const stringify = object => chaintry(
  () => inspect(object),
  () => JSON.stringify(object),
  () => String(object),
  () => `[Object ${object[Symbol.toStringTag]}]`,
  () => `[Object ${object.constructor.name}]`,
  () => '[Object]'
)

module.exports = stringify
<commit_msg>Add options<commit_after>'use strict'
const {inspect} = require('util')
const jtry = require('just-try')

const chaintry = (act, onerror, ...fnlist) =>
  jtry(act, fnlist.length ? () => jtry(onerror, fnlist) : onerror)

const stringify = (object, options = {}) => chaintry(
  () => inspect(object, options.inspect),
  () => JSON.stringify(object, ...options.json || []),
  () => object.toString(options.string),
  () => String(object),
  () => `[Object ${object[Symbol.toStringTag]}]`,
  () => `[Object ${object.constructor.name}]`,
  () => '[Object]'
)

module.exports = stringify
<|endoftext|>