<commit_before>/*
Plugin to implement the MUC extension. http://xmpp.org/extensions/xep-0045.html
*/

Strophe.addConnectionPlugin('muc', {
    _connection: null,
    // The plugin must have the init function
    /***Function
    Initialize the MUC plugin. Sets the correct connection object and
    extends the namesace.
    */
    init: function(conn) {
        this._connection = conn;
        /* extend name space
	     *  NS.MUC - XMPP Multi-user chat namespace
	     *              from XEP 45.
	     *
	     */
        Strophe.addNamespace('MUC_OWNER', Strophe.NS.MUC+"#owner");
        Strophe.addNamespace('MUC_ADMIN', Strophe.NS.MUC+"#admin");
    },
    /***Function
    Join a multi-user chat room
    Parameters:
    (String) room - The multi-user chat room to join.
    (String) nick - The nickname to use in the chat room. Optional
    (Function) msg_handler_cb - The function call to handle messages from the
    specified chat room.
    (Function) pres_handler_cb - The function call back to handle presence
    in the chat room.
    (String) password - The optional password to use. (password protected
    rooms only)
    */
    join: function(room, nick, msg_handler_cb, pres_handler_cb, password) {
        var room_nick = this.test_append_nick(room, nick);
        var msg = $pres({from: this._connection.jid,
                         to: room_nick})
            .c("x",{xmlns: Strophe.NS.MUC});
        if (password)
        {
            var password_elem = Strophe.xmlElement("password",
                                                   [],
                                                   password);
            msg.cnode(password_elem);
        }
        if (msg_handler_cb)
        {
            this._connection.addHandler(function(stanza) {
                var from = stanza.getAttribute('from');
                var roomname = from.split("/");
                // filter on room name
                if (roomname.length > 1 && roomname[0] == room)
                {
                    return msg_handler_cb(stanza);
                }
                else
                {
                    return true;
                }
            },
				        null,
				        "message",
				        null,
				        null,
				        null);
        }
        if (pres_handler_cb)
        {
            this._connection.addHandler(function(stanza) {
                var xquery = stanza.getElementsByTagName("x");
                if (xquery.length > 0)
                {
		    //Handle only MUC user protocol
		    for (var i = 0; i < xquery.length; i++)
                    {
                        var xmlns = xquery[i].getAttribute("xmlns");

		        if (xmlns && xmlns.match(Strophe.NS.MUC))
		        {
                            return pres_handler_cb(stanza);
                        }
                    }
                }
                return true;
            },
                                        null,
                                        "presence",
                                        null,
                                        null,
                                        null);
        }
        this._connection.send(msg);
    },
    /***Function
    Leave a multi-user chat room
    Parameters:
    (String) room - The multi-user chat room to leave.
    (String) nick - The nick name used in the room.
    (Function) handler_cb - Optional function to handle the successful leave.
    Returns:
    iqid - The unique id for the room leave.
    */
    leave: function(room, nick, handler_cb) {
        var room_nick = this.test_append_nick(room, nick);
        var presenceid = this._connection.getUniqueId();
        var presence = $pres({type: "unavailable",
                              id: presenceid,
                              from: this._connection.jid,
                              to: room_nick})
            .c("x",{xmlns: Strophe.NS.MUC});
        this._connection.addHandler(handler_cb,
                                    null,
                                    "presence",
                                    null,
                                    presenceid,
                                    null);
        this._connection.send(presence);
        return presenceid;
    },
    /***Function
    Parameters:
    (String) room - The multi-user chat room name.
    (String) nick - The nick name used in the chat room.
    (String) message - The message to send to the room.
    Returns:
    msgiq - the unique id used to send the message
    */
    message: function(room, nick, message) {
        var room_nick = this.test_append_nick(room, nick);
        var msgid = this._connection.getUniqueId();
	var msg = $msg({to: room_nick,
                        from: this._connection.jid,
                        type: "groupchat",
                        id: msgid}).c("body",
                                      {xmlns: Strophe.NS.CLIENT}).t(message);
        msg.up().c("x", {xmlns: "jabber:x:event"}).c("composing");
        this._connection.send(msg);
        return msgid;
    },
    /***Function
    Start a room configuration.
    Parameters:
    (String) room - The multi-user chat room name.
    Returns:
    id - the unique id used to send the configuration request
    */
    configure: function(room) {
        //send iq to start room configuration
        var config = $iq({to:room,
                          type: "get"}).c("query",
                                          {xmlns: Strophe.NS.MUC_OWNER});
        var stanza = config.tree();
	return this._connection.sendIQ(stanza,
                                       function(){},
                                       function(){});
    },
    /***Function
    Cancel the room configuration
    Parameters:
    (String) room - The multi-user chat room name.
    Returns:
    id - the unique id used to cancel the configuration.
    */
    cancelConfigure: function(room) {
        //send iq to start room configuration
        var config = $iq({to: room,
                          type: "set"})
            .c("query", {xmlns: Strophe.NS.MUC_OWNER})
            .c("x", {xmlns: "jabber:x:data", type: "cancel"});
        var stanza = config.tree();
	return this._connection.sendIQ(stanza,
                                       function(){},
                                       function(){});
    },
    /***Function
    Save a room configuration.
    Parameters:
    (String) room - The multi-user chat room name.
    (Array) configarray - an array of form elements used to configure the room.
    Returns:
    id - the unique id used to save the configuration.
    */
    saveConfiguration: function(room, configarray) {
        var config = $iq({to: room,
                          type: "set"})
            .c("query", {xmlns: Strophe.NS.MUC_OWNER})
            .c("x", {xmlns: "jabber:x:data", type: "submit"});
        for (var i = 0; i >= configarray.length; i++) {
            config.cnode(configarray[i]);
        }
        var stanza = config.tree();
	return this._connection.sendIQ(stanza,
                                       function(){},
                                       function(){});
    },
    /***Function
    Parameters:
    (String) room - The multi-user chat room name.
    Returns:
    id - the unique id used to create the chat room.
    */
    createInstantRoom: function(room) {
        var room = $iq({to: room,
                        type: "set"})
            .c("query", {xmlns: Strophe.NS.MUC_OWNER})
            .c("x", {xmlns: "jabber:x:data",
                     type: "submit"});
        return this._connection.sendIQ(room.tree(),
                                       function() {},
                                       function() {});
    },
    /***
     Set the topic of the chat room.
     Parameters:
     (String) room - The multi-user chat room name.
     (String) topic - Topic message.
     */
    setTopic: function(room, topic) {
        var msg = $msg({to: room,
                        from: this._connection.jid,
                        type: "groupchat"})
            .c("subject", {xmlns: "jabber:client"}).t(topic);
        this._connection.send(msg.tree());
    },
    /***Function
    Changes the role and affiliation of a member of a MUC room.
    The modification can only be done by a room moderator. An error will be
    returned if the user doesn't have permission.
    Parameters:
    (String) room - The multi-user chat room name.
    (String) nick - The nick name of the user to modify.
    (String) role - The new role of the user.
    (String) affiliation - The new affiliation of the user.
    (String) reason - The reason for the change.
    Returns:
    iq - the id of the mode change request.
    */
    modifyUser: function(room, nick, role, affiliation, reason) {
	var item_attrs = {nick: nick};
	if (role !== null)
	{
            item_attrs["role"] = role;
	}
	if (affiliation !== null)
	{
            item_attrs["affiliation"] = affiliation;
	}
        var item = $build("item", item_attrs);
	if (reason !== null)
	{
	    item.cnode(Strophe.xmlElement("reason", reason));
	}
        var room = $iq({to: room,
                        type: "set"})
            .c("query", {xmlns: Strophe.NS.MUC_OWNER}).cnode(item.tree());
        return this._connection.sendIQ(room.tree(),
                                       function() {},
                                       function() {});
    },
    /***Function
    Change the current users nick name.
    Parameters:
    (String) room - The multi-user chat room name.
    (String) user - The new nick name.
    */
    changeNick: function(room, user) {
        var room_nick = this.test_append_nick(room, user);
        var presence = $pres({from: this._connection.jid,
                              to: room_nick})
            .c("x",{xmlns: Strophe.NS.MUC});
        this._connection.send(presence.tree());
    },
    /***Function
    List all chat room available on a server.
    Parameters:
    (String) server - name of chat server.
    (String) handle_cb - Function to call for room list return.
    */
    listRooms: function(server, handle_cb) {
        var iq = $iq({to: server,
                      from: this._connection.jid,
                      type: "get"})
            .c("query",{xmlns: Strophe.NS.DISCO_ITEMS});
        this._connection.sendIQ(iq, handle_cb, function(){});
    },
    test_append_nick: function(room, nick) {
        var room_nick = room;
        if (nick)
        {
            room_nick += "/" + nick;
        }
        return room_nick;
    }
});<commit_msg>escape nick<commit_after>/*
Plugin to implement the MUC extension. http://xmpp.org/extensions/xep-0045.html
*/

