<commit_before>/* global define */
/* jshint devel: true */

// this is were the application is assembled,
// configured and started.
// Search for the ``setup`` method.
define(['ajax', 'util', 'views', 'ctrls'], function(ajax, util, views, ctrls) {
    'use strict';

    var extend = util.extend,
        Observer = util.Observer;

    var cdmiQueuesModel = {
        setup: function() {
            this.observables = []; // NOTE: required by Observer
        },

        service: {
            root_server: '/api/queues',

            headers: {
                'Accept': 'application/cdmi-queue',
                'X-CDMI-Specification-Version': '1.0.2'
            },

            create: function(name, topic) {
                return ajax(this.root_server + '/' + name + '/' + topic, 'PUT',
                        extend(this.headers, { 'Content-Type': 'application/cdmi-queue' }))
                    .then(JSON.parse);
            },

            read: function(name) {
                return ajax(this.root_server + '/' + name, 'GET', this.headers)
                    .then(JSON.parse)
                    .then(function(cdmi) { return cdmi.value; });
            },

            list: function() {
                return ajax(this.root_server, 'GET', this.headers)
                    .then(JSON.parse);
            }
        },

        create_queue: function(name, topic) {
            var self = this;

            this
                .service.create(name, topic)
                .then(
                    function() {
                        self.notify('queue', name);
                        self.notify('new:queue', name);
                        self.reset_read_events_timer(name);
                    },
                    function(req) {
                        console.error('error creating queue:', req.statusText + ', ' + req.responseText);
                    })
                .done();
        },

        interval_fn_id: null,

        reset_read_events_timer: function(name) {
            var self = this;

            if (this.interval_fn_id !== null) {
                clearInterval(this.interval_fn_id);
            }

            this.interval_fn_id = setInterval(function() {
                self.read_queue(name);
            }, 2000);
        },

        read_queue: function(name) {
            var self = this;

            this
                .service.read(name)
                .then(function(eventList) {
                    self.notify('events', eventList);
                })
                .done();
        },

        render_queues: function() {
            var self = this;

            this.service.list()
                .then(function(list) {
                    list.forEach(function(q) {
                        self.notify('queue', q.objectName);
                    });
                })
                .done();
        },

        render_events: function() {
            var self = this;

            this.service.list()
                .then(function(list) {
                    if (list.length > 0) {
                        var q = list[list.length - 1];

                        self.reset_read_events_timer(q.objectName);
                    }
                })
                .done();
        }
    };

    extend(cdmiQueuesModel).with(Observer);

    return {
        setup: function() {
            ctrls.updateButtonController.setup(cdmiQueuesModel);
            views.eventsView.setup(cdmiQueuesModel);
            views.queuesView.setup(cdmiQueuesModel);

            cdmiQueuesModel.setup();
            cdmiQueuesModel.add(views.queuesView);
            cdmiQueuesModel.add(views.eventsView);

            cdmiQueuesModel.render_queues();
            cdmiQueuesModel.render_events();
            console.info('app started');
        }
    };
});
<commit_msg>correcting the cdmi queue creation call headers<commit_after>/* global define */
/* jshint devel: true */

// this is were the application is assembled,
// configured and started.
// Search for the ``setup`` method.
define(['ajax', 'util', 'views', 'ctrls'], function(ajax, util, views, ctrls) {
    'use strict';

    var extend = util.extend,
        Observer = util.Observer;

    var cdmiQueuesModel = {
        setup: function() {
            this.observables = []; // NOTE: required by Observer
        },

        service: {
            root_server: '/api/queues',

            headers: {
                'Accept': 'application/cdmi-queue',
                'X-CDMI-Specification-Version': '1.0.2'
            },

            create: function(name, topic) {
                return ajax(this.root_server + '/' + name + '/' + topic, 'PUT', {
                        'Content-Type': 'application/cdmi-queue',
                        'Accept': 'application/cdmi-queue',
                        'X-CDMI-Specification-Version': '1.0.2'
                    }).then(JSON.parse);
            },

            read: function(name) {
                return ajax(this.root_server + '/' + name, 'GET', this.headers)
                    .then(JSON.parse)
                    .then(function(cdmi) { return cdmi.value; });
            },

            list: function() {
                return ajax(this.root_server, 'GET', this.headers)
                    .then(JSON.parse);
            }
        },

        create_queue: function(name, topic) {
            var self = this;

            this
                .service.create(name, topic)
                .then(
                    function() {
                        self.notify('queue', name);
                        self.notify('new:queue', name);
                        self.reset_read_events_timer(name);
                    },
                    function(req) {
                        console.error('error creating queue:', req.statusText + ', ' + req.responseText);
                    })
                .done();
        },

        interval_fn_id: null,

        reset_read_events_timer: function(name) {
            var self = this;

            if (this.interval_fn_id !== null) {
                clearInterval(this.interval_fn_id);
            }

            this.interval_fn_id = setInterval(function() {
                self.read_queue(name);
            }, 2000);
        },

        read_queue: function(name) {
            var self = this;

            this
                .service.read(name)
                .then(function(eventList) {
                    self.notify('events', eventList);
                })
                .done();
        },

        render_queues: function() {
            var self = this;

            this.service.list()
                .then(function(list) {
                    list.forEach(function(q) {
                        self.notify('queue', q.objectName);
                    });
                })
                .done();
        },

        render_events: function() {
            var self = this;

            this.service.list()
                .then(function(list) {
                    if (list.length > 0) {
                        var q = list[list.length - 1];

                        self.reset_read_events_timer(q.objectName);
                    }
                })
                .done();
        }
    };

    extend(cdmiQueuesModel).with(Observer);

    return {
        setup: function() {
            ctrls.updateButtonController.setup(cdmiQueuesModel);
            views.eventsView.setup(cdmiQueuesModel);
            views.queuesView.setup(cdmiQueuesModel);

            cdmiQueuesModel.setup();
            cdmiQueuesModel.add(views.queuesView);
            cdmiQueuesModel.add(views.eventsView);

            cdmiQueuesModel.render_queues();
            cdmiQueuesModel.render_events();
            console.info('app started');
        }
    };
});
<|endoftext|>


<commit_before>var update = function() {
    var openItems = [],
        completedItems = [],
        savedItems,
        totalOpen,
        totalClosed;
    $.openSection.setItems(Alloy.Collections.todo.getOpen());
    $.completedSection.setItems(Alloy.Collections.todo.getCompleted());
    $.openSection.headerTitle = Alloy.Collections.todo.open().length + ' open items';
    $.completedSection.headerTitle = Alloy.Collections.todo.completed().length + ' completed items';
    /**
     * change the completed item template
     */
    var items = $.completedSection.getItems();
    var count = 0;
    _.each(items, function(item) {
        item.template = 'closedTemplate';
        $.completedSection.updateItemAt(count, item);
        count++;
    });
};
/**
 * listeners
 */
$.newentry.addEventListener('return', function(e) {
    var desc,
        newTodo;
    desc = e.value;
    if (desc) {
        newTodo = Alloy.createModel('todo', {
            'desc' : desc,
            'priority' : 'high'
        });
        newTodo.save();
        Alloy.Collections.todo.add(newTodo);
        //clear the textfield
        $.newentry.value = '';
    }
});
Alloy.Collections.todo.on("add", update);
Alloy.Collections.todo.on('change', update);
/**
 * itemclick listener
 */
$.todolist.addEventListener('itemclick', function(e) {
    /**
     * completed defaults to false, onclick it toggles and view is updated
     */
    var item,
        model;
    //get the item from the relevant section
    item = $[e.section.id].getItemAt(e.itemIndex);
    //update the model and persist the update
    model = Alloy.Collections.todo.get(item.alloy_id.text);
    model.toggle();
});

//finally load the page
update();
$.index.open();
<commit_msg>more tidying up<commit_after>var update = function() {
    var openItems = [],
        completedItems = [],
        savedItems,
        totalOpen,
        totalClosed;
    $.openSection.setItems(Alloy.Collections.todo.getOpen());
    $.completedSection.setItems(Alloy.Collections.todo.getCompleted());
    $.openSection.headerTitle = Alloy.Collections.todo.open().length + ' open items';
    $.completedSection.headerTitle = Alloy.Collections.todo.completed().length + ' completed items';
    /**
     * change the completed item template
     */
    var items = $.completedSection.getItems();
    var count = 0;
    _.each(items, function(item) {
        item.template = 'closedTemplate';
        $.completedSection.updateItemAt(count, item);
        count++;
    });
};
/**
 * listeners
 */
$.newentry.addEventListener('return', function(e) {
    var desc,
        newTodo;
    desc = e.value;
    if (desc) {
        newTodo = Alloy.createModel('todo', {
            'desc' : desc,
            'priority' : 'high'
        });
        newTodo.save();
        Alloy.Collections.todo.add(newTodo);
        //clear the textfield
        $.newentry.value = '';
    }
});
_.each(['add', 'change'], function(event) {
    Alloy.Collections.todo.on(event, update);
});

/**
 * itemclick listener
 */
$.todolist.addEventListener('itemclick', function(e) {
    /**
     * completed defaults to false, onclick it toggles and view is updated
     */
    var item,
        model;
    //get the item from the relevant section
    item = $[e.section.id].getItemAt(e.itemIndex);
    //update the model and persist the update
    model = Alloy.Collections.todo.get(item.alloy_id.text);
    model.toggle();
});

//finally load the page
update();
$.index.open();<|endoftext|>


<commit_before>'use strict'

let io = null

let connectionInfo

const MIN_WAIT = 100
let wait = MIN_WAIT

let states = []

function resetWait() {
    wait = MIN_WAIT
}

function incrementWait() {
    const MAX_WAIT = 2000
    if (wait < MAX_WAIT)
        wait *= 1.25
    else
        wait = MAX_WAIT
}

function connect(address) {
    io = new WebSocket(address)
    io.onopen = () => {
        resetWait()
        if (connectionInfo) {
            connectionInfo.visible = false
        }
    };

    io.onmessage = (msg) => {
        states.push(JSON.parse(msg.data))
    }

    io.onclose = () => {
        if (connectionInfo) {
            connectionInfo.text = 'Reconnecting...'
            connectionInfo.visible = true
        }
        io = null
        setTimeout(() => {
            incrementWait()
            connect(address);
        }, wait)
    };

    io.onerror = (err) => {
        console.error('Socket encountered error: ', err.message, 'Closing socket')
        io.close()
        io = null
    };
}

function send(data) {
    if (io && io.readyState === 1) {
        console.log('sending data: ', data)
        io.send(data)
    }
}

const Application = PIXI.Application,
    loader = PIXI.loader,
    resources = PIXI.loader.resources,
    Sprite = PIXI.Sprite

const app = new Application(
    1000, 1000, {
        backgroundColor: 0x1099bb,
        autoResize: true,
        antialias: true,
        resolution: 1,
    },
)

const addr = window.location.hostname === 'localhost' ? 'ws://localhost:8081' : 'wss://beta.jnferner.com/socket'
connect(addr)
document.body.appendChild(app.view)

loader
    .add([{
        name: 'pong',
        url: 'assets/pong.json'
    }, ])
    .on('progress', loadProgressHandler)
    .load(setup)

document.addEventListener("keydown", (event) => {
    send('keydown:' + event.key)
})
document.addEventListener("keyup", (event) => {
    send('keyup:' + event.key)
})

function loadProgressHandler(loader, resource) {
    console.log('loading: ' + resource.name + ' (' + resource.url + ')')
    console.log('progress: ' + loader.progress + '%')
    if (resource.error)
        console.error(resource.error)
}

let ball

function setup() {
    const background = new Sprite(resources.pong.textures['fancy-court.png'])
    background.width = 1000
    background.height = 1000
    app.stage.addChild(background)

    connectionInfo = new PIXI.Text('')
    connectionInfo.style.fill = 0xe3e3ed
    connectionInfo.style.dropShadow = true
    connectionInfo.style.dropShadowAlpha = 0.8
    connectionInfo.anchor.set(0.5)
    connectionInfo.y = 30
    connectionInfo.x = 120
    app.stage.addChild(connectionInfo)

    ball = new Sprite(resources.pong.textures['fancy-ball.png'])
    ball.anchor.set(0.5)
    app.stage.addChild(ball)

    app.ticker.add(gameLoop)
}

let state = connecting

function gameLoop(delta) {
    state()
}

function connecting() {
    connectionInfo.text = 'Connecting...'
    connectionInfo.visible = true

    const renderTime = getRenderTime()
    const index = getIndexOfRenderState(states, renderTime)
    if (index >= 0) {
        connectionInfo.visible = false
        state = play
    }
}

function play() {
    render(states)
}

function render(states) {
    const renderTime = getRenderTime()
    const index = getIndexOfRenderState(states, renderTime)
    if (index < 0)
        return
    states.splice(0, index)
    let interpolatedState = getInterpolatedState(states[0], states[1], renderTime)
    setWorld(interpolatedState)
}

function getRenderTime() {
    const now = new Date().getTime()
    const INTERPOLATION_DELTA = 100
    return now - INTERPOLATION_DELTA
}

function getIndexOfRenderState(states, renderTime) {
    const found = states.findIndex((state) => state.timestamp >= renderTime)
    return found - 1
}

function getInterpolatedState(from, to, renderTime) {
    const total = to.timestamp - from.timestamp
    const progress = renderTime - from.timestamp
    if (total === 0 || progress === 0)
        return from
    const fraction = progress / total
    let state = from
    state.vel.x += (to.vel.x - from.vel.x) * fraction
    state.vel.y += (to.vel.y - from.vel.y) * fraction
    state.pos.x += (to.pos.x - from.pos.x) * fraction
    state.pos.y += (to.pos.y - from.pos.y) * fraction
    state.timestamp = renderTime
    return state
}

function setWorld(state) {
    ball.x = state.pos.x
    ball.y = state.pos.y
}<commit_msg>Client: Remove loading background<commit_after>'use strict'

let io = null

let connectionInfo

const MIN_WAIT = 100
let wait = MIN_WAIT

let states = []

function resetWait() {
    wait = MIN_WAIT
}

function incrementWait() {
    const MAX_WAIT = 2000
    if (wait < MAX_WAIT)
        wait *= 1.25
    else
        wait = MAX_WAIT
}

function connect(address) {
    io = new WebSocket(address)
    io.onopen = () => {
        resetWait()
        if (connectionInfo) {
            connectionInfo.visible = false
        }
    };

    io.onmessage = (msg) => {
        states.push(JSON.parse(msg.data))
    }

    io.onclose = () => {
        if (connectionInfo) {
            connectionInfo.text = 'Reconnecting...'
            connectionInfo.visible = true
        }
        io = null
        setTimeout(() => {
            incrementWait()
            connect(address);
        }, wait)
    };

    io.onerror = (err) => {
        console.error('Socket encountered error: ', err.message, 'Closing socket')
        io.close()
        io = null
    };
}

function send(data) {
    if (io && io.readyState === 1) {
        console.log('sending data: ', data)
        io.send(data)
    }
}

const Application = PIXI.Application,
    loader = PIXI.loader,
    resources = PIXI.loader.resources,
    Sprite = PIXI.Sprite

const app = new Application(
    1000, 1000, {
        backgroundColor: 0xFFFFFF,
        autoResize: true,
        antialias: true,
        resolution: 1,
    },
)

const addr = window.location.hostname === 'localhost' ? 'ws://localhost:8081' : 'wss://beta.jnferner.com/socket'
connect(addr)
document.body.appendChild(app.view)

loader
    .add([{
        name: 'pong',
        url: 'assets/pong.json'
    }, ])
    .on('progress', loadProgressHandler)
    .load(setup)

document.addEventListener("keydown", (event) => {
    send('keydown:' + event.key)
})
document.addEventListener("keyup", (event) => {
    send('keyup:' + event.key)
})

function loadProgressHandler(loader, resource) {
    console.log('loading: ' + resource.name + ' (' + resource.url + ')')
    console.log('progress: ' + loader.progress + '%')
    if (resource.error)
        console.error(resource.error)
}

let ball

function setup() {
    const background = new Sprite(resources.pong.textures['fancy-court.png'])
    background.width = 1000
    background.height = 1000
    app.stage.addChild(background)

    connectionInfo = new PIXI.Text('')
    connectionInfo.style.fill = 0xe3e3ed
    connectionInfo.style.dropShadow = true
    connectionInfo.style.dropShadowAlpha = 0.8
    connectionInfo.anchor.set(0.5)
    connectionInfo.y = 30
    connectionInfo.x = 120
    app.stage.addChild(connectionInfo)

    ball = new Sprite(resources.pong.textures['fancy-ball.png'])
    ball.anchor.set(0.5)
    app.stage.addChild(ball)

    app.ticker.add(gameLoop)
}

let state = connecting

function gameLoop(delta) {
    state()
}

function connecting() {
    connectionInfo.text = 'Connecting...'
    connectionInfo.visible = true

    const renderTime = getRenderTime()
    const index = getIndexOfRenderState(states, renderTime)
    if (index >= 0) {
        connectionInfo.visible = false
        state = play
    }
}

function play() {
    render(states)
}

function render(states) {
    const renderTime = getRenderTime()
    const index = getIndexOfRenderState(states, renderTime)
    if (index < 0)
        return
    states.splice(0, index)
    let interpolatedState = getInterpolatedState(states[0], states[1], renderTime)
    setWorld(interpolatedState)
}

function getRenderTime() {
    const now = new Date().getTime()
    const INTERPOLATION_DELTA = 100
    return now - INTERPOLATION_DELTA
}

function getIndexOfRenderState(states, renderTime) {
    const found = states.findIndex((state) => state.timestamp >= renderTime)
    return found - 1
}

function getInterpolatedState(from, to, renderTime) {
    const total = to.timestamp - from.timestamp
    const progress = renderTime - from.timestamp
    if (total === 0 || progress === 0)
        return from
    const fraction = progress / total
    let state = from
    state.vel.x += (to.vel.x - from.vel.x) * fraction
    state.vel.y += (to.vel.y - from.vel.y) * fraction
    state.pos.x += (to.pos.x - from.pos.x) * fraction
    state.pos.y += (to.pos.y - from.pos.y) * fraction
    state.timestamp = renderTime
    return state
}

function setWorld(state) {
    ball.x = state.pos.x
    ball.y = state.pos.y
}<|endoftext|>


<commit_before>var async = require('async')
var css = require('dom-css')
var startsWith = require('lodash.startswith')
var request = require('request')

var height = window.innerHeight

var style = {
  header: {
    width: '80%',
    height: '125px',
    marginLeft: '10%',
    marginRight: '10%',
    textAlign: 'center',
    marginBottom: '3%',
    marginTop: '3%'
  },
  main: {
    width: '80%',
    marginLeft: '10%',
    marginRight: '10%',
    textAlign: 'center',
    position: 'relative'
  },
  footer: {
    width: '80%',
    marginLeft: '10%',
    marginRight: '10%',
    textAlign: 'center',
    position: 'relative',
    marginTop: '50px'
  },
  template: {
    textDecoration: 'none',
    fontSize: '200%'
  },
  logo: {
    width: '350px'
  },
  loader: {
    width: height * 0.5 + 'px',
    height: height * 0.5 + 'px',
    borderRadius: height * 0.25 + 'px'
  },
  messageContainer: {
    width: '26%',
    marginLeft: '37%',
    marginRight: '37%',
    position: 'absolute',
    top: '40%'
  },
  message: {
    textAlign: 'center',
    fontFamily: 'ClearSans-Medium',
    fontSize: '300%',
    color: 'rgb(150,150,150)',
    lineHeight: '1em',
    transition: 'color 0.7s'
  },
  messageDots: {
    textAlign: 'center',
    fontFamily: 'ClearSans-Medium',
    fontSize: '300%',
    color: 'rgb(150,150,150)',
    marginTop: '-30px'
  }
}

function getOrigin () {
  var port = window.location.port
  var origin = window.location.hostname
  if (port) {
    origin = origin + ':' + port
  }
  return 'http://' + origin
}

var apiServer = getOrigin()

var displayName = window.location.pathname.replace('/repo', '').slice(1)

// add logo
var header = document.createElement('div')
var img = document.createElement('img')
img.src='/assets/images/logo.svg'
css(header, style.header)
css(img, style.logo)
document.body.appendChild(header)
header.appendChild(img)

// add main loading element
var main = document.createElement('div')
document.body.appendChild(main)
css(main, style.main)
var loader = document.createElement('div')
loader.className = 'three-quarters-loader-big'
css(loader, style.loader)
main.appendChild(loader)
var messageContainer = document.createElement('div')
css(messageContainer, style.messageContainer)
main.appendChild(messageContainer)
var message = document.createElement('div')
message.innerHTML = 'loading'
css(message, style.message)
messageContainer.appendChild(message)
var messageDots = document.createElement('div')
messageDots.innerHTML = ''
css(messageDots, style.messageDots)
messageContainer.appendChild(messageDots)

// add repo information
var footer = document.createElement('div')
var template = document.createElement('a')
css(footer, style.footer)
template.innerHTML = displayName
template.href = displayName
template.className = 'template-link'
css(template, style.template)
document.body.appendChild(footer)
footer.appendChild(template)

var counter = 0