Strophe.addConnectionPlugin('muc', {
    _connection: null,
    // The plugin must have the init function
    /***Function
    Initialize the MUC plugin. Sets the correct connection object and
    extends the namesace.
    */
    init: function(conn) {
        this._connection = conn;
        /* extend name space
	     *  NS.MUC - XMPP Multi-user chat namespace
	     *              from XEP 45.
	     *
	     */
        Strophe.addNamespace('MUC_OWNER', Strophe.NS.MUC+"#owner");
        Strophe.addNamespace('MUC_ADMIN', Strophe.NS.MUC+"#admin");
    },
    /***Function
    Join a multi-user chat room
    Parameters:
    (String) room - The multi-user chat room to join.
    (String) nick - The nickname to use in the chat room. Optional
    (Function) msg_handler_cb - The function call to handle messages from the
    specified chat room.
    (Function) pres_handler_cb - The function call back to handle presence
    in the chat room.
    (String) password - The optional password to use. (password protected
    rooms only)
    */
    join: function(room, nick, msg_handler_cb, pres_handler_cb, password) {
        var room_nick = this.test_append_nick(room, nick);
        var msg = $pres({from: this._connection.jid,
                         to: room_nick})
            .c("x",{xmlns: Strophe.NS.MUC});
        if (password)
        {
            var password_elem = Strophe.xmlElement("password",
                                                   [],
                                                   password);
            msg.cnode(password_elem);
        }
        if (msg_handler_cb)
        {
            this._connection.addHandler(function(stanza) {
                var from = stanza.getAttribute('from');
                var roomname = from.split("/");
                // filter on room name
                if (roomname.length > 1 && roomname[0] == room)
                {
                    return msg_handler_cb(stanza);
                }
                else
                {
                    return true;
                }
            },
				        null,
				        "message",
				        null,
				        null,
				        null);
        }
        if (pres_handler_cb)
        {
            this._connection.addHandler(function(stanza) {
                var xquery = stanza.getElementsByTagName("x");
                if (xquery.length > 0)
                {
		    //Handle only MUC user protocol
		    for (var i = 0; i < xquery.length; i++)
                    {
                        var xmlns = xquery[i].getAttribute("xmlns");

		        if (xmlns && xmlns.match(Strophe.NS.MUC))
		        {
                            return pres_handler_cb(stanza);
                        }
                    }
                }
                return true;
            },
                                        null,
                                        "presence",
                                        null,
                                        null,
                                        null);
        }
        this._connection.send(msg);
    },
    /***Function
    Leave a multi-user chat room
    Parameters:
    (String) room - The multi-user chat room to leave.
    (String) nick - The nick name used in the room.
    (Function) handler_cb - Optional function to handle the successful leave.
    Returns:
    iqid - The unique id for the room leave.
    */
    leave: function(room, nick, handler_cb) {
        var room_nick = this.test_append_nick(room, nick);
        var presenceid = this._connection.getUniqueId();
        var presence = $pres({type: "unavailable",
                              id: presenceid,
                              from: this._connection.jid,
                              to: room_nick})
            .c("x",{xmlns: Strophe.NS.MUC});
        this._connection.addHandler(handler_cb,
                                    null,
                                    "presence",
                                    null,
                                    presenceid,
                                    null);
        this._connection.send(presence);
        return presenceid;
    },
    /***Function
    Parameters:
    (String) room - The multi-user chat room name.
    (String) nick - The nick name used in the chat room.
    (String) message - The message to send to the room.
    Returns:
    msgiq - the unique id used to send the message
    */
    message: function(room, nick, message) {
        var room_nick = this.test_append_nick(room, nick);
        var msgid = this._connection.getUniqueId();
	var msg = $msg({to: room_nick,
                        from: this._connection.jid,
                        type: "groupchat",
                        id: msgid}).c("body",
                                      {xmlns: Strophe.NS.CLIENT}).t(message);
        msg.up().c("x", {xmlns: "jabber:x:event"}).c("composing");
        this._connection.send(msg);
        return msgid;
    },
    /***Function
    Start a room configuration.
    Parameters:
    (String) room - The multi-user chat room name.
    Returns:
    id - the unique id used to send the configuration request
    */
    configure: function(room) {
        //send iq to start room configuration
        var config = $iq({to:room,
                          type: "get"}).c("query",
                                          {xmlns: Strophe.NS.MUC_OWNER});
        var stanza = config.tree();
	return this._connection.sendIQ(stanza,
                                       function(){},
                                       function(){});
    },
    /***Function
    Cancel the room configuration
    Parameters:
    (String) room - The multi-user chat room name.
    Returns:
    id - the unique id used to cancel the configuration.
    */
    cancelConfigure: function(room) {
        //send iq to start room configuration
        var config = $iq({to: room,
                          type: "set"})
            .c("query", {xmlns: Strophe.NS.MUC_OWNER})
            .c("x", {xmlns: "jabber:x:data", type: "cancel"});
        var stanza = config.tree();
	return this._connection.sendIQ(stanza,
                                       function(){},
                                       function(){});
    },
    /***Function
    Save a room configuration.
    Parameters:
    (String) room - The multi-user chat room name.
    (Array) configarray - an array of form elements used to configure the room.
    Returns:
    id - the unique id used to save the configuration.
    */
    saveConfiguration: function(room, configarray) {
        var config = $iq({to: room,
                          type: "set"})
            .c("query", {xmlns: Strophe.NS.MUC_OWNER})
            .c("x", {xmlns: "jabber:x:data", type: "submit"});
        for (var i = 0; i >= configarray.length; i++) {
            config.cnode(configarray[i]);
        }
        var stanza = config.tree();
	return this._connection.sendIQ(stanza,
                                       function(){},
                                       function(){});
    },
    /***Function
    Parameters:
    (String) room - The multi-user chat room name.
    Returns:
    id - the unique id used to create the chat room.
    */
    createInstantRoom: function(room) {
        var room = $iq({to: room,
                        type: "set"})
            .c("query", {xmlns: Strophe.NS.MUC_OWNER})
            .c("x", {xmlns: "jabber:x:data",
                     type: "submit"});
        return this._connection.sendIQ(room.tree(),
                                       function() {},
                                       function() {});
    },
    /***
     Set the topic of the chat room.
     Parameters:
     (String) room - The multi-user chat room name.
     (String) topic - Topic message.
     */
    setTopic: function(room, topic) {
        var msg = $msg({to: room,
                        from: this._connection.jid,
                        type: "groupchat"})
            .c("subject", {xmlns: "jabber:client"}).t(topic);
        this._connection.send(msg.tree());
    },
    /***Function
    Changes the role and affiliation of a member of a MUC room.
    The modification can only be done by a room moderator. An error will be
    returned if the user doesn't have permission.
    Parameters:
    (String) room - The multi-user chat room name.
    (String) nick - The nick name of the user to modify.
    (String) role - The new role of the user.
    (String) affiliation - The new affiliation of the user.
    (String) reason - The reason for the change.
    Returns:
    iq - the id of the mode change request.
    */
    modifyUser: function(room, nick, role, affiliation, reason) {
	var item_attrs = {nick: Strophe.escapeNode(nick)};
	if (role !== null)
	{
            item_attrs["role"] = role;
	}
	if (affiliation !== null)
	{
            item_attrs["affiliation"] = affiliation;
	}
        var item = $build("item", item_attrs);
	if (reason !== null)
	{
	    item.cnode(Strophe.xmlElement("reason", reason));
	}
        var room = $iq({to: room,
                        type: "set"})
            .c("query", {xmlns: Strophe.NS.MUC_OWNER}).cnode(item.tree());
        return this._connection.sendIQ(room.tree(),
                                       function() {},
                                       function() {});
    },
    /***Function
    Change the current users nick name.
    Parameters:
    (String) room - The multi-user chat room name.
    (String) user - The new nick name.
    */
    changeNick: function(room, user) {
        var room_nick = this.test_append_nick(room, user);
        var presence = $pres({from: this._connection.jid,
                              to: room_nick})
            .c("x",{xmlns: Strophe.NS.MUC});
        this._connection.send(presence.tree());
    },
    /***Function
    List all chat room available on a server.
    Parameters:
    (String) server - name of chat server.
    (String) handle_cb - Function to call for room list return.
    */
    listRooms: function(server, handle_cb) {
        var iq = $iq({to: server,
                      from: this._connection.jid,
                      type: "get"})
            .c("query",{xmlns: Strophe.NS.DISCO_ITEMS});
        this._connection.sendIQ(iq, handle_cb, function(){});
    },
    test_append_nick: function(room, nick) {
        var room_nick = room;
        if (nick)
        {
            room_nick += "/" + Strophe.escapeNode(nick);
        }
        return room_nick;
    }
});<|endoftext|>


<commit_before>'use strict';

var http   = require('http');
var https  = require('https');
var url    = require('url');
var qs     = require('querystring');
var config = require('./config');

module.exports = function(req, res) {
    var reqUrl = url.parse(req.url),
        query  = qs.parse(reqUrl.query);

    var apiConfig = config[query.api];

    var httpLib = apiConfig.oauth2.port === 443 ? https : http;
    var proxyReq = httpLib.request({
        hostname           : apiConfig.oauth2.hostname,
        port               : apiConfig.oauth2.port,
        path               : apiConfig.oauth2.tokenUrl,
        method             : 'POST',
        rejectUnauthorized : false,
        headers  : {
            'Accept'       : 'application/json',
            'Content-Type' : 'application/x-www-form-urlencoded'
        }
    }, function(proxyRes) {
        var data = '';
        proxyRes.on('data', function(chunk) {
            data += chunk;
        });

        proxyRes.on('end', function() {
            var json = JSON.parse(data);

            res.writeHead(302, {
                Location : 'http://127.0.0.1:9001/'+query.api+'?' + qs.stringify(json)
            });

            res.end();
        });
    });

    proxyReq.on('error', function(e) {
        console.log(e);
    });

    proxyReq.write(qs.stringify({
        grant_type    : 'authorization_code',
        code          : query.code,
        client_id     : query.client_id,
        client_secret : query.client_secret,
        scope         : query.scope,
        state         : Math.random(),
        redirect_uri  : ''
    }));

    proxyReq.end();
};
<commit_msg>Display oauth error responses.<commit_after>'use strict';

var http   = require('http');
var https  = require('https');
var url    = require('url');
var qs     = require('querystring');
var config = require('./config');

module.exports = function(req, res) {
    var reqUrl = url.parse(req.url),
        query  = qs.parse(reqUrl.query);

    var apiConfig = config[query.api];

    var httpLib = apiConfig.oauth2.port === 443 ? https : http;
    var proxyReq = httpLib.request({
        hostname           : apiConfig.oauth2.hostname,
        port               : apiConfig.oauth2.port,
        path               : apiConfig.oauth2.tokenUrl,
        method             : 'POST',
        rejectUnauthorized : false,
        headers  : {
            'Accept'       : 'application/json',
            'Content-Type' : 'application/x-www-form-urlencoded'
        }
    }, function(proxyRes) {
        var data = '';
        proxyRes.on('data', function(chunk) {
            data += chunk;
        });

        proxyRes.on('end', function() {
            try {
                var json = JSON.parse(data);

                res.writeHead(302, {
                    Location : 'http://127.0.0.1:9001/'+query.api+'?' + qs.stringify(json)
                });

            } catch (e) {
                res.write(data);
            }

            res.end();
        });
    });

    proxyReq.on('error', function(e) {
        console.log(e);
    });

    proxyReq.write(qs.stringify({
        grant_type    : 'authorization_code',
        code          : query.code,
        client_id     : query.client_id,
        client_secret : query.client_secret,
        scope         : query.scope,
        state         : Math.random(),
        redirect_uri  : ''
    }));

    proxyReq.end();
};
<|endoftext|>


<commit_before>import { store } from '../persistence/store';

export const SET_BOOLEAN_OPTION = 'SET_BOOLEAN_OPTION';

export function setBooleanOption(option, state) {
  return {
    type: SET_BOOLEAN_OPTION,
    payload: {option, state}
  };
}
<commit_msg>Store options state in local db<commit_after>import { store } from '../persistence/store';

export const SET_BOOLEAN_OPTION = 'SET_BOOLEAN_OPTION';

export function setBooleanOption(option, state) {
  store.set(`settings.${option}`, state).write();

  return {
    type: SET_BOOLEAN_OPTION,
    payload: {option, state}
  };
}
<|endoftext|>


<commit_before>/* eslint-env mocha */

import React from 'react';
import expect from 'expect';
import reactElementToJSXString from './';

class TestComponent extends React.Component {}

describe(`reactElementToJSXString(ReactElement)`, () => {
  it(`reactElementToJSXString(<TestComponent/>)`, () => {
    expect(
      reactElementToJSXString(<TestComponent/>)
    ).toEqual(`<TestComponent />`);
  });

  it(`reactElementToJSXString(React.createElement('div'))`, () => {
    expect(
      reactElementToJSXString(React.createElement('div'))
    ).toEqual(`<div />`);
  });

  it(`reactElementToJSXString(<div/>)`, () => {
    expect(
      reactElementToJSXString(
)
    ).toEqual(`<div />`);
  });

  it(`reactElementToJSXString(<div fn={() => {}}/>)`, () => {
    expect(
      reactElementToJSXString(
 {}}/>)
    ).toEqual(`<div fn={function () {code;}} />`);
  });

  it(`reactElementToJSXString(<div fn={function hello(){}}/>)`, () => {
    expect(
      reactElementToJSXString(
)
    ).toEqual(`<div fn={function () {code;}} />`);
  });

  it(`reactElementToJSXString(<div co={<div a="1" />} />)`, () => {
    expect(
      reactElementToJSXString()
    ).toEqual(`<div co={<div a="1" />} />`);
  });

  it(`reactElementToJSXString(<div re={/^Hello world$/} />)`, () => {
    expect(
      reactElementToJSXString(
)
    ).toEqual(`<div re={/^Hello world$/} />`);
  });

  it(`reactElementToJSXString(<div int={8}/>)`, () => {
    expect(
      reactElementToJSXString(
)
    ).toEqual(`<div int={8} />`);
  });

  it(`reactElementToJSXString(<div obj={{hello: 'world'}}/>)`, () => {
    expect(
      reactElementToJSXString(
)
    ).toEqual(`<div obj={{hello: 'world'}} />`);
  });

  it(`reactElementToJSXString(<div></div>)`, () => {
    expect(
      reactElementToJSXString(

)
    ).toEqual(`<div />`);
  });

  it(`reactElementToJSXString(<div z="3" a="1" b="2"/>)`, () => {
    /* eslint react/jsx-sort-props: 0 */
    expect(
      reactElementToJSXString(
)
    ).toEqual(
`
`);
  });

  it(`reactElementToJSXString(<div a="1">Hello</div>)`, () => {
    expect(
      reactElementToJSXString(
Hello
)
    ).toEqual(
`

  Hello

`);
  });

  it(`reactElementToJSXString(<div a="1" b="5">Hello</div>)`, () => {
    expect(
      reactElementToJSXString(
Hello
)
    ).toEqual(
`

  Hello

`);
  });

  it(`reactElementToJSXString(<div>Hello</div>)`, () => {
    expect(
      reactElementToJSXString(
Hello
)
    ).toEqual(
`

  Hello

`);
  });

  it(`reactElementToJSXString(<div><div>Hello</div></div>)`, () => {
    expect(
      reactElementToJSXString(

Hello

)
    ).toEqual(
`

    Hello

`);
  });

  it(`reactElementToJSXString(<div a="1" b="2"><div>Hello</div></div>)`, () => {
    expect(
      reactElementToJSXString(

Hello

)
    ).toEqual(
`

    Hello

`);
  });

  it(`reactElementToJSXString()`, () => {
    expect(() => {
      reactElementToJSXString();
    }).toThrow('react-element-to-jsx-string: Expected a ReactElement');
  });

  it(`reactElementToJSXString(null)`, () => {
    expect(() => {
      reactElementToJSXString(null);
    }).toThrow('react-element-to-jsx-string: Expected a ReactElement');
  });
});
<commit_msg>test: force using the non main version<commit_after>/* eslint-env mocha */