var makeProgress = function () {
  if (counter == 0) messageDots.innerHTML = '.'
  if (counter == 1) messageDots.innerHTML = '..'
  if (counter == 2) messageDots.innerHTML = '...'
  if (counter == 2) counter = 0
  else counter += 1
}

var makeError = function (err) {
  message.innerHTML = 'failed!'
  messageDots.innerHTML = ''
  css(message, {color: 'rgb(220, 80, 50)'})
  css(loader, {border: '30px solid rgb(220, 80, 50)'})
}

var makeSuccess = function () {
  message.innerHTML = 'ready!'
  messageDots.innerHTML = ''
  css(message, {color: 'rgb(91,186,71)'})
  css(loader, {border: '30px solid rgb(91,186,71)'})
}

var templateName = displayName.replace(/\//g, '-')
async.waterfall([
  function (next) {
    request({
      url: apiServer + '/api/deploy/' + templateName,
      json: true
    }, function (err, res, json) {
      if (err) {
        makeError(err)
      }
      return next(null, json['id'])
    })
  },
  function (deployId, next) {
    async.retry({ times: 60, interval: 1000 }, function (next) {
      makeProgress()
      request({
        url: apiServer + '/api/apps/' + templateName + '/' + deployId,
        json: true
      }, function (err, res, json) {
        var location  = json['location']
        if (location) {
          if (!startsWith(location, 'http://')) {
            location = 'http://' + location
          }
          makeSuccess()
          window.location.href = location
        } else {
          return next('retrying')
        }
      })
    }, function (err) {
      return next(new Error('deployment timed out'))
    })
  }
], function (err) {
  if (err) {
    makeError(err)
  }
})
<commit_msg>display error message earlier if deployment fails<commit_after>var async = require('async')
var css = require('dom-css')
var startsWith = require('lodash.startswith')
var request = require('request')

var height = window.innerHeight

var style = {
  header: {
    width: '80%',
    height: '125px',
    marginLeft: '10%',
    marginRight: '10%',
    textAlign: 'center',
    marginBottom: '3%',
    marginTop: '3%'
  },
  main: {
    width: '80%',
    marginLeft: '10%',
    marginRight: '10%',
    textAlign: 'center',
    position: 'relative'
  },
  footer: {
    width: '80%',
    marginLeft: '10%',
    marginRight: '10%',
    textAlign: 'center',
    position: 'relative',
    marginTop: '50px'
  },
  template: {
    textDecoration: 'none',
    fontSize: '200%'
  },
  logo: {
    width: '350px'
  },
  loader: {
    width: height * 0.5 + 'px',
    height: height * 0.5 + 'px',
    borderRadius: height * 0.25 + 'px'
  },
  messageContainer: {
    width: '26%',
    marginLeft: '37%',
    marginRight: '37%',
    position: 'absolute',
    top: '40%'
  },
  message: {
    textAlign: 'center',
    fontFamily: 'ClearSans-Medium',
    fontSize: '300%',
    color: 'rgb(150,150,150)',
    lineHeight: '1em',
    transition: 'color 0.7s'
  },
  messageDots: {
    textAlign: 'center',
    fontFamily: 'ClearSans-Medium',
    fontSize: '300%',
    color: 'rgb(150,150,150)',
    marginTop: '-30px'
  }
}

function getOrigin () {
  var port = window.location.port
  var origin = window.location.hostname
  if (port) {
    origin = origin + ':' + port
  }
  return 'http://' + origin
}

var apiServer = getOrigin()

var displayName = window.location.pathname.replace('/repo', '').slice(1)

// add logo
var header = document.createElement('div')
var img = document.createElement('img')
img.src='/assets/images/logo.svg'
css(header, style.header)
css(img, style.logo)
document.body.appendChild(header)
header.appendChild(img)

// add main loading element
var main = document.createElement('div')
document.body.appendChild(main)
css(main, style.main)
var loader = document.createElement('div')
loader.className = 'three-quarters-loader-big'
css(loader, style.loader)
main.appendChild(loader)
var messageContainer = document.createElement('div')
css(messageContainer, style.messageContainer)
main.appendChild(messageContainer)
var message = document.createElement('div')
message.innerHTML = 'loading'
css(message, style.message)
messageContainer.appendChild(message)
var messageDots = document.createElement('div')
messageDots.innerHTML = ''
css(messageDots, style.messageDots)
messageContainer.appendChild(messageDots)

// add repo information
var footer = document.createElement('div')
var template = document.createElement('a')
css(footer, style.footer)
template.innerHTML = displayName
template.href = displayName
template.className = 'template-link'
css(template, style.template)
document.body.appendChild(footer)
footer.appendChild(template)

var counter = 0

var makeProgress = function () {
  if (counter == 0) messageDots.innerHTML = '.'
  if (counter == 1) messageDots.innerHTML = '..'
  if (counter == 2) messageDots.innerHTML = '...'
  if (counter == 2) counter = 0
  else counter += 1
}

var makeError = function (err) {
  message.innerHTML = 'failed!'
  messageDots.innerHTML = ''
  css(message, {color: 'rgb(220, 80, 50)'})
  css(loader, {border: '30px solid rgb(220, 80, 50)'})
}

var makeSuccess = function () {
  message.innerHTML = 'ready!'
  messageDots.innerHTML = ''
  css(message, {color: 'rgb(91,186,71)'})
  css(loader, {border: '30px solid rgb(91,186,71)'})
}

var templateName = displayName.replace(/\//g, '-')
async.waterfall([
  function (next) {
    request({
      url: apiServer + '/api/deploy/' + templateName,
      json: true
    }, function (err, res, json) {
      if (err) {
        makeError(err)
      }
      return next(null, json['id'])
    })
  },
  function (deployId, next) {
    async.retry({ times: 60, interval: 1000 }, function (next) {
      makeProgress()
      request({
        url: apiServer + '/api/apps/' + templateName + '/' + deployId,
        json: true
      }, function (err, res, json) {
        var location  = json['location']
        var status = json['status']
        if (location) {
          if (!startsWith(location, 'http://')) {
            location = 'http://' + location
          }
          makeSuccess()
          window.location.href = location
        } else if (status === 'failed') {
          makeError()
        }
      })
    }, function (err) {
      return next(new Error('deployment timed out'))
    })
  }
], function (err) {
  if (err) {
    makeError(err)
  }
})
<|endoftext|>


<commit_before>var angle = 0;
function doClickRotateImage(e){
	// rotate the image
	angle += 20;
	if(angle >= 360){
		angle = 0;
	}
	var m = Ti.UI.create2DMatrix({
    	rotate: angle
	});
	var a = {
  		transform: m,
  		duration: 2000,
  		autoreverse: true
	};

	$.ivRotateImage.animate(a);
}

$.index.open();
<commit_msg>Played with it some more<commit_after>var angle = 0;
function doClickRotateImage(e){
	// rotate the image
	angle += 45;
	if(angle >= 180){
		angle = 0;
	}
	var m = Ti.UI.create2DMatrix({
    	rotate: angle,
    	scale: 1.5

	});
	var a = {
  		transform: m,
  		duration: 2000,
  		autoreverse: true
	};

	$.ivRotateImage.animate(a);
}

$.index.open();
<|endoftext|>


<commit_before>/**
 * Login service.
 */
exports = module.exports = function(promptHandler, initiateHandler) {
  var express = require('express');
  var router = new express.Router();

  router.get('/', promptHandler);
  router.post('/', initiateHandler);

  return router;
};

exports['@implements'] = 'http://i.bixbyjs.org/http/Service';
exports['@path'] = '/login';
exports['@require'] = [
  './handlers/prompt',
  './handlers/initiate'
];
<commit_msg>Remove unused route.<commit_after>/**
 * Login service.
 */
exports = module.exports = function(promptHandler, initiateHandler) {
  var express = require('express');

  var router = new express.Router();
  router.get('/', promptHandler);

  return router;
};

exports['@implements'] = 'http://i.bixbyjs.org/http/Service';
exports['@path'] = '/login';
exports['@require'] = [
  './handlers/prompt'
];
<|endoftext|>


<commit_before>var express = require('express');
var router = new express.Router();

router.get('/', function(req, res, next) {
  res.render('polls/index');
});

router.get('/new', function(req, res, next) {
  res.render('polls/new');
});

router.get('/:id', function(req, res, next) {
  res.render('polls/show');
});

router.get('/:id/edit', function(req, res, next) {
  res.render('polls/edit');
});

module.exports = router;
<commit_msg>Stub all Polls routes<commit_after>var express = require('express');
var router = new express.Router();

router.route('/')
.get(function(req, res, next) {
  res.render('polls/index');
})
.post(function(req, res, next) {
  res.send('created new poll');
});

router.route('/new')
.get(function(req, res, next) {
  res.render('polls/new');
});

router.route('/:id')
.get(function(req, res, next) {
  res.render('polls/show');
})
.put(function(req, res, next) {
  res.send('updated poll');
})
.delete(function(req, res, next) {
  res.send('deleted poll');
});

router.route('/:id/edit')
.get(function(req, res, next) {
  res.render('polls/edit');
});

module.exports = router;
<|endoftext|>


<commit_before>'use strict';

var ngS3Upload = angular.module('angular-s3-upload', ["angular-s3-upload-tpls"]);
ngS3Upload.directive('ngS3Upload', [ '$upload', function($upload) {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      label: '@',
      uploadHelper: '=',
      buttonClass: '@',
      index: '=',
      key: '@',
      path: '@',
      successCallback: '=',
      failureCallback: '=',
      progressCallback: '=',
      awsApi:'=',
      bucket: '@',
      filename: '@'
    },
    templateUrl: 'templates/angular-s3-upload-button.html',
    link: function(scope, element, attr) {
      scope.awsApi.getAWSToken(scope.key).then(function(data){
        scope.aws = {};
        scope.aws.policy = data.policy;
        scope.aws.signature = data.signature;
        scope.aws.key = data.key;
      }, function(err){
        if (typeof scope.failureCallback !== "undefined"){
          scope.failureCallback(err);
        } // die silently
      });
    },
    controller: function($scope) {
      $scope.createUUID = function () {
          return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
              var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
              return v.toString(16);
          });
      };

      $scope.onFileSelect = function($files) {
        for ( var i = 0; i < $files.length; i++) {
          var file = $files[i];
          if ( typeof $scope.filename == "undefined" ) {
            $scope.filename = $scope.createUUID();
          }
          var fullPath = $scope.key+"/"+$scope.filename;
          if ( typeof $scope.path != "undefined" ) {
            fullPath = $scope.key+"/"+$scope.path+"/"+$scope.filename;
          }
          $scope.upload = $upload.upload({
            url: 'https://'+$scope.bucket+'.s3.amazonaws.com/',
            method: 'POST',
            data: {
                'key' : fullPath,
                'acl' : 'public-read',
                'Content-Type' : file.type,
                'AWSAccessKeyId': $scope.aws.key,
                'Policy' : $scope.aws.policy,
                'Signature' : $scope.aws.signature
            },
            file: file
          }).progress(function(evt) {
              // parseInt(100.0 * evt.loaded / evt.total));
              if ( typeof $scope.progressCallback.progress !== "undefined" ) {
                $scope.progressCallback(evt);
              }
          }).success(function(data, status, headers, config) {
            if ( typeof $scope.successCallback !== "undefined" ) {
              $scope.successCallback($scope.filename, data, status, headers, config, $scope.index);
            }
          }).error(function(data, status, headers, config) {
            if ( typeof $scope.failureCallback !== "undefined" ) {
              $scope.failureCallback(data, status, headers, config, $scope.index);
            } // die silently
          });
        }
      };
    }
  };
}]);<commit_msg>fixed wrong index position<commit_after>'use strict';

var ngS3Upload = angular.module('angular-s3-upload', ["angular-s3-upload-tpls"]);
ngS3Upload.directive('ngS3Upload', [ '$upload', function($upload) {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      label: '@',
      uploadHelper: '=',
      buttonClass: '@',
      index: '=',
      key: '@',
      path: '@',
      successCallback: '=',
      failureCallback: '=',
      progressCallback: '=',
      awsApi:'=',
      bucket: '@',
      filename: '@'
    },
    templateUrl: 'templates/angular-s3-upload-button.html',
    link: function(scope, element, attr) {
      scope.awsApi.getAWSToken(scope.key).then(function(data){
        scope.aws = {};
        scope.aws.policy = data.policy;
        scope.aws.signature = data.signature;
        scope.aws.key = data.key;
      }, function(err){
        if (typeof scope.failureCallback !== "undefined"){
          scope.failureCallback(err);
        } // die silently
      });
    },
    controller: function($scope) {
      $scope.createUUID = function () {
          return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
              var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
              return v.toString(16);
          });
      };

      $scope.onFileSelect = function($files) {
        for ( var i = 0; i < $files.length; i++) {
          var file = $files[i];
          if ( typeof $scope.filename == "undefined" ) {
            $scope.filename = $scope.createUUID();
          }
          var fullPath = $scope.key+"/"+$scope.filename;
          if ( typeof $scope.path != "undefined" ) {
            fullPath = $scope.key+"/"+$scope.path+"/"+$scope.filename;
          }
          $scope.upload = $upload.upload({
            url: 'https://'+$scope.bucket+'.s3.amazonaws.com/',
            method: 'POST',
            data: {
                'key' : fullPath,
                'acl' : 'public-read',
                'Content-Type' : file.type,
                'AWSAccessKeyId': $scope.aws.key,
                'Policy' : $scope.aws.policy,
                'Signature' : $scope.aws.signature
            },
            file: file
          }).progress(function(evt) {
              // parseInt(100.0 * evt.loaded / evt.total));
              if ( typeof $scope.progressCallback.progress !== "undefined" ) {
                $scope.progressCallback(evt);
              }
          }).success(function(data, status, headers, config) {
            if ( typeof $scope.successCallback !== "undefined" ) {
              $scope.successCallback($scope.filename, $scope.index, data, status, headers, config);
            }
          }).error(function(data, status, headers, config) {
            if ( typeof $scope.failureCallback !== "undefined" ) {
              $scope.failureCallback($scope.index, data, status, headers, config, $scope.index);
            } // die silently
          });
        }
      };
    }
  };
}]);<|endoftext|>


<commit_before>

var convertToCurrency = function(number){
    return '$' +  number.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
};

// Takes movie map as parameter
function makeMovieItem(movie) {
    return "
" + movie.name
        + " directed by " + movie.director
        + "
"
        + "
Release Date: " + movie.releaseDate + "
"
        + "
Box Office Earnings: "
        + convertToCurrency(movie.boxOffice) + "
"
        + "
Stars: " + movie.stars + "
"
        + "
"
        +"
";
};

function makeSingleMovieItem(movie) {
    return "
" + movie.name
        + " directed by " + movie.director
        + "
"
        + "
Release Date: " + movie.releaseDate + "
"
        + "
Box Office Earnings: "
        + convertToCurrency(movie.boxOffice) + "
"
        + "
Stars: " + movie.stars + "
"
        + "
Reviews:
"
        + "
"
        +"
";
};

function makeReviewItem(review) {
    return "
\"" + review.review + "\""
        + "
"
        + "
Stars: " + review.rating + "
"
        + "
Reviewer: " + review.name + "
"
        + "
 <button id='edit-" + review._id +"' class='edit-review-btn' type='button' name='editReviewBtn'>Edit</button>
"
        + "
"
        +"
";
};

// Get Movie list buton click event handler
$("#movie-list-btn").click(function() {
    $.getJSON( "/movie", function(data) {
        var items = [];

        // Call back function takes each movie object and formats
        // it to a list item which contains another list of
        // the movie's attributes.
        $.each( data, function( key, movie ) {
            items.push( makeMovieItem(movie));
        });

        $( "
", {
            "class": "full-movie-list",
            html: items.join( "" )
        }).appendTo( "#movie-list" );
    });
});

// Get movie button click event handler
$("#movie-get-btn").click(function() {
    var movieId = $("#movie-entry-select").val();
    var urlMovie = "/movie/" + movieId;
    var movieMeta = "#meta-" + movieId;

    $.getJSON( urlMovie, function(data) {
        var reviews = [];
        $( "#movie-entry" ).html("
" + makeSingleMovieItem(data) + "
");
        $.each( data.reviews, function( key, review ) {
            reviews.push( makeReviewItem(review));
        });
        $( "
", {
            "class": "review-list",
            html: reviews.join( "" )
        }).appendTo( movieMeta );
    });
});

function makeReviewForm(review) {
    return "<form action='/review/" + review._id + "' method='post'>"
        + "
Name: "
        + "<input type='text' name='name' value='" + review.name
        + "'/>
"
        + "
Stars: "
        + "<input type='text' name='rating' value='" + review.rating
        + "'/>
"
        + "
Review: "
        + "<textarea name='review' rows='4'>" + review.review
        + "</textarea>
"
        + "
"
        + "<button type='submit'>Submit</button>"
        + "
"
        + "</form>";
};

$(document).on("click",".edit-review-btn", function(event) {
    var editBtnId = event.currentTarget.id;
    var reviewId = editBtnId.split("-")[1];
    var urlReview = "/review/" + reviewId;
    var reviewIdSelect = "#" + reviewId;

    $.getJSON( urlReview, function(data) {
        var reviewForm = makeReviewForm(data);
        $(reviewIdSelect).html(reviewForm);

    });
});

// Contains dropdown of movies for get movie
$(document).ready( function () {
    $.getJSON( "/movie", function(data) {
        var items = [];

        // Call back function takes each movie object and formats
        // it to a list item which contains another list of
        // the movie's attributes.
        $.each( data, function( key, movie ) {
            items.push( "<option value='" + movie._id + "'>" + movie.name
                        +"</option>" );
        });

        $("#movie-entry-select").append(items.join(""));
    });

});
<commit_msg>Handle Submission of PUT Request<commit_after>

var convertToCurrency = function(number){
    return '$' +  number.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
};

// Takes movie map as parameter
function makeMovieItem(movie) {
    return "
" + movie.name
        + " directed by " + movie.director
        + "
"
        + "
Release Date: " + movie.releaseDate + "
"
        + "
Box Office Earnings: "
        + convertToCurrency(movie.boxOffice) + "
"
        + "
Stars: " + movie.stars + "
"
        + "
"
        +"
";
};

function makeSingleMovieItem(movie) {
    return "
" + movie.name
        + " directed by " + movie.director
        + "
"
        + "
Release Date: " + movie.releaseDate + "
"
        + "
Box Office Earnings: "
        + convertToCurrency(movie.boxOffice) + "
"
        + "
Stars: " + movie.stars + "
"
        + "
Reviews:
"
        + "
"
        +"
";
};

function makeReviewItem(review) {
    return "
\"" + review.review + "\""
        + "
"
        + "
Stars: " + review.rating + "
"
        + "
Reviewer: " + review.name + "
"
        + "
 <button id='edit-" + review._id +"' class='edit-review-btn' type='button' name='editReviewBtn'>Edit</button>
"
        + "
"
        +"
";
};

// Get Movie list buton click event handler
$("#movie-list-btn").click(function() {
    $.getJSON( "/movie", function(data) {
        var items = [];

        // Call back function takes each movie object and formats
        // it to a list item which contains another list of
        // the movie's attributes.
        $.each( data, function( key, movie ) {
            items.push( makeMovieItem(movie));
        });

        $( "
", {
            "class": "full-movie-list",
            html: items.join( "" )
        }).appendTo( "#movie-list" );
    });
});

// Get movie button click event handler
$("#movie-get-btn").click(function() {
    var movieId = $("#movie-entry-select").val();
    var urlMovie = "/movie/" + movieId;
    var movieMeta = "#meta-" + movieId;

    $.getJSON( urlMovie, function(data) {
        var reviews = [];
        $( "#movie-entry" ).html("
" + makeSingleMovieItem(data) + "
");
        $.each( data.reviews, function( key, review ) {
            reviews.push( makeReviewItem(review));
        });
        $( "
", {
            "class": "review-list",
            html: reviews.join( "" )
        }).appendTo( movieMeta );
    });
});

function makeReviewForm(review) {
    return "
"
        + "
Name: "
        + "<input type='text' name='name' value='" + review.name
        + "'/>
"
        + "
Stars: "
        + "<input type='text' name='rating' value='" + review.rating
        + "'/>
"
        + "
Review: "
        + "<input name='review' value='" + review.review
        + "'/>
"
        + "
"
        + "<button type='submit'>Submit</button>"
        + "
"
        + "
";
};

$(document).on("click",".edit-review-btn", function(event) {
    var editBtnId = event.currentTarget.id;
    var reviewId = editBtnId.split("-")[1];
    var urlReview = "/review/" + reviewId;
    var reviewIdSelect = "#" + reviewId;

    $.getJSON( urlReview, function(data) {
        var reviewForm =  makeReviewForm(data);
        $(reviewIdSelect).html(reviewForm);
    });
});

$(document).on("click", ".review-submit-btn", function(event) {
    console.log("Clicked Submit Button");
    var reviewId = event.currentTarget.attributes.reviewid.nodeValue;
    var reviewFields = $('#' + reviewId).find('input');
    var urlReview = "/review/" + reviewId;
    var sendData = {};
    $.each(reviewFields, function(index, dataMap) {
        sendData[dataMap.name] = dataMap.value;
    });

    $.ajax({
        type: 'put',
	url: urlReview,
	data: sendData,
        sucess: function(){

        }
    });
    window.location.reload(true);
});