import React from 'react';
import expect from 'expect';
import reactElementToJSXString from './index';

class TestComponent extends React.Component {}

describe(`reactElementToJSXString(ReactElement)`, () => {
  it(`reactElementToJSXString(<TestComponent/>)`, () => {
    expect(
      reactElementToJSXString(<TestComponent/>)
    ).toEqual(`<TestComponent />`);
  });

  it(`reactElementToJSXString(React.createElement('div'))`, () => {
    expect(
      reactElementToJSXString(React.createElement('div'))
    ).toEqual(`<div />`);
  });

  it(`reactElementToJSXString(<div/>)`, () => {
    expect(
      reactElementToJSXString(
)
    ).toEqual(`<div />`);
  });

  it(`reactElementToJSXString(<div fn={() => {}}/>)`, () => {
    expect(
      reactElementToJSXString(
 {}}/>)
    ).toEqual(`<div fn={function () {code;}} />`);
  });

  it(`reactElementToJSXString(<div fn={function hello(){}}/>)`, () => {
    expect(
      reactElementToJSXString(
)
    ).toEqual(`<div fn={function () {code;}} />`);
  });

  it(`reactElementToJSXString(<div co={<div a="1" />} />)`, () => {
    expect(
      reactElementToJSXString()
    ).toEqual(`<div co={<div a="1" />} />`);
  });

  it(`reactElementToJSXString(<div re={/^Hello world$/} />)`, () => {
    expect(
      reactElementToJSXString(
)
    ).toEqual(`<div re={/^Hello world$/} />`);
  });

  it(`reactElementToJSXString(<div int={8}/>)`, () => {
    expect(
      reactElementToJSXString(
)
    ).toEqual(`<div int={8} />`);
  });

  it(`reactElementToJSXString(<div obj={{hello: 'world'}}/>)`, () => {
    expect(
      reactElementToJSXString(
)
    ).toEqual(`<div obj={{hello: 'world'}} />`);
  });

  it(`reactElementToJSXString(<div></div>)`, () => {
    expect(
      reactElementToJSXString(

)
    ).toEqual(`<div />`);
  });

  it(`reactElementToJSXString(<div z="3" a="1" b="2"/>)`, () => {
    /* eslint react/jsx-sort-props: 0 */
    expect(
      reactElementToJSXString(
)
    ).toEqual(
`
`);
  });

  it(`reactElementToJSXString(<div a="1">Hello</div>)`, () => {
    expect(
      reactElementToJSXString(
Hello
)
    ).toEqual(
`

  Hello

`);
  });

  it(`reactElementToJSXString(<div a="1" b="5">Hello</div>)`, () => {
    expect(
      reactElementToJSXString(
Hello
)
    ).toEqual(
`

  Hello

`);
  });

  it(`reactElementToJSXString(<div>Hello</div>)`, () => {
    expect(
      reactElementToJSXString(
Hello
)
    ).toEqual(
`

  Hello

`);
  });

  it(`reactElementToJSXString(<div><div>Hello</div></div>)`, () => {
    expect(
      reactElementToJSXString(

Hello

)
    ).toEqual(
`

    Hello

`);
  });

  it(`reactElementToJSXString(<div a="1" b="2"><div>Hello</div></div>)`, () => {
    expect(
      reactElementToJSXString(

Hello

)
    ).toEqual(
`

    Hello

`);
  });

  it(`reactElementToJSXString()`, () => {
    expect(() => {
      reactElementToJSXString();
    }).toThrow('react-element-to-jsx-string: Expected a ReactElement');
  });

  it(`reactElementToJSXString(null)`, () => {
    expect(() => {
      reactElementToJSXString(null);
    }).toThrow('react-element-to-jsx-string: Expected a ReactElement');
  });
});
<|endoftext|>


<commit_before>import DS from 'ember-data';
import Ember from 'ember';

export default DS.RESTAdapter.extend({
    host: 'https://api.sandbox.paypal.com',
    namespace: 'v1/payments',

    headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer A0156umLXNQiNinJDcSDmWWPQE12zTCSGw39KfgaNBytboQ"
    },

    /**
     * Build the url.  Good place to log out what is using in url creation.
     * @param type
     * @param id
     * @returns {*}
     */
    buildURL: function(type, id) {
        Ember.Logger.debug('Paypal adapter information:');
        Ember.Logger.debug('  Paypal adapter, type = ' + type);
        Ember.Logger.debug('  Paypal adapter, id = ' + id);
        var url = this._super(type, id);
        Ember.Logger.debug('  Paypal adapter, url = ' + url);
        return url;
    },
    /**
     * Customize type for the url.  Ember pluralizes.  Paypal doesn't want the pluralization
     * here is where we change that.
     *
     * @param type
     * @returns {*}
     */
    pathForType: function(type) {
        //var decamelized = Ember.String.decamelize(type);
        //return Ember.String.pluralize(decamelized);
        return type;
    },
    /**
     * Override createRecord.  Paypal doesn't want the payload wrapped in
     * the type key 'payment'.
     * @param store
     * @param type
     * @param record
     * @returns {*}
     */
    createRecord: function(store, type, record) {
        var data = {};
        var serializer = store.serializerFor(type.typeKey);

        serializer.serializeIntoHash(data, type, record, { includeId: true });

        data = data.payment; //Customization here

        return this.ajax(this.buildURL(type.typeKey), "POST", { data: data });
    }
});
<commit_msg>tightened up source of payment adapter<commit_after>import DS from 'ember-data';
import Ember from 'ember';

export default DS.RESTAdapter.extend({
    host: 'https://api.sandbox.paypal.com',
    namespace: 'v1/payments',

    headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer A015B26BT-UlAK-Ct7scxcKqQerLJhTDW3lQqblgv.Cisps"
    },

    /**
     * Build the url.  Good place to log out what is using in url creation.
     * @param type
     * @param id
     * @returns {*}
     */
    buildURL: function(type, id) {
        Ember.Logger.debug('Paypal adapter information:');
        Ember.Logger.debug('  Paypal adapter, type = ' + type);
        Ember.Logger.debug('  Paypal adapter, id = ' + id);
        var url = this._super(type, id);
        Ember.Logger.debug('  Paypal adapter, url = ' + url);
        return url;
    },
    /**
     * Override to customize the type for the url.  Ember pluralizes by default.  Paypal doesn't want the pluralization
     * here is where we change that.
     *
     * @param type
     * @returns {*}
     */
    pathForType: function(type) {
        //I've commented out the pluralization below.
        //var decamelized = Ember.String.decamelize(type);
        //return Ember.String.pluralize(decamelized);
        return type;
    },
    /**
     * Override createRecord.  Paypal doesn't want the payload wrapped in
     * the type key 'payment'.
     * @param store
     * @param type
     * @param record
     * @returns {*}
     */
    createRecord: function(store, type, record) {
        var data = {};
        var serializer = store.serializerFor(type.typeKey);
        serializer.serializeIntoHash(data, type, record, { includeId: true });
        data = data.payment; //Customization here.  Only send the payment.  Not the wrapped payment.
        return this.ajax(this.buildURL(type.typeKey), "POST", { data: data });
    }

});
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';

import DatePicker from 'src/DatePicker';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/DatePicker.json';

export default class DatePickerExamples extends Component {

    constructor(props) {
        super(props);
    }

    onChangeHandle(value) {
        console.log(value);
    }