// Contains dropdown of movies for get movie
$(document).ready( function () {
    $.getJSON( "/movie", function(data) {
        var items = [];

        // Call back function takes each movie object and formats
        // it to a list item which contains another list of
        // the movie's attributes.
        $.each( data, function( key, movie ) {
            items.push( "<option value='" + movie._id + "'>" + movie.name
                        +"</option>" );
        });

        $("#movie-entry-select").append(items.join(""));
    });

});
<|endoftext|>


<commit_before>(function() {
"use strict";

var supportsMultiple = self.HTMLInputElement && "valueLow" in HTMLInputElement.prototype;

var descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");

self.multirange = function(input) {
	if (supportsMultiple || input.classList.contains("multirange")) {
		return;
	}

	var value = input.getAttribute("value");
	var values = value === null ? [] : value.split(",");
	var min = +(input.min || 0);
	var max = +(input.max || 100);
	var ghost = input.cloneNode();

	input.classList.add("multirange", "original");
	ghost.classList.add("multirange", "ghost");

	input.value = values[0] || min + (max - min) / 2;
	ghost.value = values[1] || min + (max - min) / 2;

	input.parentNode.insertBefore(ghost, input.nextSibling);

	Object.defineProperty(input, "originalValue", descriptor.get ? descriptor : {
		// Fuck you Safari >:(
		get: function() { return this.value; },
		set: function(v) { this.value = v; }
	});

	Object.defineProperties(input, {
		valueLow: {
			get: function() { return Math.min(this.originalValue, ghost.value); },
			set: function(v) { this.originalValue = v; },
			enumerable: true
		},
		valueHigh: {
			get: function() { return Math.max(this.originalValue, ghost.value); },
			set: function(v) { ghost.value = v; },
			enumerable: true
		}
	});

	if (descriptor.get) {
		// Again, fuck you Safari
		Object.defineProperty(input, "value", {
			get: function() { return this.valueLow + "," + this.valueHigh; },
			set: function(v) {
				var values = v.split(",");
				this.valueLow = values[0];
				this.valueHigh = values[1];
				update();
			},
			enumerable: true
		});
	}

	function update() {
		ghost.style.setProperty("--low", 100 * ((input.valueLow - min) / (max - min)) + 1 + "%");
		ghost.style.setProperty("--high", 100 * ((input.valueHigh - min) / (max - min)) - 1 + "%");
	}

	input.addEventListener("input", update);
	ghost.addEventListener("input", update);

	update();
}

multirange.init = function() {
	[].slice.call(document.querySelectorAll("input[type=range][multiple]:not(.multirange)")).forEach(multirange);
}

if (document.readyState == "loading") {
	document.addEventListener("DOMContentLoaded", multirange.init);
}
else {
	multirange.init();
}

})();
<commit_msg>Trigger oninput on both handles (#33)<commit_after>(function() {
"use strict";

var supportsMultiple = self.HTMLInputElement && "valueLow" in HTMLInputElement.prototype;

var descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");

self.multirange = function(input) {
	if (supportsMultiple || input.classList.contains("multirange")) {
		return;
	}

	var value = input.getAttribute("value");
	var values = value === null ? [] : value.split(",");
	var min = +(input.min || 0);
	var max = +(input.max || 100);
	var ghost = input.cloneNode();

	input.classList.add("multirange", "original");
	ghost.classList.add("multirange", "ghost");

	input.value = values[0] || min + (max - min) / 2;
	ghost.value = values[1] || min + (max - min) / 2;

	input.parentNode.insertBefore(ghost, input.nextSibling);

	Object.defineProperty(input, "originalValue", descriptor.get ? descriptor : {
		// Fuck you Safari >:(
		get: function() { return this.value; },
		set: function(v) { this.value = v; }
	});

	Object.defineProperties(input, {
		valueLow: {
			get: function() { return Math.min(this.originalValue, ghost.value); },
			set: function(v) { this.originalValue = v; },
			enumerable: true
		},
		valueHigh: {
			get: function() { return Math.max(this.originalValue, ghost.value); },
			set: function(v) { ghost.value = v; },
			enumerable: true
		}
	});

	if (descriptor.get) {
		// Again, fuck you Safari
		Object.defineProperty(input, "value", {
			get: function() { return this.valueLow + "," + this.valueHigh; },
			set: function(v) {
				var values = v.split(",");
				this.valueLow = values[0];
				this.valueHigh = values[1];
				update();
			},
			enumerable: true
		});
	}

	ghost.oninput = input.oninput.bind(input);

	function update() {
		ghost.style.setProperty("--low", 100 * ((input.valueLow - min) / (max - min)) + 1 + "%");
		ghost.style.setProperty("--high", 100 * ((input.valueHigh - min) / (max - min)) - 1 + "%");
	}

	input.addEventListener("input", update);
	ghost.addEventListener("input", update);

	update();
}

multirange.init = function() {
	[].slice.call(document.querySelectorAll("input[type=range][multiple]:not(.multirange)")).forEach(multirange);
}

if (document.readyState == "loading") {
	document.addEventListener("DOMContentLoaded", multirange.init);
}
else {
	multirange.init();
}

})();
<|endoftext|>


<commit_before>import React, {PropTypes} from "react";
import cx from "classnames";
import styles from "./form-group.scss";

function CustomControl({className, type, label, children, validationState, ...props}) {
    props.className = cx(
        styles.customControl,
        styles[`custom-${type}`]
    );

    const formGroupClass = cx(styles["form-group"], validationState && styles[`has-${validationState}`], className);

    const input = React.cloneElement(children, {
        className: cx(children.props.className, styles['custom-control-input'])
    });

    return (

                {input}

                {label}

    );
}

CustomControl.propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    label: PropTypes.string,
    type: PropTypes.oneOf(["checkbox", "radio"]),
    validationState: PropTypes.oneOf(["default", "danger", "success", "warning"]),
};

CustomControl.defaultProps = {
    type: "checkbox"
};

export default CustomControl;<commit_msg>update styles for price-table<commit_after>import React, {PropTypes} from "react";
import cx from "classnames";
import styles from "./form-group.scss";

function CustomControl({className, type, label, children, validationState, ...props}) {
    props.className = cx(
        styles.customControl,
        styles[`custom-${type}`]
    );

    const formGroupClass = cx(styles["form-group"], validationState && styles[`has-${validationState}`], className);

    const input = React.cloneElement(children, {
        className: cx(children.props.className, styles['custom-control-input'])
    });

    return (

                {input}

                {label}

    );
}

CustomControl.propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
    type: PropTypes.oneOf(["checkbox", "radio"]),
    validationState: PropTypes.oneOf(["default", "danger", "success", "warning"]),
};

CustomControl.defaultProps = {
    type: "checkbox"
};

export default CustomControl;<|endoftext|>


<commit_before>angular.module('asics').controller('RsvpCtrl', [
  '$scope',
  '$state',
  '$mdToast',
  '$stateParams',
  'rsvp',
  function ($scope, $state, $mdToast, $stateParams, rsvp) {
    $scope.result = '';
    $scope.guest = {};
    $scope.strings = {};
    $scope.isAthlete = false;
    $scope.bgImage = 'default';

    rsvp.getGuestByToken($stateParams.token)
        .then(readGuest)
        .catch(onInvalidToken);

    function readGuest(guest) {
      if (guest.rsvp)
        return toStateConfirmed(guest);

      angular.copy(guest, $scope.guest);
      angular.copy(confirmStrings[guest.language], $scope.strings);

      if (guest.occupation == 'Atleta Asics') {
        $scope.isAthlete = true;
        $scope.bgImage = 'athlete'
      }
    }

    function onInvalidToken() {
      $state.go('home');
    }

    $scope.confirmInvitation = function () {
      rsvp.postConfirm($scope.guest)
          .then(toStateConfirmed)
          .catch(errorToast);
    };

    function toStateConfirmed(guest) {
      $state.go("rsvp.confirmed", {guest: guest})
    }

    function errorToast(error) {
      $mdToast.show(
          $mdToast.simple()
              .textContent("Erro ao confirmar presença: " + error)
              .position('top right')
              .hideDelay(3000)
              .theme('error-toast')
      );
    }
  }
]);

var confirmStrings = {
  EN: {
    hello: "Hello",
    welcomeMessage: "We look forward to welcoming you at the ASICS Hub.",
    formLabelGuest: "Click on the button below to confirm attendance.",
    formLabelAthlete: "We want you to feel at home, so please answer this question before confirm your attendance.",
    formLabelMusic: "Which song makes you feel like a champion?",
    formErrorRequiredMusic: "Please, type the song name",
    formButtonConfirmPresence: "Confirm attendance"
  },
  PT: {
    hello: "Olá",
    welcomeMessage: "Estamos ansiosos para recebê-lo no ASICS Hub.",
    formLabelGuest: "Clique no botão abaixo para confirmar presença.",
    formLabelAthlete: "Nós queremos que você se sinta em casa, então por favor responda a esta pergunta antes de confirmar a sua presença.",
    formLabelMusic: "Que música faz você se sentir como um campeão?",
    formErrorRequiredMusic: "Por favor, preencha o nome da música",
    formButtonConfirmPresence: "Confirmar presença"
  }
};
<commit_msg>set rsvp background image to always be default<commit_after>angular.module('asics').controller('RsvpCtrl', [
  '$scope',
  '$state',
  '$mdToast',
  '$stateParams',
  'rsvp',
  function ($scope, $state, $mdToast, $stateParams, rsvp) {
    $scope.result = '';
    $scope.guest = {};
    $scope.strings = {};
    $scope.isAthlete = false;
    $scope.bgImage = 'default';

    rsvp.getGuestByToken($stateParams.token)
        .then(readGuest)
        .catch(onInvalidToken);

    function readGuest(guest) {
      if (guest.rsvp)
        return toStateConfirmed(guest);

      angular.copy(guest, $scope.guest);
      angular.copy(confirmStrings[guest.language], $scope.strings);

      // if (guest.occupation == 'Atleta Asics') {
      //   $scope.isAthlete = true;
      //   $scope.bgImage = 'athlete'
      // }
    }

    function onInvalidToken() {
      $state.go('home');
    }

    $scope.confirmInvitation = function () {
      rsvp.postConfirm($scope.guest)
          .then(toStateConfirmed)
          .catch(errorToast);
    };

    function toStateConfirmed(guest) {
      $state.go("rsvp.confirmed", {guest: guest})
    }

    function errorToast(error) {
      $mdToast.show(
          $mdToast.simple()
              .textContent("Erro ao confirmar presença: " + error)
              .position('top right')
              .hideDelay(3000)
              .theme('error-toast')
      );
    }
  }
]);

var confirmStrings = {
  EN: {
    hello: "Hello",
    welcomeMessage: "We look forward to welcoming you at the ASICS Hub.",
    formLabelGuest: "Click on the button below to confirm attendance.",
    formLabelAthlete: "We want you to feel at home, so please answer this question before confirm your attendance.",
    formLabelMusic: "Which song makes you feel like a champion?",
    formErrorRequiredMusic: "Please, type the song name",
    formButtonConfirmPresence: "Confirm attendance"
  },
  PT: {
    hello: "Olá",
    welcomeMessage: "Estamos ansiosos para recebê-lo no ASICS Hub.",
    formLabelGuest: "Clique no botão abaixo para confirmar presença.",
    formLabelAthlete: "Nós queremos que você se sinta em casa, então por favor responda a esta pergunta antes de confirmar a sua presença.",
    formLabelMusic: "Que música faz você se sentir como um campeão?",
    formErrorRequiredMusic: "Por favor, preencha o nome da música",
    formButtonConfirmPresence: "Confirmar presença"
  }
};
<|endoftext|>


<commit_before>/*global
    $,
    jQuery,
    error,
    endless,
    ajax,
    templateHelper,
    Routing,
    appLocale,
    exports,
    module,
    require,
    define
*/
/*jslint nomen: true */                 /* Tolerate dangling _ in identifiers */
/*jslint vars: true */           /* Tolerate many var statements per function */
/*jslint white: true */                       /* tolerate messy whithe spaces */
/*jslint browser: true */
/*jslint devel: true */                         /* Assume console, alert, ... */
/*jslint windows: true */               /* Assume window object (for browsers)*/
/*jslint maxerr: 100 */                           /* Maximum number of errors */

/*******************************************************************************
 * Class dependencies:
 *      jquery > 1.8.3
 *      jsrender
 *      jsviews
 * External dependencies:
 *      FOS Routing
 *      templateHelper
 *      ajax
 *      error
 *      endless
 ******************************************************************************/

/*******************************************************************************
    FansWorld idols Class Module 1.1

*******************************************************************************/
(function (root, factory) {
    "use strict";
    if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like enviroments that support module.exports,
        // like Node.
        module.exports = factory(require('jQuery'), require('Routing'), require('templateHelper'), require('ajax'), require('error'), require('endless'));
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jQuery', 'Routing', 'templateHelper', 'ajax', 'error', 'endless'], factory);
    } else {
        // Browser globals (root is window)
        root.IDOLS = factory(root.jQuery, root.Routing, root.templateHelper, root.ajax, root.error, root.endless);
    }
}(this, function (jQuery, Routing, templateHelper, ajax, error) {
    "use strict";
    var IDOLS = (function() {
        function IDOLS() {
            ///////////////////
            // Internal init //
            ///////////////////
            this.jQuery = jQuery;
            this.version = '1.0';
            this.category = null;
            this.activePage = 1;
            var that = this;
            if($("div.list-idols").attr('data-got-more')){
                this.addMore = true;
            }else{
                this.addMore = false;
            }
            this.getIdols();
            $("ul.categories li a").on('click', function(e){
                e.preventDefault();
                that.category = $(this).parent().attr('data-category-id');
                that.activePage = 1;

                $(".list-idols dl").html(' ');

                that.getIdols(function(){
                    var docHeight = window.innerHeight;
                    $(document).scrollTop(( docHeight - 20 ));
                });
            });
        }
        IDOLS.prototype.getIdols = function(callback) {
            var that = this;
            var deferred = new jQuery.Deferred();

            endless.stop();
            $("div.list-idols").addClass('loading');

            ajax.genericAction('idol_ajaxlist', {
                'tc': that.category,
                'page': that.activePage
            },
            function(r){
                var i;
                var tplHelperCallback = function(){
                    $(".list-idols dl").find(".btn_idolship.add:not('.loading-small')").each(function() {
                        $(this).fwIdolship();
                    });
                    if(i === (r.idols.length-1)){
                        $("div.list-idols").removeClass('loading');
                        if(typeof(callback) !== 'undefined'){
                            callback();
                        }
                    }
                };
                if(r.idols.length > 0) {
                    for(i in r.idols) {
                        if (r.idols[i].hasOwnProperty(i)) {
                            var element = r.idols[i];
                            console.log("loaded idol: %s id: %s", element.name, element.id);
                            templateHelper.renderTemplate('idol-list_element', element, $(".list-idols dl"), false, tplHelperCallback);
                        }
                        $("div.list-idols").removeClass('loading');
                    }
                } else {
                    $("div.list-idols").removeClass('loading');
                }

                that.addMore = r.gotMore;
                that.activePage += 1;
                endless.init(1, function() {
                    that.getIdols();
                });
            },
            function(r){
                $("div.list-idols").removeClass('loading');
                endless.stop();
                deferred.reject(new Error(error));
            });

            return deferred.promise();
        };
        IDOLS.prototype.getVersion = function() {
            console.log(this.version);
            return this.version;
        };
        return IDOLS;
    }());
    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return IDOLS;
}));

$(document).ready(function () {
    "use strict";
    window.fansworld = window.fansworld || {};
    window.fansworld.idols = new window.IDOLS();
});<commit_msg>team category  = numeric non alpha<commit_after>/*global
    $,
    jQuery,
    error,
    endless,
    ajax,
    templateHelper,
    Routing,
    appLocale,
    exports,
    module,
    require,
    define
*/
/*jslint nomen: true */                 /* Tolerate dangling _ in identifiers */
/*jslint vars: true */           /* Tolerate many var statements per function */
/*jslint white: true */                       /* tolerate messy whithe spaces */
/*jslint browser: true */
/*jslint devel: true */                         /* Assume console, alert, ... */
/*jslint windows: true */               /* Assume window object (for browsers)*/
/*jslint maxerr: 100 */                           /* Maximum number of errors */

/*******************************************************************************
 * Class dependencies:
 *      jquery > 1.8.3
 *      jsrender
 *      jsviews
 * External dependencies:
 *      FOS Routing
 *      templateHelper
 *      ajax
 *      error
 *      endless
 ******************************************************************************/

/*******************************************************************************
    FansWorld idols Class Module 1.1

*******************************************************************************/
(function (root, factory) {
    "use strict";
    if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like enviroments that support module.exports,
        // like Node.
        module.exports = factory(require('jQuery'), require('Routing'), require('templateHelper'), require('ajax'), require('error'), require('endless'));
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jQuery', 'Routing', 'templateHelper', 'ajax', 'error', 'endless'], factory);
    } else {
        // Browser globals (root is window)
        root.IDOLS = factory(root.jQuery, root.Routing, root.templateHelper, root.ajax, root.error, root.endless);
    }
}(this, function (jQuery, Routing, templateHelper, ajax, error) {
    "use strict";
    var IDOLS = (function() {
        function IDOLS() {
            ///////////////////
            // Internal init //
            ///////////////////
            this.jQuery = jQuery;
            this.version = '1.0';
            this.category = 0;
            this.activePage = 1;
            var that = this;
            if($("div.list-idols").attr('data-got-more')){
                this.addMore = true;
            }else{
                this.addMore = false;
            }
            this.getIdols();
            $("ul.categories li a").on('click', function(e){
                e.preventDefault();
                that.category = parseInt($(this).parent().attr('data-category-id'));
                that.activePage = 1;

                $(".list-idols dl").html(' ');

                that.getIdols(function(){
                    var docHeight = window.innerHeight;
                    $(document).scrollTop(( docHeight - 20 ));
                });
            });
        }
        IDOLS.prototype.getIdols = function(callback) {
            var that = this;
            var deferred = new jQuery.Deferred();

            endless.stop();
            $("div.list-idols").addClass('loading');

            ajax.genericAction('idol_ajaxlist', {
                'tc': that.category,
                'page': that.activePage
            },
            function(r){
                var i;
                var tplHelperCallback = function(){
                    $(".list-idols dl").find(".btn_idolship.add:not('.loading-small')").each(function() {
                        $(this).fwIdolship();
                    });
                    if(i === (r.idols.length-1)){
                        $("div.list-idols").removeClass('loading');
                        if(typeof(callback) !== 'undefined'){
                            callback();
                        }
                    }
                };
                if(r.idols.length > 0) {
                    for(i in r.idols) {
                        if (r.idols[i].hasOwnProperty(i)) {
                            var element = r.idols[i];
                            console.log("loaded idol: %s id: %s", element.name, element.id);
                            templateHelper.renderTemplate('idol-list_element', element, $(".list-idols dl"), false, tplHelperCallback);
                        }
                        $("div.list-idols").removeClass('loading');
                    }
                } else {
                    $("div.list-idols").removeClass('loading');
                }

                that.addMore = r.gotMore;
                that.activePage += 1;
                endless.init(1, function() {
                    that.getIdols();
                });
            },
            function(r){
                $("div.list-idols").removeClass('loading');
                endless.stop();
                deferred.reject(new Error(error));
            });

            return deferred.promise();
        };
        IDOLS.prototype.getVersion = function() {
            console.log(this.version);
            return this.version;
        };
        return IDOLS;
    }());
    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return IDOLS;
}));