    render() {

        return (

DatePicker

                    DatePicker is used to select a single date for an input.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="Basic"/>

                                    DatePicker using the value property to set initial date.

                                <DatePicker value={''}
                                            dateFormat={'YYYY-MM-DD'}
                                            name="date"
                                            autoClose={true}
                                            onChange={this.onChangeHandle}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With dateFormat and placeholder"/>

DatePicker using the dateFormat property to set date
                                    format and using placeholder property to set a default date when no
                                    date choice.

                                <DatePicker name="date"
                                            dateFormat='YYYY/MM/DD'
                                            value='2017/02/03'
                                            autoClose={false}
                                            onChange={this.onChangeHandle}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With maxValue and minValue"/>

DatePicker using the maxValue and minValue
                                    property to set date selectable range.

                                <DatePicker name="date"
                                            dateFormat='YYYY-MM-DD'
                                            maxValue='2020-02-01'
                                            minValue='2017-02-03'
                                            autoClose={false}
                                            onChange={this.onChangeHandle}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With autoClose"/>

Set autoClose property to false for closing date picker after choose a
                                    date.

                                <DatePicker name="date"
                                            dateFormat='YYYY-MM-DD'
                                            maxValue='2020-02-01'
                                            minValue='2017-02-03'
                                            autoClose={false}
                                            onChange={this.onChangeHandle}/>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
};
<commit_msg>update DatePickerExamples<commit_after>import React, {Component, PropTypes} from 'react';

import DatePicker from 'src/DatePicker';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/DatePicker.json';

class DatePickerExamples extends Component {

    constructor(props) {
        super(props);
    }

    onChangeHandler = value => {
        console.log(value);
    };

    render() {

        return (

DatePicker

                    DatePicker is used to select a single date for an input.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="Basic"/>

                                    DatePicker using the value property to set initial date.

                                <DatePicker value={''}
                                            dateFormat={'YYYY-MM-DD'}
                                            name="date"
                                            autoClose={true}
                                            onChange={this.onChangeHandler}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With dateFormat and placeholder"/>

DatePicker using the dateFormat property to set date
                                    format and using placeholder property to set a default date when no
                                    date choice.

                                <DatePicker name="date"
                                            dateFormat='YYYY/MM/DD'
                                            value='2017/02/03'
                                            autoClose={false}
                                            onChange={this.onChangeHandler}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With maxValue and minValue"/>

DatePicker using the maxValue and minValue
                                    property to set date selectable range.

                                <DatePicker name="date"
                                            dateFormat='YYYY-MM-DD'
                                            maxValue='2020-02-01'
                                            minValue='2017-02-03'
                                            autoClose={false}
                                            onChange={this.onChangeHandler}/>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header" title="With autoClose"/>

Set autoClose property to false for closing date picker after choose a
                                    date.

                                <DatePicker name="date"
                                            dateFormat='YYYY-MM-DD'
                                            maxValue='2020-02-01'
                                            minValue='2017-02-03'
                                            autoClose={false}
                                            onChange={this.onChangeHandler}/>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
};

export default DatePickerExamples;<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var Check            = require('../../../models/check');
var CheckEvent       = require('../../../models/checkEvent');
var CheckHourlyStat  = require('../../../models/checkHourlyStat');
var CheckDailyStat   = require('../../../models/checkDailyStat');
var CheckMonthlyStat = require('../../../models/checkMonthlyStat');

/**
 * Check Routes
 */
module.exports = function(app) {

  app.get('/checks', function(req, res, next) {
    var query = {};
    if (req.query.tag) {
      query.tags = req.query.tag;
    }
    Check
    .find(query)
    .sort({ isUp: 1, lastChanged: -1 })
    .exec(function(err, checks) {
      if (err) return next(err);
      res.json(checks);
    });
  });

  app.get('/checks/needingPoll', function(req, res, next) {
    Check
    .needingPoll()
    .select({qos: 0})
    .exec(function(err, checks) {
      if (err) return next(err);
      res.json(checks);
    });
  });

  // check route middleware
  var loadCheck = function(req, res, next) {
    Check
    .find({ _id: req.params.id })
    .select({qos: 0})
    .findOne(function(err, check) {
      if (err) return next(err);
      if (!check) return res.json(404, { error: 'failed to load check ' + req.params.id });
      req.check = check;
      next();
    });
  };

  app.get('/checks/:id', loadCheck, function(req, res, next) {
    res.json(req.check);
  });

  app.get('/checks/:id/pause', loadCheck, function(req, res, next) {
    req.check.togglePause();
    req.check.save(function(err) {
      if (err) return next(new Error('failed to toggle pause on check' + req.params.id));
      new CheckEvent({
        timestamp: new Date(),
        check: req.check,
        tags: req.check.tags,
        message: req.check.isPaused ? 'paused' : 'restarted'
      }).save();
      res.redirect(app.route + '/checks/' + req.params.id);
    });
  });

  app.put('/check/:id/test', function (req, res, next) {
    Check.update({ _id: req.params.id }, { lastTested: new Date() }, function(err, numberAffected) {
      if (err) return next(err);
      res.json({ numberAffected: numberAffected });
    });
  });

  app.get('/checks/:id/stat/:period/:timestamp', loadCheck, function(req, res, next) {
    req.check.getSingleStatForPeriod(req.params.period, new Date(parseInt(req.params.timestamp)), function(err, stat) {
      if (err) return next(err);
      res.json(stat);
    });
  });

  app.get('/checks/:id/stats/:type', loadCheck, function(req, res, next) {
    req.check.getStatsForPeriod(req.params.type, req.query.begin, req.query.end, function(err, stats) {
      if(err) return next(err);
      res.json(stats);
    });
  });

  app.get('/checks/:id/events', function(req, res, next) {
    var query = {
      check: req.params.id,
      timestamp: { $gte: req.query.begin || new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) }
    };
    if (req.query.end) {
      query.timestamp.$lte = req.query.end;
    }
    CheckEvent
    .find(query)
    .sort({ timestamp: -1 })
    .select({tags: 0})
    .limit(100)
    .exec(function(err, events) {
      if (err) return next(err);
      CheckEvent.aggregateEventsByDay(events, function(err, aggregatedEvents) {
        if(err) return next(err);
        res.json(aggregatedEvents);
      });
    });
  });

 app.put('/checks', function(req, res, next) {
   var check = new Check();
   try {
     check.populateFromDirtyCheck(req.body, app.get('pollerCollection'));
     app.emit('populateFromDirtyCheck', check, req.body, check.type);
   } catch (checkException) {
     return next(checkException);
   }
   check.save(function(saveError) {
     if(saveError) return next({status:500, error: saveError});
     res.json(check);
   });
 });

 app.delete('/checks/:id', loadCheck, function (req, res, next) {
  req.check.remove(function(err) {
    if (err) return next(err);
    res.end();
  });
 });

 app.post('/checks/:id', function(req, res, next) {
   Check.findOne({ _id: req.params.id }, function(err, check) {
     if (err) return next({status:500, error: err});
     if (!check) return next({status:404, error: 'failed to load check ' + req.params.id})

     try {
       check.populateFromDirtyCheck(req.body, app.get('pollerCollection'));
       app.emit('populateFromDirtyCheck', check, req.body, check.type);
     } catch (checkException) {
       return next(checkException);
     }
     check.save(function(saveError) {
       if(saveError) return next({status:500, error: saveError});
       res.json(check);
     });
   });
 });
};
<commit_msg>switch put and post<commit_after>/**
 * Module dependencies.
 */

var Check            = require('../../../models/check');
var CheckEvent       = require('../../../models/checkEvent');
var CheckHourlyStat  = require('../../../models/checkHourlyStat');
var CheckDailyStat   = require('../../../models/checkDailyStat');
var CheckMonthlyStat = require('../../../models/checkMonthlyStat');

/**
 * Check Routes
 */
module.exports = function(app) {

  app.get('/checks', function(req, res, next) {
    var query = {};
    if (req.query.tag) {
      query.tags = req.query.tag;
    }
    Check
    .find(query)
    .sort({ isUp: 1, lastChanged: -1 })
    .exec(function(err, checks) {
      if (err) return next(err);
      res.json(checks);
    });
  });

  app.get('/checks/needingPoll', function(req, res, next) {
    Check
    .needingPoll()
    .select({qos: 0})
    .exec(function(err, checks) {
      if (err) return next(err);
      res.json(checks);
    });
  });

  // check route middleware
  var loadCheck = function(req, res, next) {
    Check
    .find({ _id: req.params.id })
    .select({qos: 0})
    .findOne(function(err, check) {
      if (err) return next(err);
      if (!check) return res.json(404, { error: 'failed to load check ' + req.params.id });
      req.check = check;
      next();
    });
  };

  app.get('/checks/:id', loadCheck, function(req, res, next) {
    res.json(req.check);
  });

  app.get('/checks/:id/pause', loadCheck, function(req, res, next) {
    req.check.togglePause();
    req.check.save(function(err) {
      if (err) return next(new Error('failed to toggle pause on check' + req.params.id));
      new CheckEvent({
        timestamp: new Date(),
        check: req.check,
        tags: req.check.tags,
        message: req.check.isPaused ? 'paused' : 'restarted'
      }).save();
      res.redirect(app.route + '/checks/' + req.params.id);
    });
  });

  app.put('/check/:id/test', function (req, res, next) {
    Check.update({ _id: req.params.id }, { lastTested: new Date() }, function(err, numberAffected) {
      if (err) return next(err);
      res.json({ numberAffected: numberAffected });
    });
  });

  app.get('/checks/:id/stat/:period/:timestamp', loadCheck, function(req, res, next) {
    req.check.getSingleStatForPeriod(req.params.period, new Date(parseInt(req.params.timestamp)), function(err, stat) {
      if (err) return next(err);
      res.json(stat);
    });
  });

  app.get('/checks/:id/stats/:type', loadCheck, function(req, res, next) {
    req.check.getStatsForPeriod(req.params.type, req.query.begin, req.query.end, function(err, stats) {
      if(err) return next(err);
      res.json(stats);
    });
  });

  app.get('/checks/:id/events', function(req, res, next) {
    var query = {
      check: req.params.id,
      timestamp: { $gte: req.query.begin || new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) }
    };
    if (req.query.end) {
      query.timestamp.$lte = req.query.end;
    }
    CheckEvent
    .find(query)
    .sort({ timestamp: -1 })
    .select({tags: 0})
    .limit(100)
    .exec(function(err, events) {
      if (err) return next(err);
      CheckEvent.aggregateEventsByDay(events, function(err, aggregatedEvents) {
        if(err) return next(err);
        res.json(aggregatedEvents);
      });
    });
  });

 app.post('/checks', function(req, res, next) {
   var check = new Check();
   try {
     check.populateFromDirtyCheck(req.body, app.get('pollerCollection'));
     app.emit('populateFromDirtyCheck', check, req.body, check.type);
   } catch (checkException) {
     return next(checkException);
   }
   check.save(function(saveError) {
     if(saveError) return next({status:500, error: saveError});
     res.json(check);
   });
 });

 app.delete('/checks/:id', loadCheck, function (req, res, next) {
  req.check.remove(function(err) {
    if (err) return next(err);
    res.end();
  });
 });

 app.put('/checks/:id', function(req, res, next) {
   Check.findOne({ _id: req.params.id }, function(err, check) {
     if (err) return next({status:500, error: err});
     if (!check) return next({status:404, error: 'failed to load check ' + req.params.id})

     try {
       check.populateFromDirtyCheck(req.body, app.get('pollerCollection'));
       app.emit('populateFromDirtyCheck', check, req.body, check.type);
     } catch (checkException) {
       return next(checkException);
     }
     check.save(function(saveError) {
       if(saveError) return next({status:500, error: saveError});
       res.json(check);
     });
   });
 });
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Vincent Petry <pvince81@owncloud.com>
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */

/* global Handlebars */

(function(OCA) {

	var TEMPLATE_FAVORITE_ACTION =
		'' +
		'' +
		'';

	/**
	 * Returns the path to the star image
	 *
	 * @param {boolean} state true if starred, false otherwise
	 * @return {string} path to star image
	 */
	function getStarImage(state) {
		return OC.imagePath('core', state ? 'actions/starred' : 'actions/star');
	}

	/**
	 * Render the star icon with the given state
	 *
	 * @param {boolean} state true if starred, false otherwise
	 * @return {Object} jQuery object
	 */
	function renderStar(state) {
		if (!this._template) {
			this._template = Handlebars.compile(TEMPLATE_FAVORITE_ACTION);
		}
		return this._template({
			isFavorite: state,
			altText: state ? t('core', 'Favorited') : t('core', 'Favorite'),
			imgFile: getStarImage(state)
		});
	}

	/**
	 * Toggle star icon on action element
	 *
	 * @param {Object} action element
	 * @param {boolean} state true if starred, false otherwise
	 */
	function toggleStar($actionEl, state) {
		$actionEl.find('img').attr('src', getStarImage(state));
		$actionEl.toggleClass('permanent', state);
	}

	OCA.Files = OCA.Files || {};

	/**
	 * @namespace OCA.Files.TagsPlugin
	 *
	 * Extends the file actions and file list to include a favorite action icon
	 * and addition "data-tags" and "data-favorite" attributes.
	 */
	OCA.Files.TagsPlugin = {
		name: 'Tags',

		allowedLists: [
			'files',
			'favorites'
		],

		_extendFileActions: function(fileActions) {
			var self = this;
			// register "star" action
			fileActions.registerAction({
				name: 'favorite',
				displayName: 'Favorite',
				mime: 'all',
				permissions: OC.PERMISSION_READ,
				render: function(actionSpec, isDefault, context) {
					var $file = context.$file;
					var isFavorite = $file.data('favorite') === true;
					var $icon = $(renderStar(isFavorite));
					$file.find('td:first>.favorite').replaceWith($icon);
					return $icon;
				},
				actionHandler: function(fileName, context) {
					var $actionEl = context.$file.find('.action-favorite');
					var $file = context.$file;
					var dir = context.dir || context.fileList.getCurrentDirectory();
					var tags = $file.attr('data-tags');
					if (_.isUndefined(tags)) {
						tags = '';
					}
					tags = tags.split('|');
					tags = _.without(tags, '');
					var isFavorite = tags.indexOf(OC.TAG_FAVORITE) >= 0;
					if (isFavorite) {
						// remove tag from list
						tags = _.without(tags, OC.TAG_FAVORITE);
					} else {
						tags.push(OC.TAG_FAVORITE);
					}
					toggleStar($actionEl, !isFavorite);

					self.applyFileTags(
						dir + '/' + fileName,
						tags
					).then(function(result) {
						// read latest state from result
						toggleStar($actionEl, (result.tags.indexOf(OC.TAG_FAVORITE) >= 0));
						$file.attr('data-tags', tags.join('|'));
						$file.attr('data-favorite', !isFavorite);
					});
				}
			});
		},

		_extendFileList: function(fileList) {
			// extend row prototype
			fileList.$el.addClass('has-favorites');
			var oldCreateRow = fileList._createRow;
			fileList._createRow = function(fileData) {
				var $tr = oldCreateRow.apply(this, arguments);
				if (fileData.tags) {
					$tr.attr('data-tags', fileData.tags.join('|'));
					if (fileData.tags.indexOf(OC.TAG_FAVORITE) >= 0) {
						$tr.attr('data-favorite', true);
					}
				}
				$tr.find('td:first').prepend('

');
				return $tr;
			};
		},

		attach: function(fileList) {
			if (this.allowedLists.indexOf(fileList.id) < 0) {
				return;
			}
			this._extendFileActions(fileList.fileActions);
			this._extendFileList(fileList);
		},

		/**
		 * Replaces the given files' tags with the specified ones.
		 *
		 * @param {String} fileName path to the file or folder to tag
		 * @param {Array.<String>} tagNames array of tag names
		 */
		applyFileTags: function(fileName, tagNames) {
			var encodedPath = OC.encodePath(fileName);
			while (encodedPath[0] === '/') {
				encodedPath = encodedPath.substr(1);
			}
			return $.ajax({
				url: OC.generateUrl('/apps/files/api/v1/files/') + encodedPath,
				contentType: 'application/json',
				data: JSON.stringify({
					tags: tagNames || []
				}),
				dataType: 'json',
				type: 'POST'
			});
		}
	};
})(OCA);

OC.Plugins.register('OCA.Files.FileList', OCA.Files.TagsPlugin);

<commit_msg>Force browser to redraw favorite icon<commit_after>/*
 * Copyright (c) 2014 Vincent Petry <pvince81@owncloud.com>
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */

/* global Handlebars */

(function(OCA) {

	var TEMPLATE_FAVORITE_ACTION =
		'' +
		'' +
		'';

	/**
	 * Returns the path to the star image
	 *
	 * @param {boolean} state true if starred, false otherwise
	 * @return {string} path to star image
	 */
	function getStarImage(state) {
		return OC.imagePath('core', state ? 'actions/starred' : 'actions/star');
	}

	/**
	 * Render the star icon with the given state
	 *
	 * @param {boolean} state true if starred, false otherwise
	 * @return {Object} jQuery object
	 */
	function renderStar(state) {
		if (!this._template) {
			this._template = Handlebars.compile(TEMPLATE_FAVORITE_ACTION);
		}
		return this._template({
			isFavorite: state,
			altText: state ? t('core', 'Favorited') : t('core', 'Favorite'),
			imgFile: getStarImage(state)
		});
	}

	/**
	 * Toggle star icon on action element
	 *
	 * @param {Object} action element
	 * @param {boolean} state true if starred, false otherwise
	 */
	function toggleStar($actionEl, state) {
		$actionEl.find('img').attr('src', getStarImage(state));
		$actionEl.hide().show(0); //force Safari to redraw element on src change
		$actionEl.toggleClass('permanent', state);
	}

	OCA.Files = OCA.Files || {};

	/**
	 * @namespace OCA.Files.TagsPlugin
	 *
	 * Extends the file actions and file list to include a favorite action icon
	 * and addition "data-tags" and "data-favorite" attributes.
	 */
	OCA.Files.TagsPlugin = {
		name: 'Tags',

		allowedLists: [
			'files',
			'favorites'
		],

		_extendFileActions: function(fileActions) {
			var self = this;
			// register "star" action
			fileActions.registerAction({
				name: 'favorite',
				displayName: 'Favorite',
				mime: 'all',
				permissions: OC.PERMISSION_READ,
				render: function(actionSpec, isDefault, context) {
					var $file = context.$file;
					var isFavorite = $file.data('favorite') === true;
					var $icon = $(renderStar(isFavorite));
					$file.find('td:first>.favorite').replaceWith($icon);
					return $icon;
				},
				actionHandler: function(fileName, context) {
					var $actionEl = context.$file.find('.action-favorite');
					var $file = context.$file;
					var dir = context.dir || context.fileList.getCurrentDirectory();
					var tags = $file.attr('data-tags');
					if (_.isUndefined(tags)) {
						tags = '';
					}
					tags = tags.split('|');
					tags = _.without(tags, '');
					var isFavorite = tags.indexOf(OC.TAG_FAVORITE) >= 0;
					if (isFavorite) {
						// remove tag from list
						tags = _.without(tags, OC.TAG_FAVORITE);
					} else {
						tags.push(OC.TAG_FAVORITE);
					}
					toggleStar($actionEl, !isFavorite);

					self.applyFileTags(
						dir + '/' + fileName,
						tags
					).then(function(result) {
						// read latest state from result
						toggleStar($actionEl, (result.tags.indexOf(OC.TAG_FAVORITE) >= 0));
						$file.attr('data-tags', tags.join('|'));
						$file.attr('data-favorite', !isFavorite);
					});
				}
			});
		},

		_extendFileList: function(fileList) {
			// extend row prototype
			fileList.$el.addClass('has-favorites');
			var oldCreateRow = fileList._createRow;
			fileList._createRow = function(fileData) {
				var $tr = oldCreateRow.apply(this, arguments);
				if (fileData.tags) {
					$tr.attr('data-tags', fileData.tags.join('|'));
					if (fileData.tags.indexOf(OC.TAG_FAVORITE) >= 0) {
						$tr.attr('data-favorite', true);
					}
				}
				$tr.find('td:first').prepend('

');
				return $tr;
			};
		},

		attach: function(fileList) {
			if (this.allowedLists.indexOf(fileList.id) < 0) {
				return;
			}
			this._extendFileActions(fileList.fileActions);
			this._extendFileList(fileList);
		},

		/**
		 * Replaces the given files' tags with the specified ones.
		 *
		 * @param {String} fileName path to the file or folder to tag
		 * @param {Array.<String>} tagNames array of tag names
		 */
		applyFileTags: function(fileName, tagNames) {
			var encodedPath = OC.encodePath(fileName);
			while (encodedPath[0] === '/') {
				encodedPath = encodedPath.substr(1);
			}
			return $.ajax({
				url: OC.generateUrl('/apps/files/api/v1/files/') + encodedPath,
				contentType: 'application/json',
				data: JSON.stringify({
					tags: tagNames || []
				}),
				dataType: 'json',
				type: 'POST'
			});
		}
	};
})(OCA);

OC.Plugins.register('OCA.Files.FileList', OCA.Files.TagsPlugin);

<|endoftext|>


<commit_before>/*
*	Description: Ghent Trees Application
*	Modified: 10-11-2015
*	Version: 1.0.0
*	Author: Philippe De Pauw - Waterschoot
* 	-----------------------------------------------
*	Ghent Bomen Inventaris API: http://datatank.stad.gent/4/milieuennatuur/bomeninventaris.json
*/

// Anonymous function executed when document loaded
(function() {

	// Describe an App object with own functionalities
	var App = {
		init: function() {
			// Create the services via the corresponding clones
			this._treesInventoryAPI = TreesInventoryAPI;
			this._treesInventoryAPI.init('http://datatank.stad.gent/4/milieuennatuur/bomeninventaris.json');
			// Create the Db context classes via the corresponding clones
			this._treesDbContext = TreesDbContext;
			this._treesDbContext.init('dds.ghent.trees');
			// Call the API
			this.getTreesInventoryFromAPI();
		},
		getTreesInventoryFromAPI: function() {
			var self = this;
			this._treesInventoryAPI.getTreesInventory().then(
				function(data) {
					var treesInventoryOriginal = data.Document.Folder.Placemark;
					var l = 50;//max 4 MB in localstorage
					var treeOriginal = null;
					for(var i = 0; i < l; i++) {
						treeOriginal = treesInventoryOriginal[i];// Get the current tree in the array by index
						self._treesDbContext.addTreeToInventory(treeOriginal);// Add tree to localstorage
					}
				},
				function(error) {

				}
			);
		}
	};

	App.init();// Intialize the application

})();<commit_msg>Add Tree App<commit_after>/*
*	Description: Ghent Trees Application
*	Modified: 10-11-2015
*	Version: 1.0.0
*	Author: Philippe De Pauw - Waterschoot
* 	-----------------------------------------------
*	Ghent Bomen Inventaris API: http://datatank.stad.gent/4/milieuennatuur/bomeninventaris.json
*/

// Anonymous function executed when document loaded
(function() {

	// Describe an App object with own functionalities
	var App = {
		init: function() {
			// Create the services via the corresponding clones
			this._treesInventoryAPI = TreesInventoryAPI;
			this._treesInventoryAPI.init('http://datatank.stad.gent/4/milieuennatuur/bomeninventaris.json');
			// Create the Db context classes via the corresponding clones
			this._treesDbContext = TreesDbContext;
			this._treesDbContext.init('dds.ghent.trees');
			// Call the API
			this.getTreesInventoryFromAPI();
		},
		getTreesInventoryFromAPI: function() {
			var self = this;
			this._treesInventoryAPI.getTreesInventory().then(
				function(data) {
					var treesInventoryOriginal = data.Document.Folder.Placemark;
					var l = 50;//max 4 MB in localstorage
					var treeOriginal = null, tree = null;
					for(var i = 0; i < l; i++) {
						treeOriginal = treesInventoryOriginal[i];// Get the current tree in the array by index
						tree = {
							"ghentid": treeOriginal.ExtendedData.SchemaData.SimpleData[1]['@text'],
							"ghentcode": treeOriginal.ExtendedData.SchemaData.SimpleData[2]['@text'],
							"name": treeOriginal.ExtendedData.SchemaData.SimpleData[3]['@text'],
							"namenl": treeOriginal.ExtendedData.SchemaData.SimpleData[4]['@text'],
							"dimensions": {
								"height": treeOriginal.ExtendedData.SchemaData.SimpleData[5]['@text'],
								"diameter": treeOriginal.ExtendedData.SchemaData.SimpleData[6]['@text']
							},
							"dayofbirth": parseInt(treeOriginal.ExtendedData.SchemaData.SimpleData[7]['@text']),
							"geolocation": {
								"lat": parseFloat(treeOriginal.Point.coordinates['@text'].split(',')[1]),
								"lng": parseFloat(treeOriginal.Point.coordinates['@text'].split(',')[0])
							}
						};
						console.log(tree);
						//self._treesDbContext.addTreeToInventory(tree);// Add tree to localstorage
					}
				},
				function(error) {

				}
			);
		}
	};

	App.init();// Intialize the application

})();<|endoftext|>


<commit_before>import React from "react";

const Timer = () =>
Timer
;

export default Timer;
<commit_msg>Added class, put holding value for better mocking<commit_after>import React from "react";

const Timer = () =>
25:00
;

export default Timer;
<|endoftext|>


<commit_before>/* jshint undef: true, strict:false, trailing:false, unused:false, -W110 */
/* global require, exports, console, process, module, describe, it, expect, jasmine, angular */
angular.module('timon',['indx'])
	.filter('orderObjectBy', function() {
		return function(items, field, reverse) {
		    var filtered = [];
		    angular.forEach(items, function(item) {  filtered.push(item);  });
		    filtered.sort(function (a, b) {
		      return (a[field] > b[field] ? 1 : -1);
		    });
		    if(reverse) filtered.reverse();
		    return filtered;
		};
	}).controller('main', function($scope, client, utils, channels) {

		var store = client.store,
			u = utils, box, diffQs = [],
			sa = function(fn) { return u.safeApply($scope, fn); },
			guid = u.guid();

		var get_user = function(store) {
			var d = u.deferred();
			store.checkLogin().then(function(l) {
				if (l && l.user_metadata) {
					var um = JSON.parse(l.user_metadata);
					if (um && um.name) { return d.resolve(l, um.name); }
				}
				d.resolve(l, l.username);
			}).fail(function(err) { console.error(err); d.reject(); });
			return d.promise();
		};

		$scope._ = _;

		var initialise = function(boxid) {
			// kill previous queries
			if (!(boxid && boxid.length > 0)) { return ; }

			diffQs.map(function(q) { q.stop(); });

			$scope.followers = [];
			$scope.following = {};
			$scope.timeline = {};
			$scope.people = [];
			$scope.test = {};

			store.getBox(boxid).then(function(b) {
				box = b;
				b.standingQuery({ type:'timpost' }, function(message) {
					console.info('new post coming in > ', message);
					sa(function() { $scope.timeline[message.id] = message; });
				}).then(function(diffid) { diffQs.push(diffid); }).fail(function(err) {
					console.error('error setting up standing query for following ', err);
				});
				b.standingQuery({ type:'timfollow' }, function(following) {
					console.info('new following > ', following);
					sa(function() { $scope.following[following.peek('url')] = following; });
				}).then(function(diffid) { diffQs.push(diffid); }).fail(function(err) {
					console.error('error setting up standing query for following ', err);
				});
			}).fail(function(err) {  console.error('error getting box ', err); });

			get_user(store).then(function(login, name) {
				$scope.login = login;
				$scope.name = name;
			});
		};

		$scope.addFollowing = function(url) {
			console.log('adding following url ... ', url);
			var id = 'following-'+url;
			return box.obj(id).set({url:url, followed:new Date(), type:'timfollow'}).save();
		};
		$scope.addPost = function(body) {
			console.log('add post >> ', body);

			var id = 'timpost-'+u.guid(),
				username = $scope.login.username,
				name=  $scope.name,
				d = u.deferred();

			box.obj($scope.login.username).then(function(author) {
				if (!author.peek('name')) {
					author.set({name:name});
					author.save();
				}
				box.obj(id).set({body:body, author:author, created: new Date(), type:'timpost'})
					.save()
					.then(d.resolve)
					.fail(function(err) { console.error('error posting tweet', err); d.reject(); });
			}).fail(function(err) { console.error('error getting author ', err); d.reject(); });

			return d.promise();
		};
		$scope.clearNewPostInput = function() {
			console.log('clearnewpostinput');
			$scope.newpostinput.text = '';
		};
		$scope.closeAddFollowing = function() {
			$("#addFollowingModal").modal('hide');
		};
		$scope.$watch('selected_box', function(boxid) {	initialise(boxid); });

		window.$s = $scope;
		window.store = store;
		window.chan = channels;
	});

console.log('hello hello');<commit_msg>sorted out order bug<commit_after>/* jshint undef: true, strict:false, trailing:false, unused:false, -W110 */
/* global require, exports, console, process, module, describe, it, expect, jasmine, angular */
angular.module('timon',['indx'])
	.filter('orderObjectBy', function() {
		return function(items, field, reverse) {
		    var filtered = [];
		    angular.forEach(items, function(item) { filtered.push(item);  });
		    filtered.sort(function (a, b) {
		      var av = a.peek(field), bv = b.peek(field);
		      if (_.isDate(av)) { av = av.valueOf(); }
		      if (_.isDate(bv)) { bv = bv.valueOf(); }
		      return (av > bv ? 1 : -1);
		    });
		    if(reverse) filtered.reverse();
		    return filtered;
		};
	}).controller('main', function($scope, client, utils, channels) {

		var store = client.store,
			u = utils, box, diffQs = [],
			sa = function(fn) { return u.safeApply($scope, fn); },
			guid = u.guid();

		var get_user = function(store) {
			var d = u.deferred();
			store.checkLogin().then(function(l) {
				if (l && l.user_metadata) {
					var um = JSON.parse(l.user_metadata);
					if (um && um.name) { return d.resolve(l, um.name); }
				}
				d.resolve(l, l.username);
			}).fail(function(err) { console.error(err); d.reject(); });
			return d.promise();
		};

		$scope._ = _;

		var initialise = function(boxid) {
			// kill previous queries
			if (!(boxid && boxid.length > 0)) { return ; }

			diffQs.map(function(q) { q.stop(); });

			$scope.followers = [];
			$scope.following = {};
			$scope.timeline = {};
			$scope.people = [];
			$scope.test = {};

			store.getBox(boxid).then(function(b) {
				box = b;
				b.standingQuery({ type:'timpost' }, function(message) {
					console.info('new post coming in > ', message);
					sa(function() { $scope.timeline[message.id] = message; });
				}).then(function(diffid) { diffQs.push(diffid); }).fail(function(err) {
					console.error('error setting up standing query for following ', err);
				});
				b.standingQuery({ type:'timfollow' }, function(following) {
					console.info('new following > ', following);
					sa(function() { $scope.following[following.peek('url')] = following; });
				}).then(function(diffid) { diffQs.push(diffid); }).fail(function(err) {
					console.error('error setting up standing query for following ', err);
				});
			}).fail(function(err) {  console.error('error getting box ', err); });

			get_user(store).then(function(login, name) {
				$scope.login = login;
				$scope.name = name;
			});
		};

		$scope.addFollowing = function(url) {
			console.log('adding following url ... ', url);
			var id = 'following-'+url;
			return box.obj(id).set({url:url, followed:new Date(), type:'timfollow'}).save();
		};
		$scope.addPost = function(body) {
			console.log('add post >> ', body);

			var id = 'timpost-'+u.guid(),
				username = $scope.login.username,
				name=  $scope.name,
				d = u.deferred();

			box.obj($scope.login.username).then(function(author) {
				if (!author.peek('name')) {
					author.set({name:name});
					author.save();
				}
				box.obj(id).set({body:body, author:author, created: new Date(), type:'timpost'})
					.save()
					.then(d.resolve)
					.fail(function(err) { console.error('error posting tweet', err); d.reject(); });
			}).fail(function(err) { console.error('error getting author ', err); d.reject(); });

			return d.promise();
		};
		$scope.clearNewPostInput = function() {
			console.log('clearnewpostinput');
			$scope.newpostinput.text = '';
		};
		$scope.closeAddFollowing = function() {
			$("#addFollowingModal").modal('hide');
		};
		$scope.$watch('selected_box', function(boxid) {	initialise(boxid); });

		window.$s = $scope;
		window.store = store;
		window.chan = channels;
	});

console.log('hello hello');<|endoftext|>


<commit_before>// @flow
import React, { Component } from "react";

type Props = {
  active: boolean,
  minutes: number
};

type State = {
  time: number,
  active: boolean,
  timerInterval: number
};

class Timer extends Component {
  props: Props;
  state: State;

  constructor(props: Props) {
    super(props);

    this.state = {
      // Time is in seconds
      time: this.props.minutes * 60,
      active: this.props.active,
      timerInterval: this.props.active
        ? setInterval(() => this.reduceTime(), 1000)
        : -1
    };
  }

  componentWillUnmount(): void {
    clearInterval(this.state.timerInterval);
  }

  reduceTime(): void {
    if (this.state.time >= 0) {
      this.setState({ time: this.state.time - 1 });
    }
  }

  render() {
    return (

        {displayTime(this.state.time)}

    );
  }
}

/**
 * Gets time in seconds, returns a formatted string which we'll use to display
 * the timer
 *
 * @export
 * @param {number} time in seconds
 * @returns {string}
 */
export function displayTime(time: number): string {
  const hours = Math.floor(time / 3600);

  const remaining = time - hours * 3600;

  const minutes = Math.floor(remaining / 60);
  const seconds = remaining - minutes * 60;

  if (hours > 0)
    return `${hours}:${zeroPadding(minutes)}:${zeroPadding(seconds)}`;
  return `${zeroPadding(minutes)}:${zeroPadding(seconds)}`;
}

export function zeroPadding(seconds: number): string {
  const secondsString = String(seconds);

  if (secondsString.length > 1) {
    // Basically do nothing
    return secondsString;
  }
  return `0${secondsString}`;
}

export default Timer;
<commit_msg>Active should be optional<commit_after>// @flow
import React, { Component } from "react";

type Props = {
  active?: boolean,
  minutes: number
};

type State = {
  time: number,
  active: boolean,
  timerInterval: number
};

class Timer extends Component {
  props: Props;
  state: State;

  constructor(props: Props) {
    super(props);

    this.state = {
      // Time is in seconds
      time: this.props.minutes * 60,
      active: this.props.active,
      timerInterval: this.props.active
        ? setInterval(() => this.reduceTime(), 1000)
        : -1
    };
  }

  componentWillUnmount(): void {
    clearInterval(this.state.timerInterval);
  }

  reduceTime(): void {
    if (this.state.time >= 0) {
      this.setState({ time: this.state.time - 1 });
    }
  }

  render() {
    return (

        {displayTime(this.state.time)}

    );
  }
}

/**
 * Gets time in seconds, returns a formatted string which we'll use to display
 * the timer
 *
 * @export
 * @param {number} time in seconds
 * @returns {string}
 */
export function displayTime(time: number): string {
  const hours = Math.floor(time / 3600);

  const remaining = time - hours * 3600;

  const minutes = Math.floor(remaining / 60);
  const seconds = remaining - minutes * 60;

  if (hours > 0)
    return `${hours}:${zeroPadding(minutes)}:${zeroPadding(seconds)}`;
  return `${zeroPadding(minutes)}:${zeroPadding(seconds)}`;
}

export function zeroPadding(seconds: number): string {
  const secondsString = String(seconds);

  if (secondsString.length > 1) {
    // Basically do nothing
    return secondsString;
  }
  return `0${secondsString}`;
}

export default Timer;
<|endoftext|>


<commit_before>var React = require('react');
var $ = require('jquery');
var generalUtil = require('../utils/generalUtil');
var badlyNamedUtil = require('../utils/badlyNamedUtil');
var wordTransformUtil = require('../utils/wordTransformUtil');

var getRandomWord = (sentence) => {
  var words = sentence.split(/\s/).filter((item) => {
    return item !== '';
  });
  return generalUtil.getRandomMember(words);
}

var Tweet = React.createClass({
  propTypes: {
    id: React.PropTypes.number.isRequired,
    username: React.PropTypes.string.isRequired,
    avatar_url: React.PropTypes.string.isRequired,
    text: React.PropTypes.string.isRequired,
    timestamp: React.PropTypes.string.isRequired
  },

  getInitialState() {
    return {
      text: generalUtil.normalizeWhitespace(this.props.text)
    };
  },

  componentWillMount() {
    badlyNamedUtil.register(this);
  },

  componentWillUnmount() {
    badlyNamedUtil.unregister(this);
  },

  componentDidUpdate() {
    var container = this.refs.container.getDOMNode();
    $(container).addClass('updated');
    setTimeout(() => {
      $(container).removeClass('updated');
    }, 300);
  },

  swapRandomWord() {
    var sentence = this.state.text;
    var randomWord = getRandomWord(sentence);
    var cleanedWord = randomWord.replace(/^([^\w]|_)+/g, '').replace(/([^\w]|_)+$/g, '');

    var index, tail;
    if (cleanedWord.replace(/\s+/g, '') === '') {
      index = sentence.indexOf(randomWord);
      tail = sentence.substring(index + randomWord.length);
    } else {
      index = sentence.indexOf(cleanedWord);
      tail = sentence.substring(index + cleanedWord.length);
    }
    var head = sentence.substring(0, index);

    wordTransformUtil.betterRandom((word) => {
      this.setState({
        text: head + word + tail
      });
    });
  },

  reset() {
    this.setState(this.getInitialState());
  },

  render() {
    var styles = {
      container: {
        margin: '10px',
        padding: '10px',
        display: 'inline-block',
        width: '22%',
        verticalAlign: 'top'
      },

      timestamp: {
        fontStyle: 'italic'
      },

      avatar: {
        height: '40px',
        marginRight: '20px'
      },

      username: {
        verticalAlign: 'top'
      }
    };

    return (

        {this.props.username}

{this.state.text}

{this.props.timestamp}

        <button onClick={this.reset}>Reset</button>

    );
  }
});

module.exports = Tweet;
<commit_msg>Little prettier timestamps<commit_after>var React = require('react');
var $ = require('jquery');
var generalUtil = require('../utils/generalUtil');
var badlyNamedUtil = require('../utils/badlyNamedUtil');
var wordTransformUtil = require('../utils/wordTransformUtil');

var getRandomWord = (sentence) => {
  var words = sentence.split(/\s/).filter((item) => {
    return item !== '';
  });
  return generalUtil.getRandomMember(words);
}

var Tweet = React.createClass({
  propTypes: {
    id: React.PropTypes.number.isRequired,
    username: React.PropTypes.string.isRequired,
    avatar_url: React.PropTypes.string.isRequired,
    text: React.PropTypes.string.isRequired,
    timestamp: React.PropTypes.string.isRequired
  },

  getInitialState() {
    return {
      text: generalUtil.normalizeWhitespace(this.props.text)
    };
  },

  componentWillMount() {
    badlyNamedUtil.register(this);
  },

  componentWillUnmount() {
    badlyNamedUtil.unregister(this);
  },

  componentDidUpdate() {
    var container = this.refs.container.getDOMNode();
    $(container).addClass('updated');
    setTimeout(() => {
      $(container).removeClass('updated');
    }, 300);
  },

  swapRandomWord() {
    var sentence = this.state.text;
    var randomWord = getRandomWord(sentence);
    var cleanedWord = randomWord.replace(/^([^\w]|_)+/g, '').replace(/([^\w]|_)+$/g, '');

    var index, tail;
    if (cleanedWord.replace(/\s+/g, '') === '') {
      index = sentence.indexOf(randomWord);
      tail = sentence.substring(index + randomWord.length);
    } else {
      index = sentence.indexOf(cleanedWord);
      tail = sentence.substring(index + cleanedWord.length);
    }
    var head = sentence.substring(0, index);

    wordTransformUtil.betterRandom((word) => {
      this.setState({
        text: head + word + tail
      });
    });
  },

  reset() {
    this.setState(this.getInitialState());
  },

  render() {
    var styles = {
      container: {
        margin: '10px',
        padding: '10px',
        display: 'inline-block',
        width: '22%',
        verticalAlign: 'top'
      },

      timestamp: {
        fontStyle: 'italic',
      },

      avatar: {
        height: '40px',
        marginRight: '10px',
        verticalAlign: 'middle'
      },

      username: {
        verticalAlign: 'top',
        textDecoration: 'none',
        color: 'rgb(0, 132, 180)'
      }
    };

    var userLink = `https://twitter.com/${this.props.username}`;
    var date = new Date(Date.parse(this.props.timestamp));
    var timestamp = `${date.toLocaleDateString()} at ${date.toLocaleTimeString()}`

    return (

        @{this.props.username}

{this.state.text}

{timestamp}

        <button onClick={this.reset}>Reset</button>

    );
  }
});

module.exports = Tweet;
<|endoftext|>


<commit_before>/* John McCutchan ========================================= */
console.log('ChatCtrl-on');
app.controller('ChatCtrl', function($scope){ // arg 1 is name of control, arg 2 is function with scope name
})
<commit_msg>added logout<commit_after>/* John McCutchan ========================================= */
console.log('ChatCtrl-on');
app.controller('ChatCtrl', function($location, $scope, $rootScope, PostServices, LoginServices, userUID){ // arg 1 is name of control, arg 2 is function with scope name
  $scope.name = $rootScope.name;
  //get uid and assign it to $scope
  $scope.uid = userUID.uid()
  console.log("$scope UID: ",$scope.uid)
  //assign local $scope uid to global scope
  $rootScope.uid = $scope.uid
  console.log("$rootScope UID: ",$rootScope.uid)
  //check to see name is global
  console.log("Test2: ", $rootScope.name)
  //build chat object
  $scope.chat = {
    "uid":$rootScope.uid,
    "name": $scope.name,
    "conversation": $scope.conversation,
  }
  //function to post chat to firebase
  $scope.chatSend = ()=> {
    PostServices
    .chatSend($scope.chat)
  }
  $scope.logout = ()=> {
    LoginServices
    .logout()
  }
})
<|endoftext|>


<commit_before>'use strict';

/*================================================================
  #MAIN
  ================================================================*/

angular
  .module(appName)
  .controller('MainController', MainController);

MainController.$inject = [
  '$scope', '$http', '$log', // angular core
  'localStorageService', 'hotkeys', // third party
  'appConstant', 'skillService', 'keyValue', 'statService' // app
];

function MainController($scope, $http, $log, localStorageService, hotkeys, appConstant, skillService, keyValue, statService) {
  var imgPath = appConstant.imgPath;
  var appSkillDataName = appConstant.appSkillDataName;

  var vm = this;

  // gameStage
  // - start
  // - over
  vm.gameStage = 'start'; // unused
  vm.key = keyValue;
  vm.stats = statService.get();
  vm.invokedOrbs = ['', '', '']; // starter key pressed
  vm.skills = localStorageService.get(appSkillDataName); // null
  vm.nSkill = 0;
  vm.targetedSkill = null;
  vm.invokedSkills = [null, null]; // only 2 skills

  /* ================================================================ PRIVATE - HELPER
  */

  function hasNoInvokedSkill() {
    return vm.invokedSkills[0] === null;
  }

  // unused
  function hasOneInvokedSkill() {
    if (vm.invokedSkills[0] !== null &&
      vm.invokedSkills[1] === null) {
      return true;

    } else {
      return false;
    }
  }

  function updateNPressedPerSkill() {
    if (vm.stats.nSkillInvoked > 0) {
      vm.stats.nPressedPerSkill = vm.stats.nPressed / vm.stats.nSkillInvoked;
    }
  }

  function updateNPressedPerTargetedSkill() {
    if (vm.stats.nTargetedSkillInvoked > 0) {
      vm.stats.nPressedPerTargetedSkill = vm.stats.nPressed / vm.stats.nTargetedSkillInvoked;
    }
  }

  function getTargetedSkill() {
    var randomSkillIdx = _.random(0, vm.nSkill - 1);
    var randomSkill = vm.skills[randomSkillIdx];
    var randomSkillKey = randomSkill.key;

    // first generate targeted skill (no invoked skill)
    if (hasNoInvokedSkill()) {
      return randomSkill;

    // has one invoked skill and
    // otherwise
    } else {
      if (randomSkill.key === vm.invokedSkills[0].key) {
        $log.log('generated skill is duplicate with latest invoked skill, it will generate new one');

        return getTargetedSkill();

      } else {
        return randomSkill
      }
    }

    return randomSkill;
  }

  function updateInvokedSkills(skill) {
    // first invoked skill
    if (hasNoInvokedSkill()) {
      vm.invokedSkills[0] = skill;

    // second invoked skill and
    // otherwise
    } else {
      vm.invokedSkills[1] = vm.invokedSkills[0];
      vm.invokedSkills[0] = skill;
    }
  }

  function orderAllSkillOrbs() {
    angular.forEach(vm.skills, function (val, key) {
      vm.skills[key].orbs = _.sortBy(val.orbs);
    });
  }

  function initSkillData() {
    if (! vm.skills) {
      $log.log('not found skill\'s data in local storage');

      skillService.get().then(function (res) {
        var skills = res.data;
        var skillsJson = angular.toJson(skills);

        vm.skills = skills
        vm.nSkill = vm.skills.length;

        setTargetedSkill();
        orderAllSkillOrbs();

        localStorageService.set(appSkillDataName, skillsJson); // save skill's data into local storage
      });

    } else {

      vm.skills = JSON.parse(vm.skills);
      vm.nSkill = vm.skills.length;

      setTargetedSkill();
      orderAllSkillOrbs();
    }

    $log.debug('vm.skills', vm.skills);
    $log.debug('vm.nSkill', vm.nSkill);
  }

  function setTargetedSkill() {
    vm.targetedSkill = getTargetedSkill();

    $log.debug('vm.targetedSkill', vm.targetedSkill);
  }

  // have to order it first
  // compare one deeped array only
  //
  // http://stackoverflow.com/questions/28947253/sort-array-with-lodash-by-value-integer
  // http://stackoverflow.com/questions/29951293/using-lodash-to-compare-arrays
  function isSameOrbArr(orderedArr1, orderedArr2) {
    return _.isEqual(orderedArr1, orderedArr2);
  }

  function getSpellCssClass(idx) {
    var skill = vm.invokedSkills[idx];
    var cssClass = (skill) ? vm.getSkillCssClass(skill.key) : '';

    return cssClass;
  }

  function validateSkill(invokedSkill) {
    if (invokedSkill) {
      if (invokedSkill.key === vm.targetedSkill.key) {
        $log.log('valid skill');

        // generate new targeted skill
        setTargetedSkill();

        // update stat
        vm.stats.nStage++;
        vm.stats.nTargetedSkillInvoked++;
        updateNPressedPerTargetedSkill();

      } else {
        $log.log('not valid skill');
      }
    }
  }

  /* ================================================================ PUBLIC - HELPER & INIT
  */

  // unused
  vm.getSkillImgPath = function (fileName) {
    return imgPath + '/' + fileName;
  };

  vm.getSkillCssClass = function (skillKey) {
    return 'skill-' + skillKey;
  };

  vm.getOrbClass = function (orb) {
    var orbClass = 'orb-quas';

    switch (orb) {
      case 'q':
        orbClass = 'orb-quas';
        break;
      case 'w':
        orbClass = 'orb-wex';
        break;
      case 'e':
        orbClass = 'orb-exort';
        break;
    }

    return orbClass;
  }

  vm.getSpell1CssClass = function () {
    return getSpellCssClass(0);
  }

  vm.getSpell2CssClass = function () {
    return getSpellCssClass(1);
  }

  vm.init = function () {
    initSkillData();
  }

  /* ================================================================ PUBLIC - EVENT
  */

  vm.updateKeyPress = function (key) {
    // update invoked orbs
    vm.invokedOrbs.shift(); // remove zero index
    vm.invokedOrbs.push(key); // add new key

    // update stat
    vm.stats.nPressed++;
    vm.stats.latestKey = key;
    updateNPressedPerSkill();
  }

  vm.invokeSkill = function () {
    var loopFlag = true;
    var invokedSkill = null;
    var invokedOrbs = _.sortBy(vm.invokedOrbs);

    angular.forEach(vm.skills, function (skill, key) {
      if (loopFlag) {
        if (isSameOrbArr(invokedOrbs, skill.orbs)) {
          invokedSkill = skill;
          loopFlag = false; // break
        }
      }
    });

    var invokedSkill1Key = (vm.invokedSkills[0]) ? vm.invokedSkills[0].key : '';
    var invokedSkill2Key = (vm.invokedSkills[1]) ? vm.invokedSkills[0].key : '';

    if (invokedSkill && invokedSkill.key) {
      if (invokedSkill.key !== invokedSkill1Key &&
        invokedSkill.key !== invokedSkill2Key) {
        $log.log('valid orbs');

        // update invoked skill
        updateInvokedSkills(invokedSkill);

        // update stat
        vm.stats.nSkillInvoked++;
        updateNPressedPerSkill();

      } else {
        $log.log('skill already invoked');
      }

    } else {
      // impossible
      $log.log('not valid orbs');
    }

    // update stat
    vm.stats.latestKey = vm.key.invoke;
  }

  vm.validateSkill1 = function () {
    validateSkill(vm.invokedSkills[0]);

    // update stat
    vm.stats.latestKey = vm.key.spell1;
  }

  vm.validateSkill2 = function () {
    validateSkill(vm.invokedSkills[1]);

    // update stat
    vm.stats.latestKey = vm.key.spell2;
  }

  vm.resetGame = function () {
    $log.log('statService.reset()', statService.reset());
    vm.stats = statService.reset();
    vm.invokedSkills = [null, null];
    vm.invokedOrbs = ['', '', ''];

    setTargetedSkill();
  }

  /*================================================================ PUBLIC - KEY BINDING
  */

  hotkeys.add({
    combo: vm.key.quas,
    description: 'press ' + vm.key.quas,
    callback: function() {
      vm.updateKeyPress(vm.key.quas);
    }
  });

  hotkeys.add({
    combo: vm.key.wex,
    description: 'press ' + vm.key.wex,
    callback: function() {
      vm.updateKeyPress(vm.key.wex);
    }
  });

  hotkeys.add({
    combo: vm.key.exort,
    description: 'press ' + vm.key.exort,
    callback: function() {
      vm.updateKeyPress(vm.key.exort);
    }
  });

  hotkeys.add({
    combo: vm.key.invoke,
    description: 'press ' + vm.key.invoke,
    callback: function() {
      vm.invokeSkill();
    }
  });

  hotkeys.add({
    combo: vm.key.spell1,
    description: 'press ' + vm.key.spell1,
    callback: function() {
      vm.validateSkill1();
    }
  });

  hotkeys.add({
    combo: vm.key.spell2,
    description: 'press ' + vm.key.spell2,
    callback: function() {
      vm.validateSkill2();
    }
  });
}
<commit_msg>Use named functions instead of passing an anonymous function in as a callback<commit_after>'use strict';

/*================================================================
  #MAIN
  ================================================================*/

angular
  .module(appName)
  .controller('MainController', MainController);

MainController.$inject = [
  '$scope', '$http', '$log', // angular core
  'localStorageService', 'hotkeys', // third party
  'appConstant', 'skillService', 'keyValue', 'statService' // app
];

function MainController($scope, $http, $log, localStorageService, hotkeys, appConstant, skillService, keyValue, statService) {
  var imgPath = appConstant.imgPath;
  var appSkillDataName = appConstant.appSkillDataName;

  var vm = this;

  // gameStage
  // - start
  // - over
  vm.gameStage = 'start'; // unused
  vm.key = keyValue;
  vm.stats = statService.get();
  vm.invokedOrbs = ['', '', '']; // starter key pressed
  vm.skills = localStorageService.get(appSkillDataName); // null
  vm.nSkill = 0;
  vm.targetedSkill = null;
  vm.invokedSkills = [null, null]; // only 2 skills

  // private - helper
  vm.hasNoInvokedSkill = hasNoInvokedSkill;
  vm.hasOneInvokedSkill = hasOneInvokedSkill;
  vm.updateNPressedPerSkill = updateNPressedPerSkill;
  vm.updateNPressedPerTargetedSkill = updateNPressedPerTargetedSkill;
  vm.getTargetedSkill = getTargetedSkill;
  vm.updateInvokedSkills = updateInvokedSkills;
  vm.orderAllSkillOrbs = orderAllSkillOrbs;
  vm.initSkillData = initSkillData;
  vm.setTargetedSkill = setTargetedSkill;
  vm.isSameOrbArr = isSameOrbArr;
  vm.getSpellCssClass = getSpellCssClass;
  vm.validateSkill = validateSkill;

  // public - helper & init
  vm.getSkillImgPath = getSkillImgPath
  vm.getSkillCssClass = getSkillCssClass;
  vm.getOrbClass = getOrbClass;
  vm.getSpell1CssClass = getSpell1CssClass;
  vm.getSpell2CssClass = getSpell2CssClass;
  vm.init = init;

  // public - event
  vm.updateKeyPress = updateKeyPress;
  vm.invokeSkill = invokeSkill;
  vm.validateSkill1 = validateSkill1;
  vm.validateSkill2 = validateSkill2;
  vm.resetGame = resetGame;

  /* ================================================================ PRIVATE - HELPER
  */

  function hasNoInvokedSkill() {
    return vm.invokedSkills[0] === null;
  }

  // unused
  function hasOneInvokedSkill() {
    if (vm.invokedSkills[0] !== null &&
      vm.invokedSkills[1] === null) {
      return true;

    } else {
      return false;
    }
  }

  function updateNPressedPerSkill() {
    if (vm.stats.nSkillInvoked > 0) {
      vm.stats.nPressedPerSkill = vm.stats.nPressed / vm.stats.nSkillInvoked;
    }
  }

  function updateNPressedPerTargetedSkill() {
    if (vm.stats.nTargetedSkillInvoked > 0) {
      vm.stats.nPressedPerTargetedSkill = vm.stats.nPressed / vm.stats.nTargetedSkillInvoked;
    }
  }

  function getTargetedSkill() {
    var randomSkillIdx = _.random(0, vm.nSkill - 1);
    var randomSkill = vm.skills[randomSkillIdx];
    var randomSkillKey = randomSkill.key;

    // first generate targeted skill (no invoked skill)
    if (hasNoInvokedSkill()) {
      return randomSkill;

    // has one invoked skill and
    // otherwise
    } else {
      if (randomSkill.key === vm.invokedSkills[0].key) {
        $log.log('generated skill is duplicate with latest invoked skill, it will generate new one');

        return getTargetedSkill();

      } else {
        return randomSkill
      }
    }

    return randomSkill;
  }

  function updateInvokedSkills(skill) {
    // first invoked skill
    if (hasNoInvokedSkill()) {
      vm.invokedSkills[0] = skill;

    // second invoked skill and
    // otherwise
    } else {
      vm.invokedSkills[1] = vm.invokedSkills[0];
      vm.invokedSkills[0] = skill;
    }
  }

  function orderAllSkillOrbs() {
    angular.forEach(vm.skills, function (val, key) {
      vm.skills[key].orbs = _.sortBy(val.orbs);
    });
  }

  function initSkillData() {
    if (! vm.skills) {
      $log.log('not found skill\'s data in local storage');

      skillService.get().then(function (res) {
        var skills = res.data;
        var skillsJson = angular.toJson(skills);

        vm.skills = skills
        vm.nSkill = vm.skills.length;

        setTargetedSkill();
        orderAllSkillOrbs();

        localStorageService.set(appSkillDataName, skillsJson); // save skill's data into local storage
      });

    } else {

      vm.skills = JSON.parse(vm.skills);
      vm.nSkill = vm.skills.length;

      setTargetedSkill();
      orderAllSkillOrbs();
    }

    $log.debug('vm.skills', vm.skills);
    $log.debug('vm.nSkill', vm.nSkill);
  }

  function setTargetedSkill() {
    vm.targetedSkill = getTargetedSkill();

    $log.debug('vm.targetedSkill', vm.targetedSkill);
  }

  // have to order it first
  // compare one deeped array only
  //
  // http://stackoverflow.com/questions/28947253/sort-array-with-lodash-by-value-integer
  // http://stackoverflow.com/questions/29951293/using-lodash-to-compare-arrays
  function isSameOrbArr(orderedArr1, orderedArr2) {
    return _.isEqual(orderedArr1, orderedArr2);
  }

  function getSpellCssClass(idx) {
    var skill = vm.invokedSkills[idx];
    var cssClass = (skill) ? vm.getSkillCssClass(skill.key) : '';

    return cssClass;
  }

  function validateSkill(invokedSkill) {
    if (invokedSkill) {
      if (invokedSkill.key === vm.targetedSkill.key) {
        $log.log('valid skill');

        // generate new targeted skill
        setTargetedSkill();

        // update stat
        vm.stats.nStage++;
        vm.stats.nTargetedSkillInvoked++;
        updateNPressedPerTargetedSkill();

      } else {
        $log.log('not valid skill');
      }
    }
  }

  /* ================================================================ PUBLIC - HELPER & INIT
  */

  // unused
  function getSkillImgPath(fileName) {
    return imgPath + '/' + fileName;
  };

  function getSkillCssClass(skillKey) {
    return 'skill-' + skillKey;
  };

  function getOrbClass(orb) {
    var orbClass = 'orb-quas';

    switch (orb) {
      case 'q':
        orbClass = 'orb-quas';
        break;
      case 'w':
        orbClass = 'orb-wex';
        break;
      case 'e':
        orbClass = 'orb-exort';
        break;
    }

    return orbClass;
  }

  function getSpell1CssClass() {
    return getSpellCssClass(0);
  }

  function getSpell2CssClass() {
    return getSpellCssClass(1);
  }

  function init() {
    initSkillData();
  }

  /* ================================================================ PUBLIC - EVENT
  */

  function updateKeyPress(key) {
    // update invoked orbs
    vm.invokedOrbs.shift(); // remove zero index
    vm.invokedOrbs.push(key); // add new key

    // update stat
    vm.stats.nPressed++;
    vm.stats.latestKey = key;
    updateNPressedPerSkill();
  }

  function invokeSkill() {
    var loopFlag = true;
    var invokedSkill = null;
    var invokedOrbs = _.sortBy(vm.invokedOrbs);

    angular.forEach(vm.skills, function (skill, key) {
      if (loopFlag) {
        if (isSameOrbArr(invokedOrbs, skill.orbs)) {
          invokedSkill = skill;
          loopFlag = false; // break
        }
      }
    });

    var invokedSkill1Key = (vm.invokedSkills[0]) ? vm.invokedSkills[0].key : '';
    var invokedSkill2Key = (vm.invokedSkills[1]) ? vm.invokedSkills[0].key : '';

    if (invokedSkill && invokedSkill.key) {
      if (invokedSkill.key !== invokedSkill1Key &&
        invokedSkill.key !== invokedSkill2Key) {
        $log.log('valid orbs');

        // update invoked skill
        updateInvokedSkills(invokedSkill);

        // update stat
        vm.stats.nSkillInvoked++;
        updateNPressedPerSkill();

      } else {
        $log.log('skill already invoked');
      }

    } else {
      // impossible
      $log.log('not valid orbs');
    }

    // update stat
    vm.stats.latestKey = vm.key.invoke;
  }

  function validateSkill1() {
    validateSkill(vm.invokedSkills[0]);

    // update stat
    vm.stats.latestKey = vm.key.spell1;
  }

  function validateSkill2() {
    validateSkill(vm.invokedSkills[1]);

    // update stat
    vm.stats.latestKey = vm.key.spell2;
  }

  function resetGame() {
    $log.log('statService.reset()', statService.reset());
    vm.stats = statService.reset();
    vm.invokedSkills = [null, null];
    vm.invokedOrbs = ['', '', ''];

    setTargetedSkill();
  }

  /*================================================================ PUBLIC - KEY BINDING
  */

  hotkeys.add({
    combo: vm.key.quas,
    description: 'press ' + vm.key.quas,
    callback: function() {
      vm.updateKeyPress(vm.key.quas);
    }
  });

  hotkeys.add({
    combo: vm.key.wex,
    description: 'press ' + vm.key.wex,
    callback: function() {
      vm.updateKeyPress(vm.key.wex);
    }
  });

  hotkeys.add({
    combo: vm.key.exort,
    description: 'press ' + vm.key.exort,
    callback: function() {
      vm.updateKeyPress(vm.key.exort);
    }
  });

  hotkeys.add({
    combo: vm.key.invoke,
    description: 'press ' + vm.key.invoke,
    callback: function() {
      vm.invokeSkill();
    }
  });

  hotkeys.add({
    combo: vm.key.spell1,
    description: 'press ' + vm.key.spell1,
    callback: function() {
      vm.validateSkill1();
    }
  });

  hotkeys.add({
    combo: vm.key.spell2,
    description: 'press ' + vm.key.spell2,
    callback: function() {
      vm.validateSkill2();
    }
  });
}
<|endoftext|>