$(document).ready(function () {
    "use strict";
    window.fansworld = window.fansworld || {};
    window.fansworld.idols = new window.IDOLS();
});<|endoftext|>


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

    var EMOGen = require('emo-gen');
    var objectAssign = require('object-assign');

    /**
     * A grunt style guide generator
     *
     * @param {Object} grunt
     * @param {Array} gruntFilesArray  an unexpanded grunt file array
     * @param {Object} gruntOptions  grunt task options
     */
    var StyleGuideGenerator = function(grunt, gruntFilesArray, gruntOptions) {
        /**
         * @property styleGuideGenerator.grunt
         * @type {Object}
         */
        this.grunt = grunt;

        /**
         * An unexpanded grunt file array
         *
         * @property styleGuideGenerator.gruntFilesArray
         * @type {Array}
         */
        this.gruntFilesArray = gruntFilesArray;

        /**
         * Grunt task options
         *
         * @property styleGuideGenerator.gruntOptions
         * @type {Array}
         */
        this.gruntOptions = gruntOptions;

        /**
         * An emo-gen instance
         *
         * @property styleGuideGenerator.generator
         */
        this.generator = new EMOGen(
            this.gruntOptions.components,
            this.gruntOptions
        );
    };

    /**
     * Convert a grunt files object to a
     * grunt file mapping options object
     * (http://gruntjs.com/api/grunt.file#grunt.file.expandmapping)
     *
     * @method StyleGuideGenerator.createGruntFileMappingOptions
     * @return {Object} gruntFileMappingOptions
     * @static
     */
    StyleGuideGenerator.createGruntFileMappingOptions = function(gruntFilesObject) {
        var gruntFileMappingOptions = objectAssign({}, gruntFilesObject);

        // delete those properties we don't need
        delete gruntFileMappingOptions.src;
        delete gruntFileMappingOptions.dest;

        return gruntFileMappingOptions;
    };

    var proto = StyleGuideGenerator.prototype;

    /**
     * Build the style guide
     *
     * @method styleGuideGenerator.build
     * @return {Object} a promise
     */
    proto.build = function() {
        return this.generator.place().then(function() {
            var files = this.expandGruntFilesArray(this.gruntFilesArray);

            return this.generator.copy(files);
        }.bind(this)).then(function() {
            return this.generator.build();
        }.bind(this));
    };

    /**
     * Expand grunt files array
     *
     * @method styleGuideGenerator.expandGruntFilesArray
     * @return {Object} gruntFilesMappingList
     */
    proto.expandGruntFilesArray = function(gruntFilesArray) {
        var gruntFilesMappingList = [];

        if (!gruntFilesArray) {
            return gruntFilesMappingList;
        }

        gruntFilesArray.forEach(function(gruntFilesObject) {
            this.grunt.file.expandMapping(
                gruntFilesObject.src,
                gruntFilesObject.dest,
                StyleGuide.createGruntFileMappingOptions(gruntFilesObject)
            ).forEach(function(srcDestFileMapping) {
                var flattenedArray = [];
                var dest = srcDestFileMapping.dest;

                srcDestFileMapping.src.forEach(function(src) {
                    flattenedArray.push({
                        src: src,
                        dest: dest
                    });
                });

                gruntFilesMappingList = gruntFilesMappingList.concat(flattenedArray);
            });
        }.bind(this));

        return gruntFilesMappingList;
    };

    module.exports = StyleGuideGenerator;

} ());<commit_msg>Added log statement for copied files<commit_after>(function() {
    'use strict';

    var EMOGen = require('emo-gen');
    var objectAssign = require('object-assign');

    /**
     * A grunt style guide generator
     *
     * @param {Object} grunt
     * @param {Array} gruntFilesArray  an unexpanded grunt file array
     * @param {Object} gruntOptions  grunt task options
     */
    var StyleGuideGenerator = function(grunt, gruntFilesArray, gruntOptions) {
        /**
         * @property styleGuideGenerator.grunt
         * @type {Object}
         */
        this.grunt = grunt;

        /**
         * An unexpanded grunt file array
         *
         * @property styleGuideGenerator.gruntFilesArray
         * @type {Array}
         */
        this.gruntFilesArray = gruntFilesArray;

        /**
         * Grunt task options
         *
         * @property styleGuideGenerator.gruntOptions
         * @type {Array}
         */
        this.gruntOptions = gruntOptions;

        /**
         * An emo-gen instance
         *
         * @property styleGuideGenerator.generator
         */
        this.generator = new EMOGen(
            this.gruntOptions.components,
            this.gruntOptions
        );
    };

    /**
     * Convert a grunt files object to a
     * grunt file mapping options object
     * (http://gruntjs.com/api/grunt.file#grunt.file.expandmapping)
     *
     * @method StyleGuideGenerator.createGruntFileMappingOptions
     * @return {Object} gruntFileMappingOptions
     * @static
     */
    StyleGuideGenerator.createGruntFileMappingOptions = function(gruntFilesObject) {
        var gruntFileMappingOptions = objectAssign({}, gruntFilesObject);

        // delete those properties we don't need
        delete gruntFileMappingOptions.src;
        delete gruntFileMappingOptions.dest;

        return gruntFileMappingOptions;
    };

    var proto = StyleGuideGenerator.prototype;

    /**
     * Build the style guide
     *
     * @method styleGuideGenerator.build
     * @return {Object} a promise
     */
    proto.build = function() {
        return this.generator.place().then(function() {
            var files = this.expandGruntFilesArray(this.gruntFilesArray);

            if (files.length > 0) {
                this.grunt.log.writeln('Copying ' + files.length + ' files');
            }

            return this.generator.copy(files);
        }.bind(this)).then(function() {
            return this.generator.build();
        }.bind(this));
    };

    /**
     * Expand grunt files array
     *
     * @method styleGuideGenerator.expandGruntFilesArray
     * @return {Object} gruntFilesMappingList
     */
    proto.expandGruntFilesArray = function(gruntFilesArray) {
        var gruntFilesMappingList = [];

        if (!gruntFilesArray) {
            return gruntFilesMappingList;
        }

        gruntFilesArray.forEach(function(gruntFilesObject) {
            this.grunt.file.expandMapping(
                gruntFilesObject.src,
                gruntFilesObject.dest,
                StyleGuide.createGruntFileMappingOptions(gruntFilesObject)
            ).forEach(function(srcDestFileMapping) {
                var flattenedArray = [];
                var dest = srcDestFileMapping.dest;

                srcDestFileMapping.src.forEach(function(src) {
                    flattenedArray.push({
                        src: src,
                        dest: dest
                    });
                });

                gruntFilesMappingList = gruntFilesMappingList.concat(flattenedArray);
            });
        }.bind(this));

        return gruntFilesMappingList;
    };

    module.exports = StyleGuideGenerator;

} ());<|endoftext|>


<commit_before>'use strict';

angular.module('eyoApp.facebook', ['ngRoute', 'ngFacebook'])

.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/facebook', {
        templateUrl: 'facebook/facebook.html',
        controller: 'facebookController'
    });
}])

.config(function ($facebookProvider) {
    $facebookProvider.setAppId('126685577873363');
    $facebookProvider.setPermissions("email, public_profile, user_posts, publish_actions, user_photos");
    $facebookProvider.setVersion('v2.4');
    $facebookProvider.setCustomInit({
        xfbml: true,
        cookie: true
    });
    //$facebookProvider.setCookie(true);
})

.run(function ($rootScope) {

    (function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement(s);
        js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
})

.controller('facebookController', ['$scope', '$facebook', function ($scope, $facebook) {
    $scope.isLoggedIn = false;
    $scope.logIn = function () {
        $facebook.login().then(function () {
            $scope.isLoggedIn = true;
            refresh();
        });
    }

    $scope.logOut = function () {
        $facebook.logout().then(function () {
            $scope.isLoggedIn = false;
            refresh();
        });
    }

    function refresh() {
        var fields = [
          'id',
          'name',
          'first_name',
          'middle_name',
          'last_name',
          'gender',
          'locale',
          'languages',
          'link',
          'username',
          'third_party_id',
          'installed',
          'timezone',
          'updated_time',
          'verified',
          'age_range',
          'bio',
          'birthday',
          'cover',
          'currency',
          'devices',
          'education',
          'email',
          'hometown',
          'interested_in',
          'location',
          'political',
          'payment_pricepoints',
          'favorite_athletes',
          'favorite_teams',
          'picture',
          'quotes',
          'relationship_status',
          'religion',
          'significant_other',
          'video_upload_limits',
          'website',
          'work'
          ].join(',');
        $facebook.api('/me', {
            fields: fields
        }).then(function (response) {
            console.log('response');
            console.log(response);
            $scope.welcomeMsg = "Welcome " + response.name;
            $scope.isLoggedIn = true;
            $scope.userInfo = response;
            $facebook.api('/me/picture').then(function (response) {
                console.log("picture response");
                console.log(response);
                $scope.picture = response.data.url;
                $facebook.api('/me/permissions').then(function (response) {
                    console.log('permissions response');
                    console.log(response);
                    $scope.permissions = response.data;
                    $facebook.api('/me/posts', {
                        fields: fields
                    }, function (response) {
                        $scope.posts = response.data;
                    });
                });
            });
        }, function (error) {
            console.log('Error');
            console.log(error);
            $scope.welcomeMsg = "Please Log In";
        });

    }

    refresh();

}]);
<commit_msg>add then to posts request in refresh()<commit_after>'use strict';

angular.module('eyoApp.facebook', ['ngRoute', 'ngFacebook'])

.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/facebook', {
        templateUrl: 'facebook/facebook.html',
        controller: 'facebookController'
    });
}])

.config(function ($facebookProvider) {
    $facebookProvider.setAppId('126685577873363');
    $facebookProvider.setPermissions("email, public_profile, user_posts, publish_actions, user_photos");
    $facebookProvider.setVersion('v2.4');
    $facebookProvider.setCustomInit({
        xfbml: true,
        cookie: true
    });
    //$facebookProvider.setCookie(true);
})

.run(function ($rootScope) {

    (function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement(s);
        js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
})

.controller('facebookController', ['$scope', '$facebook', function ($scope, $facebook) {
    $scope.isLoggedIn = false;
    $scope.logIn = function () {
        $facebook.login().then(function () {
            $scope.isLoggedIn = true;
            refresh();
        });
    }

    $scope.logOut = function () {
        $facebook.logout().then(function () {
            $scope.isLoggedIn = false;
            refresh();
        });
    }

    function refresh() {
        var fields = [
          'id',
          'name',
          'first_name',
          'middle_name',
          'last_name',
          'gender',
          'locale',
          'languages',
          'link',
          'username',
          'third_party_id',
          'installed',
          'timezone',
          'updated_time',
          'verified',
          'age_range',
          'bio',
          'birthday',
          'cover',
          'currency',
          'devices',
          'education',
          'email',
          'hometown',
          'interested_in',
          'location',
          'political',
          'payment_pricepoints',
          'favorite_athletes',
          'favorite_teams',
          'picture',
          'quotes',
          'relationship_status',
          'religion',
          'significant_other',
          'video_upload_limits',
          'website',
          'work'
          ].join(',');
        $facebook.api('/me', {
            fields: fields
        }).then(function (response) {
            console.log('response');
            console.log(response);
            $scope.welcomeMsg = "Welcome " + response.name;
            $scope.isLoggedIn = true;
            $scope.userInfo = response;
            $facebook.api('/me/picture').then(function (response) {
                console.log("picture response");
                console.log(response);
                $scope.picture = response.data.url;
                $facebook.api('/me/permissions').then(function (response) {
                    console.log('permissions response');
                    console.log(response);
                    $scope.permissions = response.data;
                    $facebook.api('/me/posts').then(function (response) {
                        console.log('posts response');
                        console.log(response);
                        $scope.posts = response.data;
                    });
                });
            });
        }, function (error) {
            console.log('Error');
            console.log(error);
            $scope.welcomeMsg = "Please Log In";
        });

    }

    refresh();

}]);
<|endoftext|>


<commit_before>window.addEventListener('load', function () {
	var vue = new Vue({
		el: '#app',
		data: {
			numberOfCols: 3,
			allTodos: [
				{desc:'First',  done:false, pri:'C', matches:true,},
				{desc:'Second', done:false, pri:'C', matches:true,},
				{desc:'Third',  done:false, pri:'C', matches:true,},
				{desc:'Fourth', done:false, pri:'C', matches:true,},
				{desc:'Fifth',  done:false, pri:'C', matches:true,},
			],
			addTodoTextbox: '',
			searchMode: 'Open',
			searchText: '',
		},
		computed: {
			matchingTodos: function() {
				return this.allTodos.filter( t => t.matches );
			},
			chunkedTodos: function() {
				return _.chunk(this.matchingTodos, this.numberOfCols);
			},
		},
		methods: {
			addTodo: function() {
				this.allTodos.push({desc:this.addTodoTextbox, done:false, pri:'C', matches:true,});
				this.addTodoTextbox = '';
			},
			todoDoneClass: function(todo) {
				return 'glyphicon glyphicon-' + (todo.done ? 'check' : 'unchecked');
			},
			priClass: function(todo) {
				return 'btn btn-xs' + (todo.pri == 'A' ? ' btn-danger' : todo.pri == 'B' ? ' btn-primary' : '');
			},
			toggleDone: function(todo) {
				todo.done = todo.done ? false : Date.now();
			},
			clickPri: function(todo) {
				todo.pri = todo.pri == 'A' ? 'C' : todo.pri == 'B' ? 'A' : 'B';
			},
			clickSearchMode: function() {
				this.searchMode = this.searchMode == 'Open' ? 'Done' : 'Open';
				this.search();
			},
			search: function() {
				for (todo of this.allTodos) {
					todo.matches = this.searchMode == 'Open' ? ! todo.done : todo.done;
				}
			},
		},
	});
});
<commit_msg>sort order<commit_after>function newTodo (desc) {
	return { desc, done: false, pri:'C', matches:true, order:'C' };
}

window.addEventListener('load', function () {
	var vue = new Vue({
		el: '#app',
		data: {
			numberOfCols: 3,
			allTodos: [
				newTodo('First'),
				newTodo('Second'),
				newTodo('Third'),
				newTodo('Fourth'),
				newTodo('Fifth'),
			],
			addTodoTextbox: '',
			searchMode: 'Open',
			searchText: '',
		},
		computed: {
			matchingTodos: function() {
				return _.sortBy(this.allTodos.filter( t => t.matches ), 'order');
			},
			chunkedTodos: function() {
				return _.chunk(this.matchingTodos, this.numberOfCols);
			},
		},
		methods: {
			addTodo: function() {
				this.allTodos.push(newTodo(this.addTodoTextbox));
				this.addTodoTextbox = '';
			},
			todoDoneClass: function(todo) {
				return 'glyphicon glyphicon-' + (todo.done ? 'check' : 'unchecked');
			},
			priClass: function(todo) {
				return 'btn btn-xs' + (todo.pri == 'A' ? ' btn-danger' : todo.pri == 'B' ? ' btn-primary' : '');
			},
			toggleDone: function(todo) {
				todo.done = todo.done ? false : Date.now();
			},
			clickPri: function(todo) {
				todo.pri = todo.pri == 'A' ? 'C' : todo.pri == 'B' ? 'A' : 'B';
			},
			clickSearchMode: function() {
				this.searchMode = this.searchMode == 'Open' ? 'Done' : 'Open';
				this.search();
			},
			search: function() {
				for (todo of this.allTodos) {
					todo.matches = this.searchMode == 'Open' ? ! todo.done : todo.done;
					todo.order = this.searchMode == 'Open' ? todo.pri : -todo.done;
				}
			},
		},
	});
});
<|endoftext|>


<commit_before>/**
 * MIT License
 *
 * Copyright (c) 2016 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com>
 * Copyright (c) 2016 Yusuke Suzuki <utatane.tea@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
/*eslint quote-props: [2, "always"] */

'use strict';

module.exports = {

    'plugins': [
        'react',
    ],

    'rules': {
        // ESLint-plugin-React
        // https://github.com/yannickcr/eslint-plugin-react
        'react/display-name': 0, // JSX transpiler creates displayName automatically.
        'react/forbid-prop-types': 0,
        'react/no-danger': 1,
        'react/no-deprecated': [1, { // Detect deprected styles
            'react': '15.0.0',
        }],
        'react/no-did-mount-set-state': [1, 'allow-in-func'],
        'react/no-did-update-set-state': [1, 'allow-in-func'],
        'react/no-direct-mutation-state': 1,
        'react/no-is-mounted': 2, // Disallow the deprected style
        'react/no-multi-comp': 0,
        'react/no-set-state': 0, // FIXME: Enable this rule as a waring
        'react/no-string-refs': 2, // Disallow the legacy style
        'react/no-unknown-property': 2,
        'react/prefer-es6-class': [2, 'always'],
        'react/prefer-stateless-function': 1,
        'react/prop-types': 1,
        'react/react-in-jsx-scope': 1,
        'react/require-extension': 0,
        'react/require-render-return': 2,
        'react/self-closing-comp': 2,
        'react/sort-comp': [1, {
            'order': [
                'constructor',
                'metadata',
                'rendering',
                'lifecycle',
                'everything-else'
            ],
            'groups': {
                'metadata': [
                    'displayName',
                    'propTypes',
                    'contextTypes',
                    'childContextTypes',
                    'mixins',
                    'getDefaultProps',
                    'getInitialState',
                    'getChildContext'
                ],
                'rendering': [
                    'render',
                    '/^render.+$/'
                ]
            }
        }],
        'react/sort-prop-types': [0, {
            'callbacksLast': true,
            'requiredFirst': true,
        }],
        'react/wrap-multilines': 2,

        // JSX-specific rules
        'react/jsx-boolean-value': [2, 'always'], // Force boolean attribute explicitly.
        'react/jsx-closing-bracket-location': 0,
        'react/jsx-curly-spacing': 1,
        'react/jsx-first-prop-new-line': [1, 'never'],
        'react/jsx-equals-spacing': [1, 'never'],
        'react/jsx-handler-names': [2, {
            'eventHandlerPrefix': 'on', // we need not differ this prefix from `eventHandlerPropPrefix`.
            'eventHandlerPropPrefix': 'on',
        }],
        'react/jsx-indent': [1, 4],
        'react/jsx-indent-props': 0,
        'react/jsx-key': 1,
        'react/jsx-max-props-per-line': 0,
        'react/jsx-no-bind': [2, {
            'ignoreRefs': true,
            'allowArrowFunctions': false,
            'allowBind': false,
        }],
        'react/jsx-no-duplicate-props': 2,
        'react/jsx-no-literals': 0,
        'react/jsx-no-target-blank': 1, // In our usecase, we would not need `window.opener` or the referrer.
        'react/jsx-no-undef': 2,
        'react/jsx-pascal-case': [2, {
            'allowAllCaps': false,
            'ignore': [],
        }],
        'react/jsx-sort-props': 0,
        'react/jsx-space-before-closing': 0, // I don't this is a serious problem.
        'react/jsx-uses-react': 1,
        'react/jsx-uses-vars': 1,
    }
};
<commit_msg>feat(eslint): enable new rules for react<commit_after>/**
 * MIT License
 *
 * Copyright (c) 2016 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com>
 * Copyright (c) 2016 Yusuke Suzuki <utatane.tea@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
/*eslint quote-props: [2, "always"] */

'use strict';

module.exports = {

    'plugins': [
        'react',
    ],

    'rules': {
        // ESLint-plugin-React
        // https://github.com/yannickcr/eslint-plugin-react
        'react/display-name': 0, // JSX transpiler creates displayName automatically.
        'react/forbid-prop-types': 0,
        'react/no-comment-textnodes': 1,
        'react/no-danger': 1,
        'react/no-deprecated': [1, { // Detect deprected styles
            'react': '15.0.0',
        }],
        'react/no-did-mount-set-state': [1, 'allow-in-func'],
        'react/no-did-update-set-state': [1, 'allow-in-func'],
        'react/no-direct-mutation-state': 1,
        'react/no-is-mounted': 2, // Disallow the deprected style
        'react/no-multi-comp': 0,
        'react/no-render-return-value': 2,
        'react/no-set-state': 0, // FIXME: Enable this rule as a waring
        'react/no-string-refs': 2, // Disallow the legacy style
        'react/no-unknown-property': 2,
        'react/prefer-es6-class': [2, 'always'],
        'react/prefer-stateless-function': 1,
        'react/prop-types': 1,
        'react/react-in-jsx-scope': 1,
        'react/require-extension': 0,
        'react/require-optimization': 0,
        'react/require-render-return': 2,
        'react/self-closing-comp': 2,
        'react/sort-comp': [1, {
            'order': [
                'constructor',
                'metadata',
                'rendering',
                'lifecycle',
                'everything-else'
            ],
            'groups': {
                'metadata': [
                    'displayName',
                    'propTypes',
                    'contextTypes',
                    'childContextTypes',
                    'mixins',
                    'getDefaultProps',
                    'getInitialState',
                    'getChildContext'
                ],
                'rendering': [
                    'render',
                    '/^render.+$/'
                ]
            }
        }],
        'react/sort-prop-types': [0, {
            'callbacksLast': true,
            'requiredFirst': true,
        }],
        'react/wrap-multilines': 2,

        // JSX-specific rules
        'react/jsx-boolean-value': [2, 'always'], // Force boolean attribute explicitly.
        'react/jsx-closing-bracket-location': 0,
        'react/jsx-curly-spacing': 1,
        'react/jsx-first-prop-new-line': [1, 'never'],
        'react/jsx-equals-spacing': [1, 'never'],
        'react/jsx-filename-extension': [2, {
            'extensions': ['.jsx', '.tsx'],
        }],
        'react/jsx-handler-names': [2, {
            'eventHandlerPrefix': 'on', // we need not differ this prefix from `eventHandlerPropPrefix`.
            'eventHandlerPropPrefix': 'on',
        }],
        'react/jsx-indent': [1, 4],
        'react/jsx-indent-props': 0,
        'react/jsx-key': 1,
        'react/jsx-max-props-per-line': 0,
        'react/jsx-no-bind': [2, {
            'ignoreRefs': true,
            'allowArrowFunctions': false,
            'allowBind': false,
        }],
        'react/jsx-no-duplicate-props': 2,
        'react/jsx-no-literals': 0,
        'react/jsx-no-target-blank': 1, // In our usecase, we would not need `window.opener` or the referrer.
        'react/jsx-no-undef': 2,
        'react/jsx-pascal-case': [2, {
            'allowAllCaps': false,
            'ignore': [],
        }],
        'react/jsx-sort-props': 0,
        'react/jsx-space-before-closing': 0, // I don't this is a serious problem.
        'react/jsx-uses-react': 1,
        'react/jsx-uses-vars': 1,
    }
};
<|endoftext|>